-
-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathmod.rs
935 lines (820 loc) · 30.4 KB
/
mod.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
use super::{NSComparisonResult, NSRange};
use crate::core::Arc;
use crate::objc::{Class, ClassType, NSObject, NSUInteger, Sel, BOOL};
use std::{cmp::Ordering, fmt, os::raw::c_char, ptr, slice, str};
#[macro_use]
mod macros;
mod encoding;
pub use encoding::*;
/// Returns the selector with a given name.
///
/// If the string cannot be converted to UTF-8 (this should be only due to
/// insufficient memory), this returns [`None`].
///
/// Use this function if you want your code to look more like Objective-C.
/// Otherwise, the [`to_selector`](struct.NSString.html#method.to_selector)
/// method should be preferred.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/1395294-nsselectorfromstring).
#[inline]
#[allow(non_snake_case)]
pub fn NSSelectorFromString(string: &NSString) -> Option<Sel> {
extern "C" {
fn NSSelectorFromString(string: &NSString) -> Option<Sel>;
}
unsafe { NSSelectorFromString(string) }
}
objc_subclass! {
/// A static, plain-text Unicode string object.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring).
pub class NSString<'data>: NSObject<'data>;
}
impl Default for &NSString<'_> {
#[inline]
fn default() -> Self {
ns_string!("")
}
}
impl PartialEq for NSString<'_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
unsafe { _msg_send_any_cached![self, isEqualToString: other => BOOL] }.into()
}
}
impl Eq for NSString<'_> {}
impl PartialOrd for NSString<'_> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for NSString<'_> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
self.compare(other).into()
}
}
impl PartialEq<str> for NSString<'_> {
fn eq(&self, other: &str) -> bool {
// SAFETY: This instance is not mutated while the UTF-16 slice exists.
if let Some(this) = unsafe { self.as_utf16() } {
let mut this_iter = this.iter();
let mut other_iter = other.encode_utf16();
loop {
match (this_iter.next(), other_iter.next()) {
(Some(&this), Some(other)) if this == other => continue,
(None, None) => return true,
(_, _) => return false,
}
}
} else {
// If the string is not UTF-16, then it is UTF-8 (or some other
// encoding?).
// SAFETY: `this` is short-lived.
let this = unsafe { self.to_str() };
this == other
}
}
}
impl PartialEq<&str> for NSString<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
*self == **other
}
}
impl PartialEq<NSString<'_>> for str {
#[inline]
fn eq(&self, other: &NSString) -> bool {
other == self
}
}
impl PartialEq<NSString<'_>> for &str {
#[inline]
fn eq(&self, other: &NSString) -> bool {
other == self
}
}
impl PartialOrd<str> for NSString<'_> {
fn partial_cmp(&self, other: &str) -> Option<Ordering> {
// SAFETY: This instance is not mutated while the UTF-16 slice exists.
if let Some(this) = unsafe { self.as_utf16() } {
let mut this_iter = this.iter();
let mut other_iter = other.encode_utf16();
loop {
match (this_iter.next(), other_iter.next()) {
(Some(&this), Some(other)) => match this.cmp(&other) {
Ordering::Equal => continue,
ord => return Some(ord),
},
(Some(_), None) => return Some(Ordering::Greater),
(None, Some(_)) => return Some(Ordering::Less),
(None, None) => return Some(Ordering::Equal),
}
}
} else {
// If the string is not UTF-16, then it is UTF-8 (or some other
// encoding?).
// SAFETY: `this` is short-lived.
let this = unsafe { self.to_str() };
Some(this.cmp(other))
}
}
}
impl PartialOrd<&str> for NSString<'_> {
#[inline]
fn partial_cmp(&self, other: &&str) -> Option<Ordering> {
self.partial_cmp(*other)
}
}
impl PartialOrd<NSString<'_>> for str {
#[inline]
fn partial_cmp(&self, other: &NSString) -> Option<Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl PartialOrd<NSString<'_>> for &str {
#[inline]
fn partial_cmp(&self, other: &NSString) -> Option<Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl From<&str> for Arc<NSString<'_>> {
#[inline]
fn from(s: &str) -> Self {
NSString::from_str(s)
}
}
impl From<&mut str> for Arc<NSString<'_>> {
#[inline]
fn from(s: &mut str) -> Self {
NSString::from_str(s)
}
}
impl From<NSRange> for Arc<NSString<'_>> {
#[inline]
fn from(range: NSRange) -> Self {
NSString::from_nsrange(range)
}
}
impl fmt::Debug for NSString<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// SAFETY: The lifetime of `str` is very short.
let str = unsafe { self.to_str() };
str.fmt(f)
}
}
impl fmt::Display for NSString<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
// SAFETY: The lifetime of `str` is very short.
let str = unsafe { self.to_str() };
str.fmt(f)
}
}
/// Getting available encodings.
impl NSString<'_> {
/// Returns a slice containing all supported encodings.
///
/// The first time this is called, one pass is done to determine the length
/// of the slice. The slice is then cached for subsequent calls.
#[inline]
#[doc(alias = "availableStringEncodings")]
pub fn available_encodings_slice() -> &'static [NSStringEncoding] {
use std::sync::atomic::{AtomicPtr, AtomicUsize, Ordering};
static CACHED: (AtomicPtr<NSStringEncoding>, AtomicUsize) = (
AtomicPtr::new(ptr::null_mut()),
AtomicUsize::new(0), // count
);
#[cold]
fn slow_path() -> &'static [NSStringEncoding] {
let start = NSString::available_encodings_ptr();
let mut current = start;
let mut count = 0;
unsafe {
// The end of the buffer is marked by a 0 encoding.
while (*current).0 != 0 {
count += 1;
current = current.add(1);
}
}
// The pointer must be stored second so that the fast path does not
// read a length of 0.
//
// This is to prevent:
// A: store ptr
// B: read ptr
// B: read count
// A: store count
CACHED.1.store(count, Ordering::Release);
CACHED.0.store(start as *mut _, Ordering::Release);
unsafe { slice::from_raw_parts(start, count) }
}
let cached_ptr = CACHED.0.load(Ordering::Acquire);
if !cached_ptr.is_null() {
let count = CACHED.1.load(Ordering::Acquire);
return unsafe { slice::from_raw_parts(cached_ptr, count) };
}
slow_path()
}
/// Returns an iterator over all supported encodings.
///
/// Unlike [`available_encodings_slice`](Self::available_encodings_slice),
/// this is implemented lazily and does not perform caching.
#[inline]
#[doc(alias = "availableStringEncodings")]
pub fn available_encodings_iter() -> impl Iterator<Item = NSStringEncoding> {
#[repr(transparent)]
struct Iter(*const NSStringEncoding);
unsafe impl Send for Iter {}
unsafe impl Sync for Iter {}
impl Iterator for Iter {
type Item = NSStringEncoding;
#[inline]
fn next(&mut self) -> Option<NSStringEncoding> {
let encoding = unsafe { *self.0 };
if encoding.0 == 0 {
None
} else {
unsafe { self.0 = self.0.add(1) };
Some(encoding)
}
}
}
// No more encodings are emitted after `None`.
impl std::iter::FusedIterator for Iter {}
Iter(Self::available_encodings_ptr())
}
/// Returns a pointer to a buffer containing all supported encodings.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1417579-availablestringencodings).
#[inline]
#[doc(alias = "availableStringEncodings")]
pub fn available_encodings_ptr() -> *const NSStringEncoding {
unsafe { _msg_send_any![Self::class(), availableStringEncodings] }
}
/// Returns the number of supported encodings.
///
/// The first time this is called, one pass is done to determine the number
/// of encodings. The count is then cached for subsequent calls. This shares
/// the same cache as
/// [`available_encodings_slice`](Self::available_encodings_slice).
#[inline]
#[doc(alias = "availableStringEncodings")]
pub fn available_encodings_count() -> usize {
Self::available_encodings_slice().len()
}
}
impl<'data> NSString<'data> {
// Shared non-inlined `from_str` implementation.
//
// This allows for reducing the code size of the final binary.
unsafe fn _from_str(s: &str, class: &Class) -> Arc<Self> {
let value: Arc<Self> = class.alloc();
#[allow(clashing_extern_declarations)]
extern "C" {
fn objc_msgSend(
obj: Arc<NSString>,
sel: Sel,
bytes: *const u8,
length: NSUInteger,
encoding: NSStringEncoding,
) -> Arc<NSString>;
}
let obj = value;
let sel = selector!(initWithBytes:length:encoding:);
let bytes = s.as_ptr();
let length = s.len();
let encoding = NSStringEncoding::UTF8;
objc_msgSend(obj, sel, bytes, length, encoding)
}
/// Creates an immutable string object from copying a slice.
#[inline]
#[doc(alias = "initWithBytes")]
#[doc(alias = "initWithBytes:length:encoding:")]
pub fn from_str(s: &str) -> Arc<Self> {
unsafe { Self::_from_str(s, Self::class()) }
}
/// Creates an immutable string object without copying a slice.
///
/// # Safety
///
/// The returned string object or its clones must not outlive the referenced
/// string slice.
#[doc(alias = "initWithBytesNoCopy")]
#[doc(alias = "initWithBytesNoCopy:length:encoding:freeWhenDone:")]
pub fn from_str_no_copy(s: &'data str) -> Arc<Self> {
let value: Arc<Self> = unsafe { Self::class().alloc() };
#[allow(clashing_extern_declarations)]
extern "C" {
fn objc_msgSend<'data>(
obj: Arc<NSString<'data>>,
sel: Sel,
bytes: *const u8,
length: NSUInteger,
encoding: NSStringEncoding,
free_when_done: BOOL,
) -> Arc<NSString<'data>>;
}
let obj = value;
let sel = selector!(initWithBytesNoCopy:length:encoding:freeWhenDone:);
let bytes = s.as_ptr();
let length = s.len();
let encoding = NSStringEncoding::UTF8;
let free_when_done = BOOL::NO;
unsafe { objc_msgSend(obj, sel, bytes, length, encoding, free_when_done) }
}
/// Returns a string representation of `range`.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/1415155-nsstringfromrange).
#[inline]
#[doc(alias = "NSStringFromRange")]
pub fn from_nsrange(range: NSRange) -> Arc<Self> {
extern "C" {
fn NSStringFromRange<'data>(range: NSRange) -> Arc<NSString<'data>>;
}
unsafe { NSStringFromRange(range) }
}
/// Returns a copy of this object using
/// [`NSCopying`](https://developer.apple.com/documentation/foundation/nscopying).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject/1418807-copy).
#[inline]
pub fn copy(&self) -> Arc<Self> {
let copy = NSObject::copy(self);
unsafe { Arc::cast_unchecked(copy) }
}
/// Returns a copy of this object using
/// [`NSMutableCopying`](https://developer.apple.com/documentation/foundation/nsmutablecopying).
///
/// See [documentation](https://developer.apple.com/documentation/objectivec/nsobject/1418978-mutablecopy).
#[inline]
pub fn mutable_copy(&self) -> Arc<NSMutableString<'data>> {
let copy = NSObject::mutable_copy(self);
unsafe { Arc::cast_unchecked(copy) }
}
}
/// Getting contents as [UTF-8](https://en.wikipedia.org/wiki/UTF-8).
impl NSString<'_> {
/// Returns a null-terminated UTF-8 representation of `self`, or null
/// if the internal storage of `self` does not allow this to be returned
/// efficiently.
///
/// Unlike [`to_utf8_ptr`](Self::to_utf8_ptr.html), this does not allocate
/// and construct a new UTF-8 C string if `self` does not represent one.
///
/// This is retrieved using
/// [`CFStringGetCStringPtr`](https://developer.apple.com/documentation/corefoundation/1542133-cfstringgetcstringptr)
/// and
/// [`kCFStringEncodingUTF8`](https://developer.apple.com/documentation/corefoundation/cfstringbuiltinencodings/kcfstringencodingutf8).
#[inline]
#[doc(alias = "CFStringGetCStringPtr")]
pub fn as_utf8_ptr(&self) -> *const c_char {
type CFStringEncoding = u32;
#[allow(non_upper_case_globals)]
const kCFStringEncodingUTF8: CFStringEncoding = 0x08000100;
extern "C" {
fn CFStringGetCStringPtr(s: &NSString, encoding: CFStringEncoding) -> *const c_char;
}
unsafe { CFStringGetCStringPtr(self, kCFStringEncodingUTF8) }
}
/// Returns a null-terminated UTF-8 representation of `self`.
///
/// This C string is a pointer to a structure inside `self`,
/// which may have a lifetime shorter than the string object and will
/// certainly not have a longer lifetime. Therefore, you should copy the C
/// string if it needs to be stored outside of the memory context in which
/// you use this property.
///
/// This is retrieved using
/// [`-[NSString UTF8String]`](https://developer.apple.com/documentation/foundation/nsstring/1411189-utf8string).
#[inline]
pub fn to_utf8_ptr(&self) -> *const c_char {
unsafe { _msg_send_any![self, UTF8String] }
}
/// Returns the number of bytes required to encode this string as UTF-8.
#[inline]
pub fn utf8_length(&self) -> usize {
self.length_of_bytes_using_encoding(NSStringEncoding::UTF8)
}
/// Returns the contents of `self` as a native UTF-8 string slice, or `None`
/// if the internal storage of `self` does not allow this to be returned
/// efficiently.
///
/// Unlike [`to_str`](Self::to_str.html), this does not allocate and
/// construct a new UTF-8 C string if `self` does not represent one.
///
/// # Safety
///
/// You must ensure that `self` is not mutated during the lifetime of the
/// returned string slice.
#[inline]
pub unsafe fn as_str(&self) -> Option<&str> {
let s = self.as_str_with_nul()?;
// `CStr::to_bytes` does a checked slice conversion that emits a length
// failure panic that'll never get called.
Some(s.get_unchecked(..s.len() - 1))
}
/// Returns the contents of `self` as a native UTF-8 string slice.
///
/// This internally uses [`to_utf8_ptr`](Self::to_utf8_ptr). See its
/// documentation for details.
///
/// # Safety
///
/// The lifetime of the returned string slice may be shorter than this
/// object. Therefore, long use cases should copy the bytes of the returned
/// string slice or use [`to_string`](Self::to_string).
#[inline]
pub unsafe fn to_str(&self) -> &str {
let cstr = self.to_utf8_ptr();
let len = self.utf8_length();
str::from_utf8_unchecked(slice::from_raw_parts(cstr.cast(), len))
}
/// Returns the contents of `self` as a native UTF-8 string slice ending
/// with a 0 byte, or `None` if the internal storage of `self` does not
/// allow this to be returned efficiently.
///
/// Unlike [`to_str_with_nul`](Self::to_str_with_nul.html), this does not
/// allocate and construct a new UTF-8 C string if `self` does not represent
/// one.
///
/// # Safety
///
/// You must ensure that `self` is not mutated during the lifetime of the
/// returned string slice.
#[inline]
pub unsafe fn as_str_with_nul(&self) -> Option<&str> {
let cstr = self.as_utf8_ptr();
if cstr.is_null() {
return None;
}
let len = self.utf8_length();
Some(str::from_utf8_unchecked(slice::from_raw_parts(
cstr.cast(),
len + 1,
)))
}
/// Returns the contents of `self` as a native UTF-8 string slice ending
/// with a 0 byte.
///
/// This internally uses [`to_utf8_ptr`](Self::to_utf8_ptr). See its
/// documentation for details.
///
/// # Safety
///
/// The lifetime of the returned string slice may be shorter than this
/// object. Therefore, long use cases should copy the bytes of the returned
/// string slice or use [`to_string_with_nul`](Self::to_string_with_nul).
pub unsafe fn to_str_with_nul(&self) -> &str {
let cstr = self.to_utf8_ptr();
let len = self.utf8_length();
str::from_utf8_unchecked(slice::from_raw_parts(cstr.cast(), len + 1))
}
/// Returns the contents of `self` as a native UTF-8 string buffer.
///
/// This internally uses [`to_utf8_ptr`](Self::to_utf8_ptr). See its
/// documentation for details.
///
/// # Performance Considerations
///
/// Because of how
/// [`-[NSString UTF8String]`](https://developer.apple.com/documentation/foundation/nsstring/1411189-utf8string)
/// works, this method will likely allocate twice as much memory needed for
/// the length of the resulting buffer. If your use case is short-lived
/// enough, consider using [`to_str`](Self::to_str) to save memory and time.
#[inline]
pub fn to_string(&self) -> String {
// This method relies on `to_string_with_nul` because that method
// generates a lot of code that is best to only exist once.
let mut string = self.to_string_with_nul();
let len = string.len() - 1;
// This approach is slightly faster than `String::pop`.
//
// SAFETY: The null character takes 1 byte in UTF-8.
unsafe { string.as_mut_vec().set_len(len) };
string
}
/// Returns the contents of `self` as a native UTF-8 string buffer ending
/// with a 0 byte.
///
/// This internally uses [`to_utf8_ptr`](Self::to_utf8_ptr). See its
/// documentation for details.
///
/// # Performance Considerations
///
/// Because of how
/// [`-[NSString UTF8String]`](https://developer.apple.com/documentation/foundation/nsstring/1411189-utf8string)
/// works, this method will likely allocate twice as much memory needed for
/// the length of the resulting buffer. If your use case is short-lived
/// enough, consider using [`to_str_with_nul`](Self::to_str_with_nul) to
/// save memory and time.
pub fn to_string_with_nul(&self) -> String {
// SAFETY: This use of the string is reasonably short-lived enough for
// its lifetime to be long enough.
unsafe { self.to_str_with_nul() }.into()
}
}
/// Getting contents as [UTF-16](https://en.wikipedia.org/wiki/UTF-16).
impl NSString<'_> {
/// Returns a pointer to the UTF-16 representation of `self`, or null if the
/// internal storage of `self` does not allow this to be returned
/// efficiently.
///
/// This is retrieved using
/// [`CFStringGetCharactersPtr`](https://developer.apple.com/documentation/corefoundation/1542939-cfstringgetcharactersptr)
///
/// See [`as_utf8_ptr`](Self::as_utf8_ptr) for the UTF-8 equivalent.
#[inline]
#[doc(alias = "CFStringGetCharactersPtr")]
pub fn as_utf16_ptr(&self) -> *const u16 {
extern "C" {
fn CFStringGetCharactersPtr(s: &NSString) -> *const u16;
}
unsafe { CFStringGetCharactersPtr(self) }
}
/// Returns the contents of `self` as a UTF-16 string slice, or `None` if
/// the internal storage of `self` does not allow this to be returned
/// efficiently.
///
/// See [`as_str`](Self::as_str) for the UTF-8 equivalent.
///
/// # Safety
///
/// You must ensure that `self` is not mutated during the lifetime of the
/// returned slice.
#[inline]
pub unsafe fn as_utf16(&self) -> Option<&[u16]> {
let ptr = self.as_utf16_ptr();
if ptr.is_null() {
return None;
}
Some(slice::from_raw_parts(ptr, self.length()))
}
}
impl NSString<'_> {
/// Returns the number of UTF-16 code units in `self`.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1414212-length).
#[inline]
pub fn length(&self) -> NSUInteger {
unsafe { _msg_send_any![self, length] }
}
/// Returns the number of bytes required to store `self` in a given
/// encoding.
///
/// The length does not include space for a terminating null character.
/// Returns `0` if the specified encoding cannot be used to convert `self`
/// or if the amount of memory required for storing the results of the
/// encoding conversion would exceed NSIntegerMax.
///
/// The result is exact and is returned in `O(n)` time.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1410710-lengthofbytesusingencoding).
#[inline]
#[doc(alias = "lengthOfBytesUsingEncoding")]
#[doc(alias = "lengthOfBytesUsingEncoding:")]
pub fn length_of_bytes_using_encoding(&self, encoding: NSStringEncoding) -> NSUInteger {
unsafe { _msg_send_any![self, lengthOfBytesUsingEncoding: encoding] }
}
/// Returns a selector with `self` as its name.
///
/// If `self` cannot be converted to UTF-8 (this should be only due to
/// insufficient memory), this returns [`None`].
///
/// See [documentation](https://developer.apple.com/documentation/foundation/1395294-nsselectorfromstring).
#[inline]
pub fn to_selector(&self) -> Option<Sel> {
NSSelectorFromString(self)
}
// TODO: Other comparison methods:
// - compare:options:
// - compare:options:range:
// - compare:options:range:locale:
/// Compares the string and a given string using no options.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1414082-compare).
#[inline]
pub fn compare(&self, other: &NSString) -> NSComparisonResult {
unsafe { _msg_send_any![self, compare: other] }
}
/// Compares the string and a given string using a localized comparison.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1416999-localizedcompare).
#[inline]
#[doc(alias = "localizedCompare")]
pub fn localized_compare(&self, other: &NSString) -> NSComparisonResult {
unsafe { _msg_send_any![self, localizedCompare: other] }
}
/// Compares the string with a given string using `NSCaseInsensitiveSearch`.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1414769-caseinsensitivecompare).
#[inline]
#[doc(alias = "caseInsensitiveCompare")]
pub fn case_insensitive_compare(&self, other: &NSString) -> NSComparisonResult {
unsafe { _msg_send_any![self, caseInsensitiveCompare: other] }
}
/// Compares the string with a given string using a case-insensitive,
/// localized, comparison.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1417333-localizedcaseinsensitivecompare).
#[inline]
#[doc(alias = "localizedCaseInsensitiveCompare")]
pub fn localized_case_insensitive_compare(&self, other: &NSString) -> NSComparisonResult {
unsafe { _msg_send_any![self, localizedCaseInsensitiveCompare: other] }
}
/// Compares strings as sorted by the Finder.
///
/// This method should be used whenever file names or other strings are
/// presented in lists and tables where Finder-like sorting is appropriate.
/// The exact sorting behavior of this method is different under different
/// locales and may be changed in future releases. This method uses the
/// current locale.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1409742-localizedstandardcompare).
#[inline]
#[doc(alias = "localizedStandardCompare")]
pub fn localized_standard_compare(&self, other: &NSString) -> NSComparisonResult {
unsafe { _msg_send_any![self, localizedStandardCompare: other] }
}
/// Returns `true` if the given string matches the beginning characters of
/// `self`.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1410309-hasprefix).
#[inline]
#[doc(alias = "hasPrefix")]
pub fn has_prefix(&self, prefix: &NSString) -> bool {
unsafe { _msg_send_any![self, hasPrefix: prefix => BOOL] }.into()
}
/// Returns `true` if the given string matches the ending characters of this
/// string.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsstring/1416529-hassuffix).
#[inline]
#[doc(alias = "hasSuffix")]
pub fn has_suffix(&self, suffix: &NSString) -> bool {
unsafe { _msg_send_any![self, hasSuffix: suffix => BOOL] }.into()
}
}
objc_subclass! {
/// A dynamic plain-text Unicode string object.
///
/// See [documentation](https://developer.apple.com/documentation/foundation/nsmutablestring).
pub class NSMutableString<'data>: NSString<'data>;
}
impl Default for Arc<NSMutableString<'_>> {
#[inline]
fn default() -> Self {
unsafe { NSMutableString::class().alloc_init() }
}
}
impl PartialEq for NSMutableString<'_> {
#[inline]
fn eq(&self, other: &Self) -> bool {
NSString::eq(self, other)
}
}
impl PartialEq<NSString<'_>> for NSMutableString<'_> {
#[inline]
fn eq(&self, other: &NSString) -> bool {
(self as &NSString).eq(other)
}
}
impl PartialEq<NSMutableString<'_>> for NSString<'_> {
#[inline]
fn eq(&self, other: &NSMutableString) -> bool {
self.eq(other as &NSString)
}
}
impl Eq for NSMutableString<'_> {}
impl PartialOrd for NSMutableString<'_> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialOrd<NSString<'_>> for NSMutableString<'_> {
#[inline]
fn partial_cmp(&self, other: &NSString) -> Option<Ordering> {
Some(NSString::cmp(self, other))
}
}
impl PartialOrd<NSMutableString<'_>> for NSString<'_> {
#[inline]
fn partial_cmp(&self, other: &NSMutableString) -> Option<Ordering> {
Some(NSString::cmp(self, other))
}
}
impl Ord for NSMutableString<'_> {
#[inline]
fn cmp(&self, other: &Self) -> Ordering {
NSString::cmp(self, other)
}
}
impl PartialEq<str> for NSMutableString<'_> {
#[inline]
fn eq(&self, other: &str) -> bool {
NSString::eq(self, other)
}
}
impl PartialEq<&str> for NSMutableString<'_> {
#[inline]
fn eq(&self, other: &&str) -> bool {
NSString::eq(self, other)
}
}
impl PartialEq<NSMutableString<'_>> for str {
#[inline]
fn eq(&self, other: &NSMutableString) -> bool {
other == self
}
}
impl PartialEq<NSMutableString<'_>> for &str {
#[inline]
fn eq(&self, other: &NSMutableString) -> bool {
other == self
}
}
impl PartialOrd<str> for NSMutableString<'_> {
#[inline]
fn partial_cmp(&self, other: &str) -> Option<Ordering> {
NSString::partial_cmp(self, other)
}
}
impl PartialOrd<&str> for NSMutableString<'_> {
#[inline]
fn partial_cmp(&self, other: &&str) -> Option<Ordering> {
NSString::partial_cmp(self, other)
}
}
impl PartialOrd<NSMutableString<'_>> for str {
#[inline]
fn partial_cmp(&self, other: &NSMutableString) -> Option<Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl PartialOrd<NSMutableString<'_>> for &str {
#[inline]
fn partial_cmp(&self, other: &NSMutableString) -> Option<Ordering> {
Some(other.partial_cmp(self)?.reverse())
}
}
impl From<&str> for Arc<NSMutableString<'_>> {
#[inline]
fn from(s: &str) -> Self {
NSMutableString::from_str(s)
}
}
impl From<&mut str> for Arc<NSMutableString<'_>> {
#[inline]
fn from(s: &mut str) -> Self {
NSMutableString::from_str(s)
}
}
impl fmt::Debug for NSMutableString<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(self as &NSString).fmt(f)
}
}
impl fmt::Display for NSMutableString<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(self as &NSString).fmt(f)
}
}
impl<'data> NSMutableString<'data> {
/// Creates a mutable string object from copying a slice.
#[inline]
pub fn from_str(s: &str) -> Arc<Self> {
unsafe { Arc::cast_unchecked(NSString::_from_str(s, Self::class())) }
}
/// Creates a mutable string object without copying a slice.
///
/// # Safety
///
/// The returned string object or its clones must not outlive the referenced
/// string slice.
pub fn from_str_no_copy(s: &'data mut str) -> Arc<Self> {
let value: Arc<Self> = unsafe { Self::class().alloc() };
#[allow(clashing_extern_declarations)]
extern "C" {
fn objc_msgSend<'data>(
obj: Arc<NSMutableString<'data>>,
sel: Sel,
bytes: *mut u8,
length: NSUInteger,
encoding: NSStringEncoding,
free_when_done: BOOL,
) -> Arc<NSMutableString<'data>>;
}
let obj = value;
let sel = selector!(initWithBytesNoCopy:length:encoding:freeWhenDone:);
let bytes = s.as_mut_ptr();
let length = s.len();
let encoding = NSStringEncoding::UTF8;
let free_when_done = BOOL::NO;
unsafe { objc_msgSend(obj, sel, bytes, length, encoding, free_when_done) }
}
}