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
use alloc::vec::Vec;
use core::fmt;
use core::marker::PhantomData;
use core::panic::{RefUnwindSafe, UnwindSafe};

use super::{
    NSArray, NSCopying, NSEnumerator, NSFastEnumeration, NSFastEnumerator, NSMutableCopying,
    NSMutableSet, NSObject,
};
use crate::rc::{DefaultId, Id, Owned, Ownership, Shared, SliceId};
use crate::runtime::Class;
use crate::{ClassType, Message, __inner_extern_class, extern_methods, msg_send, msg_send_id};

__inner_extern_class!(
    /// An immutable unordered collection of unique objects.
    ///
    /// See [Apple's documentation][apple-doc].
    ///
    /// [apple-doc]: https://developer.apple.com/documentation/foundation/nsset?language=objc
    #[derive(PartialEq, Eq, Hash)]
    pub struct NSSet<T: Message, O: Ownership = Shared> {
        item: PhantomData<Id<T, O>>,
        notunwindsafe: PhantomData<&'static mut ()>,
    }

    unsafe impl<T: Message, O: Ownership> ClassType for NSSet<T, O> {
        type Super = NSObject;
    }
);

// SAFETY: Same as NSArray<T, O>
unsafe impl<T: Message + Sync + Send> Sync for NSSet<T, Shared> {}
unsafe impl<T: Message + Sync + Send> Send for NSSet<T, Shared> {}
unsafe impl<T: Message + Sync> Sync for NSSet<T, Owned> {}
unsafe impl<T: Message + Send> Send for NSSet<T, Owned> {}

// SAFETY: Same as NSArray<T, O>
impl<T: Message + RefUnwindSafe, O: Ownership> RefUnwindSafe for NSSet<T, O> {}
impl<T: Message + RefUnwindSafe> UnwindSafe for NSSet<T, Shared> {}
impl<T: Message + UnwindSafe> UnwindSafe for NSSet<T, Owned> {}

#[track_caller]
pub(crate) unsafe fn with_objects<T: Message + ?Sized, R: Message, O: Ownership>(
    cls: &Class,
    objects: &[&T],
) -> Id<R, O> {
    unsafe {
        msg_send_id![
            msg_send_id![cls, alloc],
            initWithObjects: objects.as_ptr(),
            count: objects.len()
        ]
    }
}

