objc2_core_foundation/
array.rs

1#[cfg(feature = "alloc")]
2use alloc::vec::Vec;
3use core::borrow::Borrow;
4use core::ffi::c_void;
5
6use crate::{kCFTypeArrayCallBacks, CFArray, CFIndex, CFMutableArray, CFRetained, Type};
7
8#[inline]
9fn get_len<T>(objects: &[T]) -> CFIndex {
10    // An allocation in Rust cannot be larger than isize::MAX, so this will
11    // never fail.
12    //
13    // Note that `CFArray::new` documents:
14    // > If this parameter is negative, [...] the behavior is undefined.
15    let len = objects.len();
16    debug_assert!(len < CFIndex::MAX as usize);
17    len as CFIndex
18}
19
20/// Reading the source code:
21/// <https://github.com/apple-oss-distributions/CF/blob/CF-1153.18/CFArray.c#L391>
22/// <https://github.com/apple-oss-distributions/CF/blob/CF-1153.18/CFRuntime.c#L323>
23///
24/// It is clear that creating arrays can only realistically fail if allocating
25/// failed. So we choose to panic/abort in those cases, to roughly match
26/// `Vec`'s behaviour.
27#[cold]
28fn failed_creating_array(len: CFIndex) -> ! {
29    #[cfg(feature = "alloc")]
30    {
31        use alloc::alloc::{handle_alloc_error, Layout};
32        use core::mem::align_of;
33
34        // The layout here is not correct, only best-effort (CFArray adds
35        // extra padding when allocating).
36        let layout = Layout::array::<*const ()>(len as usize).unwrap_or_else(|_| unsafe {
37            Layout::from_size_align_unchecked(0, align_of::<*const ()>())
38        });
39
40        handle_alloc_error(layout)
41    }
42    #[cfg(not(feature = "alloc"))]
43    {
44        panic!("failed allocating CFArray holding {len} elements")
45    }
46}
47
48/// Convenience creation methods.
49impl<T: ?Sized> CFArray<T> {
50    /// Create a new empty `CFArray` capable of holding CoreFoundation
51    /// objects.
52    #[inline]
53    #[doc(alias = "CFArray::new")]
54    pub fn empty() -> CFRetained<Self>
55    where
56        T: Type,
57    {
58        // It may not strictly be necessary to use correct array callbacks
59        // here, though it's good to know that it's correct for use in e.g.
60        // `CFMutableArray::newCopy`.
61        Self::from_objects(&[])
62    }
63
64    /// Create a new `CFArray` with the given CoreFoundation objects.
65    #[inline]
66    #[doc(alias = "CFArray::new")]
67    pub fn from_objects(objects: &[&T]) -> CFRetained<Self>
68    where
69        T: Type,
70    {
71        let len = get_len(objects);
72        // `&T` has the same layout as `*const c_void`, and are non-NULL.
73        let ptr = objects.as_ptr().cast::<*const c_void>().cast_mut();
74
75        // SAFETY: The objects are CFTypes (`T: Type` bound), and the array
76        // callbacks are thus correct.
77        //
78        // The objects are retained internally by the array, so we do not need
79        // to keep them alive ourselves after this.
80        let array = unsafe { CFArray::new(None, ptr, len, &kCFTypeArrayCallBacks) }
81            .unwrap_or_else(|| failed_creating_array(len));
82
83        // SAFETY: The objects came from `T`.
84        unsafe { CFRetained::cast_unchecked::<Self>(array) }
85    }
86
87    /// Alias for easier transition from the `core-foundation` crate.
88    #[inline]
89    #[allow(non_snake_case)]
90    #[deprecated = "renamed to CFArray::from_objects"]
91    pub fn from_CFTypes(objects: &[&T]) -> CFRetained<Self>
92    where
93        T: Type,
94    {
95        Self::from_objects(objects)
96    }
97
98    /// Create a new `CFArray` with the given retained CoreFoundation objects.
99    #[inline]
100    #[doc(alias = "CFArray::new")]
101    pub fn from_retained_objects(objects: &[CFRetained<T>]) -> CFRetained<Self>
102    where
103        T: Type,
104    {
105        let len = get_len(objects);
106        // `CFRetained<T>` has the same layout as `*const c_void`.
107        let ptr = objects.as_ptr().cast::<*const c_void>().cast_mut();
108
109        // SAFETY: Same as in `from_objects`.
110        let array = unsafe { CFArray::new(None, ptr, len, &kCFTypeArrayCallBacks) }
111            .unwrap_or_else(|| failed_creating_array(len));
112
113        // SAFETY: The objects came from `T`.
114        unsafe { CFRetained::cast_unchecked::<Self>(array) }
115    }
116}
117
118/// Convenience creation methods.
119impl<T: ?Sized> CFMutableArray<T> {
120    /// Create a new empty mutable array.
121    #[inline]
122    #[doc(alias = "CFMutableArray::new")]
123    pub fn empty() -> CFRetained<Self>
124    where
125        T: Type,
126    {
127        Self::with_capacity(0)
128    }
129
130    /// Create a new mutable array with the given capacity.
131    #[inline]
132    #[doc(alias = "CFMutableArray::new")]
133    pub fn with_capacity(capacity: usize) -> CFRetained<Self>
134    where
135        T: Type,
136    {
137        // User can pass wrong value here, we must check.
138        let capacity = capacity.try_into().expect("capacity too high");
139
140        // SAFETY: The objects are CFTypes (`T: Type` bound), and the array
141        // callbacks are thus correct.
142        let array = unsafe { CFMutableArray::new(None, capacity, &kCFTypeArrayCallBacks) }
143            .unwrap_or_else(|| failed_creating_array(capacity));
144
145        // SAFETY: The array contains no objects yet, and thus it's safe to
146        // cast them to `T` (as the array callbacks are matching).
147        unsafe { CFRetained::cast_unchecked::<Self>(array) }
148    }
149}
150
151// TODO: Do we want to pass NULL callbacks or `CFArrayEqualCallBack`.
152// impl CFArray<()> {
153//     /// Create a new `CFArray` with the given retained CoreFoundation objects.
154//     pub fn from_usize(objects: &[usize]) -> CFRetained<Self> {
155//         let len = get_len(objects);
156//         // `CFRetained<T>` has the same layout as `*const c_void`.
157//         let ptr: *const c_void = objects.as_ptr().cast();
158//
159//         // SAFETY: Same as in `from_objects`.
160//         let array = unsafe { CFArray::new(None, ptr, len, null) }
161//             .unwrap_or(|| failed_creating_array(len));
162//
163//         // SAFETY: The objects came from `T`.
164//         unsafe { CFRetained::cast_unchecked::<Self>(array) }
165//     }
166// }
167
168/// Direct, unsafe object accessors.
169///
170/// CFArray stores its values directly, and you can get references to said
171/// values data without having to retain it first - but only if the array
172/// isn't mutated while doing so - otherwise, we might end up accessing a
173/// deallocated object.
174impl<T: ?Sized> CFArray<T> {
175    /// Get a direct reference to one of the array's objects.
176    ///
177    /// Consider using the [`get`](Self::get) method instead, unless you're
178    /// seeing performance issues from the retaining.
179    ///
180    /// # Safety
181    ///
182    /// - The index must not be negative, and must be in bounds of the array.
183    /// - The array must not be mutated while the returned reference is live.
184    #[inline]
185    #[doc(alias = "CFArrayGetValueAtIndex")]
186    pub unsafe fn get_unchecked(&self, index: CFIndex) -> &T
187    where
188        T: Type + Sized,
189    {
190        // SAFETY: Caller ensures that `index` is in bounds.
191        let ptr = unsafe { self.as_opaque().value_at_index(index) };
192        // SAFETY: The array's values are of type `T`, and the objects are
193        // CoreFoundation types (and thus cannot be NULL).
194        //
195        // Caller ensures that the array isn't mutated for the lifetime of the
196        // reference.
197        unsafe { &*ptr.cast::<T>() }
198    }
199
200    /// A vector containing direct references to the array's objects.
201    ///
202    /// Consider using the [`to_vec`](Self::to_vec) method instead, unless
203    /// you're seeing performance issues from the retaining.
204    ///
205    /// # Safety
206    ///
207    /// The array must not be mutated while the returned references are alive.
208    #[cfg(feature = "alloc")]
209    #[doc(alias = "CFArrayGetValues")]
210    pub unsafe fn to_vec_unchecked(&self) -> Vec<&T>
211    where
212        T: Type,
213    {
214        let len = self.len();
215        let range = crate::CFRange {
216            location: 0,
217            // Fine to cast, it came from CFIndex
218            length: len as CFIndex,
219        };
220        let mut vec = Vec::<&T>::with_capacity(len);
221
222        // `&T` has the same layout as `*const c_void`.
223        let ptr = vec.as_mut_ptr().cast::<*const c_void>();
224        // SAFETY: The range is in bounds
225        unsafe { self.as_opaque().values(range, ptr) };
226        // SAFETY: Just initialized the Vec above.
227        unsafe { vec.set_len(len) };
228
229        vec
230    }
231
232    /// Iterate over the array without touching the elements.
233    ///
234    /// Consider using the [`iter`](Self::iter) method instead, unless you're
235    /// seeing performance issues from the retaining.
236    ///
237    /// # Safety
238    ///
239    /// The array must not be mutated for the lifetime of the iterator or for
240    /// the lifetime of the elements the iterator returns.
241    #[inline]
242    pub unsafe fn iter_unchecked(&self) -> CFArrayIterUnchecked<'_, T>
243    where
244        T: Type,
245    {
246        CFArrayIterUnchecked {
247            array: self,
248            index: 0,
249            len: self.len() as CFIndex,
250        }
251    }
252}
253
254/// Various accessor methods.
255impl<T: ?Sized> CFArray<T> {
256    /// The amount of elements in the array.
257    #[inline]
258    #[doc(alias = "CFArrayGetCount")]
259    pub fn len(&self) -> usize {
260        // Fine to cast here, the count is never negative.
261        self.as_opaque().count() as _
262    }
263
264    /// Whether the array is empty or not.
265    #[inline]
266    pub fn is_empty(&self) -> bool {
267        self.len() == 0
268    }
269
270    /// Retrieve the object at the given index.
271    ///
272    /// Returns `None` if the index was out of bounds.
273    #[doc(alias = "CFArrayGetValueAtIndex")]
274    pub fn get(&self, index: usize) -> Option<CFRetained<T>>
275    where
276        T: Type + Sized,
277    {
278        if index < self.len() {
279            // Index is `usize` and just compared below the length (which is
280            // at max `CFIndex::MAX`), so a cast is safe here.
281            let index = index as CFIndex;
282            // SAFETY:
283            // - Just checked that the index is in bounds.
284            // - We retain the value right away, so that the reference is not
285            //   used while the array is mutated.
286            //
287            // Note that this is _technically_ wrong; the user _could_ have
288            // implemented a `retain` method that mutates the array. We're
289            // going to rule this out though, as that's basically never going
290            // to happen, and will make a lot of other things unsound too.
291            Some(unsafe { self.get_unchecked(index) }.retain())
292        } else {
293            None
294        }
295    }
296
297    /// Convert the array to a `Vec` of the array's objects.
298    #[cfg(feature = "alloc")]
299    #[doc(alias = "CFArrayGetValues")]
300    pub fn to_vec(&self) -> Vec<CFRetained<T>>
301    where
302        T: Type + Sized,
303    {
304        // SAFETY: We retain the elements below, so we know that the array
305        // isn't mutated while the references are alive.
306        let vec = unsafe { self.to_vec_unchecked() };
307        vec.into_iter().map(T::retain).collect()
308    }
309
310    /// Iterate over the array's elements.
311    #[inline]
312    pub fn iter(&self) -> CFArrayIter<'_, T> {
313        CFArrayIter {
314            array: self,
315            index: 0,
316        }
317    }
318}
319
320/// Convenience mutation methods.
321impl<T> CFMutableArray<T> {
322    /// Push an object to the end of the array.
323    #[inline]
324    #[doc(alias = "CFArrayAppendValue")]
325    pub fn append(&self, obj: &T) {
326        let ptr: *const T = obj;
327        let ptr: *const c_void = ptr.cast();
328        // SAFETY: The pointer is valid.
329        unsafe { CFMutableArray::append_value(Some(self.as_opaque()), ptr) }
330    }
331
332    /// Insert an object into the array at the given index.
333    ///
334    /// # Panics
335    ///
336    /// Panics if the index is out of bounds.
337    #[doc(alias = "CFArrayInsertValueAtIndex")]
338    pub fn insert(&self, index: usize, obj: &T) {
339        // TODO: Replace this check with catching the thrown NSRangeException
340        let len = self.len();
341        if index <= len {
342            let ptr: *const T = obj;
343            let ptr: *const c_void = ptr.cast();
344            // SAFETY: The pointer is valid, and just checked that the index
345            // is in bounds.
346            unsafe {
347                CFMutableArray::insert_value_at_index(Some(self.as_opaque()), index as CFIndex, ptr)
348            }
349        } else {
350            panic!(
351                "insertion index (is {}) should be <= len (is {})",
352                index, len
353            );
354        }
355    }
356}
357
358/// An iterator over retained objects of an array.
359#[derive(Debug)]
360pub struct CFArrayIter<'a, T: ?Sized + 'a> {
361    array: &'a CFArray<T>,
362    index: usize,
363}
364
365impl<T: Type> Iterator for CFArrayIter<'_, T> {
366    type Item = CFRetained<T>;
367
368    fn next(&mut self) -> Option<CFRetained<T>> {
369        // We _must_ re-check the length on every loop iteration, since the
370        // array could have come from `CFMutableArray` and have been mutated
371        // while we're iterating.
372        let value = self.array.get(self.index)?;
373        self.index += 1;
374        Some(value)
375    }
376
377    fn size_hint(&self) -> (usize, Option<usize>) {
378        let len = self.array.len().saturating_sub(self.index);
379        (len, Some(len))
380    }
381}
382
383impl<T: Type> ExactSizeIterator for CFArrayIter<'_, T> {}
384
385// TODO:
386// impl<T: Type> DoubleEndedIterator for CFArrayIter<'_, T> { ... }
387
388// Fused unless someone mutates the array, so we won't guarantee that (for now).
389// impl<T: Type> FusedIterator for CFArrayIter<'_, T> {}
390
391/// A retained iterator over the items of an array.
392#[derive(Debug)]
393pub struct CFArrayIntoIter<T: ?Sized> {
394    array: CFRetained<CFArray<T>>,
395    index: usize,
396}
397
398impl<T: Type> Iterator for CFArrayIntoIter<T> {
399    type Item = CFRetained<T>;
400
401    fn next(&mut self) -> Option<CFRetained<T>> {
402        // Same as `CFArrayIter::next`.
403        let value = self.array.get(self.index)?;
404        self.index += 1;
405        Some(value)
406    }
407
408    fn size_hint(&self) -> (usize, Option<usize>) {
409        let len = self.array.len().saturating_sub(self.index);
410        (len, Some(len))
411    }
412}
413
414impl<T: Type> ExactSizeIterator for CFArrayIntoIter<T> {}
415
416impl<'a, T: Type> IntoIterator for &'a CFArray<T> {
417    type Item = CFRetained<T>;
418    type IntoIter = CFArrayIter<'a, T>;
419
420    #[inline]
421    fn into_iter(self) -> Self::IntoIter {
422        self.iter()
423    }
424}
425
426impl<'a, T: Type> IntoIterator for &'a CFMutableArray<T> {
427    type Item = CFRetained<T>;
428    type IntoIter = CFArrayIter<'a, T>;
429
430    #[inline]
431    fn into_iter(self) -> Self::IntoIter {
432        self.iter()
433    }
434}
435
436impl<T: Type> IntoIterator for CFRetained<CFArray<T>> {
437    type Item = CFRetained<T>;
438    type IntoIter = CFArrayIntoIter<T>;
439
440    #[inline]
441    fn into_iter(self) -> Self::IntoIter {
442        CFArrayIntoIter {
443            array: self,
444            index: 0,
445        }
446    }
447}
448
449impl<T: Type> IntoIterator for CFRetained<CFMutableArray<T>> {
450    type Item = CFRetained<T>;
451    type IntoIter = CFArrayIntoIter<T>;
452
453    #[inline]
454    fn into_iter(self) -> Self::IntoIter {
455        // SAFETY: Upcasting `CFMutableArray<T>` to `CFArray<T>`.
456        let array = unsafe { CFRetained::cast_unchecked::<CFArray<T>>(self) };
457        CFArrayIntoIter { array, index: 0 }
458    }
459}
460
461/// An iterator over raw items of an array.
462///
463/// # Safety
464///
465/// The array must not be mutated while this is alive.
466#[derive(Debug)]
467pub struct CFArrayIterUnchecked<'a, T: ?Sized + 'a> {
468    array: &'a CFArray<T>,
469    index: CFIndex,
470    len: CFIndex,
471}
472
473impl<'a, T: Type> Iterator for CFArrayIterUnchecked<'a, T> {
474    type Item = &'a T;
475
476    #[inline]
477    fn next(&mut self) -> Option<&'a T> {
478        debug_assert_eq!(
479            self.array.len(),
480            self.len as usize,
481            "array was mutated while iterating"
482        );
483        if self.index < self.len {
484            // SAFETY:
485            // - That the array isn't mutated while iterating is upheld by the
486            //   caller of `CFArray::iter_unchecked`.
487            // - Index in bounds is ensured by the check above (which uses a
488            //   pre-computed length, and thus also assumes that the array
489            //   isn't mutated while iterating).
490            let value = unsafe { self.array.get_unchecked(self.index) };
491            self.index += 1;
492            Some(value)
493        } else {
494            None
495        }
496    }
497
498    #[inline]
499    fn size_hint(&self) -> (usize, Option<usize>) {
500        let len = (self.len - self.index) as usize;
501        (len, Some(len))
502    }
503}
504
505impl<T: Type> ExactSizeIterator for CFArrayIterUnchecked<'_, T> {}
506
507// Allow easy conversion from `&CFArray<T>` to `&CFArray`.
508// Requires `T: Type` because of reflexive impl in `cf_type!`.
509impl<T: ?Sized + Type> AsRef<CFArray> for CFArray<T> {
510    fn as_ref(&self) -> &CFArray {
511        self.as_opaque()
512    }
513}
514impl<T: ?Sized + Type> AsRef<CFMutableArray> for CFMutableArray<T> {
515    fn as_ref(&self) -> &CFMutableArray {
516        self.as_opaque()
517    }
518}
519
520// `Eq`, `Ord` and `Hash` have the same semantics.
521impl<T: ?Sized + Type> Borrow<CFArray> for CFArray<T> {
522    fn borrow(&self) -> &CFArray {
523        self.as_opaque()
524    }
525}
526impl<T: ?Sized + Type> Borrow<CFMutableArray> for CFMutableArray<T> {
527    fn borrow(&self) -> &CFMutableArray {
528        self.as_opaque()
529    }
530}
531
532#[cfg(test)]
533mod tests {
534    use super::*;
535    #[cfg(feature = "CFString")]
536    use crate::CFString;
537    use core::ptr::null;
538
539    #[test]
540    fn array_with_invalid_pointers() {
541        // without_provenance
542        let ptr = [0 as _, 1 as _, 2 as _, 3 as _, usize::MAX as _].as_mut_ptr();
543        let array = unsafe { CFArray::new(None, ptr, 1, null()) }.unwrap();
544        let value = unsafe { array.value_at_index(0) };
545        assert!(value.is_null());
546    }
547
548    #[test]
549    #[should_panic]
550    #[ignore = "aborts (as expected)"]
551    fn object_array_cannot_contain_null() {
552        let ptr = [null()].as_mut_ptr();
553        let _array = unsafe { CFArray::new(None, ptr, 1, &kCFTypeArrayCallBacks) };
554    }
555
556    #[test]
557    #[cfg(feature = "CFString")]
558    fn correct_retain_count() {
559        let objects = [
560            CFString::from_str("some long string that doesn't get small-string optimized"),
561            CFString::from_str("another long string that doesn't get small-string optimized"),
562        ];
563        let array = CFArray::from_retained_objects(&objects);
564
565        // Creating array retains elements.
566        assert_eq!(array.retain_count(), 1);
567        assert_eq!(unsafe { array.get_unchecked(0) }.retain_count(), 2);
568        assert_eq!(unsafe { array.get_unchecked(1) }.retain_count(), 2);
569
570        drop(objects);
571        assert_eq!(unsafe { array.get_unchecked(0) }.retain_count(), 1);
572        assert_eq!(unsafe { array.get_unchecked(1) }.retain_count(), 1);
573
574        // Retaining array doesn't affect retain count of elements.
575        let _array2 = array.retain();
576        assert_eq!(unsafe { array.get_unchecked(0) }.retain_count(), 1);
577        assert_eq!(unsafe { array.get_unchecked(1) }.retain_count(), 1);
578
579        // Using retaining API changes retain count.
580        assert_eq!(array.get(0).unwrap().retain_count(), 2);
581    }
582
583    #[test]
584    #[cfg(feature = "CFString")]
585    fn iter() {
586        use alloc::vec::Vec;
587
588        let s1 = CFString::from_str("a");
589        let s2 = CFString::from_str("b");
590        let array = CFArray::from_objects(&[&*s1, &*s2, &*s1]);
591
592        assert_eq!(
593            array.iter().collect::<Vec<_>>(),
594            [s1.clone(), s2.clone(), s1.clone()]
595        );
596
597        assert_eq!(
598            unsafe { array.iter_unchecked() }.collect::<Vec<_>>(),
599            [&*s1, &*s2, &*s1]
600        );
601    }
602
603    #[test]
604    #[cfg(feature = "CFString")]
605    fn iter_fused() {
606        let s1 = CFString::from_str("a");
607        let s2 = CFString::from_str("b");
608        let array = CFArray::from_objects(&[&*s1, &*s2]);
609
610        let mut iter = array.iter();
611        assert_eq!(iter.next(), Some(s1.clone()));
612        assert_eq!(iter.next(), Some(s2.clone()));
613        assert_eq!(iter.next(), None);
614        assert_eq!(iter.next(), None);
615        assert_eq!(iter.next(), None);
616        assert_eq!(iter.next(), None);
617        assert_eq!(iter.next(), None);
618        assert_eq!(iter.next(), None);
619        assert_eq!(iter.next(), None);
620
621        let mut iter = unsafe { array.iter_unchecked() };
622        assert_eq!(iter.next(), Some(&*s1));
623        assert_eq!(iter.next(), Some(&*s2));
624        assert_eq!(iter.next(), None);
625        assert_eq!(iter.next(), None);
626        assert_eq!(iter.next(), None);
627        assert_eq!(iter.next(), None);
628        assert_eq!(iter.next(), None);
629        assert_eq!(iter.next(), None);
630        assert_eq!(iter.next(), None);
631    }
632
633    #[test]
634    #[cfg(feature = "CFString")]
635    fn mutate() {
636        let array = CFMutableArray::<CFString>::with_capacity(10);
637        array.insert(0, &CFString::from_str("a"));
638        array.append(&CFString::from_str("c"));
639        array.insert(1, &CFString::from_str("b"));
640        assert_eq!(
641            array.to_vec(),
642            [
643                CFString::from_str("a"),
644                CFString::from_str("b"),
645                CFString::from_str("c"),
646            ]
647        );
648    }
649
650    #[test]
651    #[cfg(feature = "CFString")]
652    #[cfg_attr(
653        not(debug_assertions),
654        ignore = "not detected when debug assertions are off"
655    )]
656    #[should_panic = "array was mutated while iterating"]
657    fn mutate_while_iter_unchecked() {
658        let array = CFMutableArray::<CFString>::with_capacity(10);
659        assert_eq!(array.len(), 0);
660
661        let mut iter = unsafe { array.iter_unchecked() };
662        array.append(&CFString::from_str("a"));
663        // Should panic
664        let _ = iter.next();
665    }
666}