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 let len = objects.len();
16 debug_assert!(len < CFIndex::MAX as usize);
17 len as CFIndex
18}
19
20#[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 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
48impl<T: ?Sized> CFArray<T> {
50 #[inline]
53 #[doc(alias = "CFArray::new")]
54 pub fn empty() -> CFRetained<Self>
55 where
56 T: Type,
57 {
58 Self::from_objects(&[])
62 }
63
64 #[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 let ptr = objects.as_ptr().cast::<*const c_void>().cast_mut();
74
75 let array = unsafe { CFArray::new(None, ptr, len, &kCFTypeArrayCallBacks) }
81 .unwrap_or_else(|| failed_creating_array(len));
82
83 unsafe { CFRetained::cast_unchecked::<Self>(array) }
85 }
86
87 #[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 #[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 let ptr = objects.as_ptr().cast::<*const c_void>().cast_mut();
108
109 let array = unsafe { CFArray::new(None, ptr, len, &kCFTypeArrayCallBacks) }
111 .unwrap_or_else(|| failed_creating_array(len));
112
113 unsafe { CFRetained::cast_unchecked::<Self>(array) }
115 }
116}
117
118impl<T: ?Sized> CFMutableArray<T> {
120 #[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 #[inline]
132 #[doc(alias = "CFMutableArray::new")]
133 pub fn with_capacity(capacity: usize) -> CFRetained<Self>
134 where
135 T: Type,
136 {
137 let capacity = capacity.try_into().expect("capacity too high");
139
140 let array = unsafe { CFMutableArray::new(None, capacity, &kCFTypeArrayCallBacks) }
143 .unwrap_or_else(|| failed_creating_array(capacity));
144
145 unsafe { CFRetained::cast_unchecked::<Self>(array) }
148 }
149}
150
151impl<T: ?Sized> CFArray<T> {
175 #[inline]
185 #[doc(alias = "CFArrayGetValueAtIndex")]
186 pub unsafe fn get_unchecked(&self, index: CFIndex) -> &T
187 where
188 T: Type + Sized,
189 {
190 let ptr = unsafe { self.as_opaque().value_at_index(index) };
192 unsafe { &*ptr.cast::<T>() }
198 }
199
200 #[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 length: len as CFIndex,
219 };
220 let mut vec = Vec::<&T>::with_capacity(len);
221
222 let ptr = vec.as_mut_ptr().cast::<*const c_void>();
224 unsafe { self.as_opaque().values(range, ptr) };
226 unsafe { vec.set_len(len) };
228
229 vec
230 }
231
232 #[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
254impl<T: ?Sized> CFArray<T> {
256 #[inline]
258 #[doc(alias = "CFArrayGetCount")]
259 pub fn len(&self) -> usize {
260 self.as_opaque().count() as _
262 }
263
264 #[inline]
266 pub fn is_empty(&self) -> bool {
267 self.len() == 0
268 }
269
270 #[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 let index = index as CFIndex;
282 Some(unsafe { self.get_unchecked(index) }.retain())
292 } else {
293 None
294 }
295 }
296
297 #[cfg(feature = "alloc")]
299 #[doc(alias = "CFArrayGetValues")]
300 pub fn to_vec(&self) -> Vec<CFRetained<T>>
301 where
302 T: Type + Sized,
303 {
304 let vec = unsafe { self.to_vec_unchecked() };
307 vec.into_iter().map(T::retain).collect()
308 }
309
310 #[inline]
312 pub fn iter(&self) -> CFArrayIter<'_, T> {
313 CFArrayIter {
314 array: self,
315 index: 0,
316 }
317 }
318}
319
320impl<T> CFMutableArray<T> {
322 #[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 unsafe { CFMutableArray::append_value(Some(self.as_opaque()), ptr) }
330 }
331
332 #[doc(alias = "CFArrayInsertValueAtIndex")]
338 pub fn insert(&self, index: usize, obj: &T) {
339 let len = self.len();
341 if index <= len {
342 let ptr: *const T = obj;
343 let ptr: *const c_void = ptr.cast();
344 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#[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 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#[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 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 let array = unsafe { CFRetained::cast_unchecked::<CFArray<T>>(self) };
457 CFArrayIntoIter { array, index: 0 }
458 }
459}
460
461#[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 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
507impl<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
520impl<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 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 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 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 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 let _ = iter.next();
665 }
666}