extern_methods!(
    unsafe impl<T: Message, O: Ownership> NSSet<T, O> {
        /// Creates an empty [`NSSet`].
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let set = NSSet::<NSString>::new();
        /// ```
        pub fn new() -> Id<Self, Shared> {
            // SAFETY:
            // - `new` may not create a new object, but instead return a shared
            //   instance. We remedy this by returning `Id<Self, Shared>`.
            // - `O` don't actually matter here! E.g. `NSSet<T, Owned>` is
            //   perfectly legal, since the set doesn't have any elements, and
            //   hence the notion of ownership over the elements is void.
            unsafe { msg_send_id![Self::class(), new] }
        }

        /// Creates an [`NSSet`] from a vector.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str).to_vec();
        /// let set = NSSet::from_vec(strs);
        /// ```
        pub fn from_vec(vec: Vec<Id<T, O>>) -> Id<Self, O> {
            // SAFETY:
            // When we know that we have ownership over the variables, we also
            // know that there cannot be another set in existence with the same
            // objects, so `Id<NSSet<T, Owned>, Owned>` is safe to return when
            // we receive `Vec<Id<T, Owned>>`.
            unsafe { with_objects(Self::class(), vec.as_slice_ref()) }
        }

        /// Returns the number of elements in the set.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// assert_eq!(set.len(), 3);
        /// ```
        #[doc(alias = "count")]
        #[sel(count)]
        pub fn len(&self) -> usize;

        /// Returns `true` if the set contains no elements.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let set = NSSet::<NSString>::new();
        /// assert!(set.is_empty());
        /// ```
        pub fn is_empty(&self) -> bool {
            self.len() == 0
        }

        /// Returns a reference to one of the objects in the set, or `None` if
        /// the set is empty.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// let any = set.get_any().unwrap();
        /// assert!(any == &*strs[0] || any == &*strs[1] || any == &*strs[2]);
        /// ```
        #[doc(alias = "anyObject")]
        #[sel(anyObject)]
        pub fn get_any(&self) -> Option<&T>;

        /// An iterator visiting all elements in arbitrary order.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// for s in set.iter() {
        ///     println!("{s}");
        /// }
        /// ```
        #[doc(alias = "objectEnumerator")]
        pub fn iter(&self) -> NSEnumerator<'_, T> {
            unsafe {
                let result = msg_send![self, objectEnumerator];
                NSEnumerator::from_ptr(result)
            }
        }

        /// Returns a [`Vec`] containing the set's elements, consuming the set.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSMutableString, NSSet};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = vec![
        ///     NSMutableString::from_str("one"),
        ///     NSMutableString::from_str("two"),
        ///     NSMutableString::from_str("three"),
        /// ];
        /// let set = NSSet::from_vec(strs);
        /// let vec = NSSet::into_vec(set);
        /// assert_eq!(vec.len(), 3);
        /// ```
        pub fn into_vec(set: Id<Self, O>) -> Vec<Id<T, O>> {
            set.into_iter()
                .map(|obj| unsafe { Id::retain(obj as *const T as *mut T).unwrap_unchecked() })
                .collect()
        }
    }

    unsafe impl<T: Message> NSSet<T, Shared> {
        /// Creates an [`NSSet`] from a slice.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// ```
        pub fn from_slice(slice: &[Id<T, Shared>]) -> Id<Self, Shared> {
            // SAFETY:
            // Taking `&T` would not be sound, since the `&T` could come from
            // an `Id<T, Owned>` that would now no longer be owned!
            //
            // We always return `Id<NSSet<T, Shared>, Shared>` because the
            // elements are shared.
            unsafe { with_objects(Self::class(), slice.as_slice_ref()) }
        }

        /// Returns an [`NSArray`] containing the set's elements, or an empty
        /// array if the set is empty.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSNumber, NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let nums = [1, 2, 3];
        /// let set = NSSet::from_slice(&nums.map(NSNumber::new_i32));
        ///
        /// assert_eq!(set.to_array().len(), 3);
        /// assert!(set.to_array().iter().all(|i| nums.contains(&i.as_i32())));
        /// ```
        #[doc(alias = "allObjects")]
        pub fn to_array(&self) -> Id<NSArray<T, Shared>, Shared> {
            // SAFETY:
            // We only define this method for sets with shared elements
            // because we can't return copies of owned elements.
            unsafe { msg_send_id![self, allObjects] }
        }
    }

    // We're explicit about `T` being `PartialEq` for these methods because the
    // set compares the input value(s) with elements in the set
    // For comparison: Rust's HashSet requires similar methods to be `Hash` + `Eq`
    unsafe impl<T: Message + PartialEq, O: Ownership> NSSet<T, O> {
        /// Returns `true` if the set contains a value.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// use objc2::ns_string;
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// assert!(set.contains(ns_string!("one")));
        /// ```
        #[doc(alias = "containsObject:")]
        #[sel(containsObject:)]
        pub fn contains(&self, value: &T) -> bool;

        /// Returns a reference to the value in the set, if any, that is equal
        /// to the given value.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// use objc2::ns_string;
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let strs = ["one", "two", "three"].map(NSString::from_str);
        /// let set = NSSet::from_slice(&strs);
        /// assert_eq!(set.get(ns_string!("one")), Some(&*strs[0]));
        /// assert_eq!(set.get(ns_string!("four")), None);
        /// ```
        #[doc(alias = "member:")]
        #[sel(member:)]
        pub fn get(&self, value: &T) -> Option<&T>;

        /// Returns `true` if the set is a subset of another, i.e., `other`
        /// contains at least all the values in `self`.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        /// let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));
        ///
        /// assert!(set1.is_subset(&set2));
        /// assert!(!set2.is_subset(&set1));
        /// ```
        #[doc(alias = "isSubsetOfSet:")]
        #[sel(isSubsetOfSet:)]
        pub fn is_subset(&self, other: &NSSet<T, O>) -> bool;

        /// Returns `true` if the set is a superset of another, i.e., `self`
        /// contains at least all the values in `other`.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        /// let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));
        ///
        /// assert!(!set1.is_superset(&set2));
        /// assert!(set2.is_superset(&set1));
        /// ```
        pub fn is_superset(&self, other: &NSSet<T, O>) -> bool {
            other.is_subset(self)
        }

        #[sel(intersectsSet:)]
        fn intersects_set(&self, other: &NSSet<T, O>) -> bool;

        /// Returns `true` if `self` has no elements in common with `other`.
        ///
        /// # Examples
        ///
        /// ```
        /// use objc2::foundation::{NSSet, NSString};
        /// # #[cfg(feature = "gnustep-1-7")]
        /// # unsafe { objc2::__gnustep_hack::get_class_to_force_linkage() };
        ///
        /// let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        /// let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));
        /// let set3 = NSSet::from_slice(&["four", "five", "six"].map(NSString::from_str));
        ///
        /// assert!(!set1.is_disjoint(&set2));
        /// assert!(set1.is_disjoint(&set3));
        /// assert!(set2.is_disjoint(&set3));
        /// ```
        pub fn is_disjoint(&self, other: &NSSet<T, O>) -> bool {
            !self.intersects_set(other)
        }
    }
);

unsafe impl<T: Message> NSCopying for NSSet<T, Shared> {
    type Ownership = Shared;
    type Output = NSSet<T, Shared>;
}

unsafe impl<T: Message> NSMutableCopying for NSSet<T, Shared> {
    type Output = NSMutableSet<T, Shared>;
}

impl<T: Message> alloc::borrow::ToOwned for NSSet<T, Shared> {
    type Owned = Id<NSSet<T, Shared>, Shared>;
    fn to_owned(&self) -> Self::Owned {
        self.copy()
    }
}

unsafe impl<T: Message, O: Ownership> NSFastEnumeration for NSSet<T, O> {
    type Item = T;
}

impl<'a, T: Message, O: Ownership> IntoIterator for &'a NSSet<T, O> {
    type Item = &'a T;
    type IntoIter = NSFastEnumerator<'a, NSSet<T, O>>;

    fn into_iter(self) -> Self::IntoIter {
        self.iter_fast()
    }
}

impl<T: Message, O: Ownership> DefaultId for NSSet<T, O> {
    type Ownership = Shared;

    #[inline]
    fn default_id() -> Id<Self, Self::Ownership> {
        Self::new()
    }
}

impl<T: fmt::Debug + Message, O: Ownership> fmt::Debug for NSSet<T, O> {
    #[inline]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_set().entries(self.iter_fast()).finish()
    }
}

#[cfg(test)]
mod tests {
    use alloc::format;
    use alloc::vec;

    use super::*;
    use crate::foundation::{NSMutableString, NSNumber, NSString};
    use crate::ns_string;
    use crate::rc::{RcTestObject, ThreadTestData};

    #[test]
    fn test_new() {
        let set = NSSet::<NSString>::new();
        assert!(set.is_empty());
    }

    #[test]
    fn test_from_vec() {
        let set = NSSet::<NSString>::from_vec(Vec::new());
        assert!(set.is_empty());

        let strs = ["one", "two", "three"].map(NSString::from_str);
        let set = NSSet::from_vec(strs.to_vec());
        assert!(strs.into_iter().all(|s| set.contains(&s)));

        let nums = [1, 2, 3].map(NSNumber::new_i32);
        let set = NSSet::from_vec(nums.to_vec());
        assert!(nums.into_iter().all(|n| set.contains(&n)));
    }

    #[test]
    fn test_from_slice() {
        let set = NSSet::<NSString>::from_slice(&[]);
        assert!(set.is_empty());

        let strs = ["one", "two", "three"].map(NSString::from_str);
        let set = NSSet::from_slice(&strs);
        assert!(strs.into_iter().all(|s| set.contains(&s)));

        let nums = [1, 2, 3].map(NSNumber::new_i32);
        let set = NSSet::from_slice(&nums);
        assert!(nums.into_iter().all(|n| set.contains(&n)));
    }

    #[test]
    fn test_len() {
        let set = NSSet::<NSString>::new();
        assert!(set.is_empty());

        let set = NSSet::from_slice(&["one", "two", "two"].map(NSString::from_str));
        assert_eq!(set.len(), 2);

        let set = NSSet::from_vec(vec![NSObject::new(), NSObject::new(), NSObject::new()]);
        assert_eq!(set.len(), 3);
    }

    #[test]
    fn test_get() {
        let set = NSSet::<NSString>::new();
        assert!(set.get(ns_string!("one")).is_none());

        let set = NSSet::from_slice(&["one", "two", "two"].map(NSString::from_str));
        assert!(set.get(ns_string!("two")).is_some());
        assert!(set.get(ns_string!("three")).is_none());
    }

    #[test]
    fn test_get_return_lifetime() {
        let set = NSSet::from_slice(&["one", "two", "two"].map(NSString::from_str));

        let res = {
            let value = NSString::from_str("one");
            set.get(&value)
        };

        assert_eq!(res, Some(ns_string!("one")));
    }

    #[test]
    fn test_get_any() {
        let set = NSSet::<NSString>::new();
        assert!(set.get_any().is_none());

        let strs = ["one", "two", "three"].map(NSString::from_str);
        let set = NSSet::from_slice(&strs);
        let any = set.get_any().unwrap();
        assert!(any == &*strs[0] || any == &*strs[1] || any == &*strs[2]);
    }

    #[test]
    fn test_contains() {
        let set = NSSet::<NSString>::new();
        assert!(!set.contains(ns_string!("one")));

        let set = NSSet::from_slice(&["one", "two", "two"].map(NSString::from_str));
        assert!(set.contains(ns_string!("one")));
        assert!(!set.contains(ns_string!("three")));
    }

    #[test]
    fn test_is_subset() {
        let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));

        assert!(set1.is_subset(&set2));
        assert!(!set2.is_subset(&set1));
    }

    #[test]
    fn test_is_superset() {
        let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));

        assert!(!set1.is_superset(&set2));
        assert!(set2.is_superset(&set1));
    }

    #[test]
    fn test_is_disjoint() {
        let set1 = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        let set2 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));
        let set3 = NSSet::from_slice(&["four", "five", "six"].map(NSString::from_str));

        assert!(!set1.is_disjoint(&set2));
        assert!(set1.is_disjoint(&set3));
        assert!(set2.is_disjoint(&set3));
    }

    #[test]
    fn test_to_array() {
        let nums = [1, 2, 3];
        let set = NSSet::from_slice(&nums.map(NSNumber::new_i32));

        assert_eq!(set.to_array().len(), 3);
        assert!(set.to_array().iter().all(|i| nums.contains(&i.as_i32())));
    }

    #[test]
    fn test_iter() {
        let nums = [1, 2, 3];
        let set = NSSet::from_slice(&nums.map(NSNumber::new_i32));

        assert_eq!(set.iter().count(), 3);
        assert!(set.iter().all(|i| nums.contains(&i.as_i32())));
    }

    #[test]
    fn test_iter_fast() {
        let nums = [1, 2, 3];
        let set = NSSet::from_slice(&nums.map(NSNumber::new_i32));

        assert_eq!(set.iter_fast().count(), 3);
        assert!(set.iter_fast().all(|i| nums.contains(&i.as_i32())));
    }

    #[test]
    fn test_into_iter() {
        let nums = [1, 2, 3];
        let set = NSSet::from_slice(&nums.map(NSNumber::new_i32));

        assert!(set.into_iter().all(|i| nums.contains(&i.as_i32())));
    }

    #[test]
    fn test_into_vec() {
        let strs = vec![
            NSMutableString::from_str("one"),
            NSMutableString::from_str("two"),
            NSMutableString::from_str("three"),
        ];
        let set = NSSet::from_vec(strs);

        let mut vec = NSSet::into_vec(set);
        for str in vec.iter_mut() {
            str.push_nsstring(ns_string!(" times zero is zero"));
        }

        assert_eq!(vec.len(), 3);
        let suffix = ns_string!("zero");
        assert!(vec.iter().all(|str| str.has_suffix(suffix)));
    }

    #[test]
    fn test_equality() {
        let set1 = NSSet::<NSString>::new();
        let set2 = NSSet::<NSString>::new();
        assert_eq!(set1, set2);
    }

    #[test]
    fn test_copy() {
        let set1 = NSSet::from_slice(&["one", "two", "three"].map(NSString::from_str));
        let set2 = set1.copy();
        assert_eq!(set1, set2);
    }

    #[test]
    fn test_debug() {
        let set = NSSet::<NSString>::new();
        assert_eq!(format!("{:?}", set), "{}");

        let set = NSSet::from_slice(&["one", "two"].map(NSString::from_str));
        assert!(matches!(
            format!("{:?}", set).as_str(),
            "{\"one\", \"two\"}" | "{\"two\", \"one\"}"
        ));
    }

    #[test]
    fn test_retains_stored() {
        let obj = Id::into_shared(RcTestObject::new());
        let mut expected = ThreadTestData::current();

        let input = [obj.clone(), obj.clone()];
        expected.retain += 2;
        expected.assert_current();

        let set = NSSet::from_slice(&input);
        expected.retain += 1;
        expected.assert_current();

        let _obj = set.get_any().unwrap();
        expected.assert_current();

        drop(set);
        expected.release += 1;
        expected.assert_current();

        let set = NSSet::from_vec(Vec::from(input));
        expected.retain += 1;
        expected.release += 2;
        expected.assert_current();

        drop(set);
        expected.release += 1;
        expected.assert_current();

        drop(obj);
        expected.release += 1;
        expected.dealloc += 1;
        expected.assert_current();
    }

    #[test]
    fn test_nscopying_uses_retain() {
        let obj = Id::into_shared(RcTestObject::new());
        let set = NSSet::from_slice(&[obj]);
        let mut expected = ThreadTestData::current();

        let _copy = set.copy();
        expected.assert_current();

        let _copy = set.mutable_copy();
        expected.retain += 1;
        expected.assert_current();
    }

    #[test]
    #[cfg_attr(
        feature = "apple",
        ignore = "this works differently on different framework versions"
    )]
    fn test_iter_no_retain() {
        let obj = Id::into_shared(RcTestObject::new());
        let set = NSSet::from_slice(&[obj]);
        let mut expected = ThreadTestData::current();

        let iter = set.iter();
        expected.retain += 0;
        expected.assert_current();

        assert_eq!(iter.count(), 1);
        expected.autorelease += 0;
        expected.assert_current();

        let iter = set.iter_fast();
        assert_eq!(iter.count(), 1);
        expected.assert_current();
    }
}