|
| 1 | +use super::{sys, CoreType}; |
| 2 | +use std::marker::PhantomData; |
| 3 | +use std::mem::MaybeUninit; |
| 4 | +use std::ptr::NonNull; |
| 5 | +use std::{mem, ptr}; |
| 6 | + |
| 7 | +pub trait AsPtr { |
| 8 | + fn as_ptr(&self) -> *const (); |
| 9 | + #[allow(clippy::len_without_is_empty)] |
| 10 | + fn len(&self) -> usize; |
| 11 | +} |
| 12 | + |
| 13 | +impl<T> AsPtr for Vec<T> { |
| 14 | + fn as_ptr(&self) -> *const () { |
| 15 | + self.as_ptr().cast() |
| 16 | + } |
| 17 | + |
| 18 | + fn len(&self) -> usize { |
| 19 | + self.len() |
| 20 | + } |
| 21 | +} |
| 22 | + |
| 23 | +impl<T, const N: usize> AsPtr for [T; N] { |
| 24 | + fn as_ptr(&self) -> *const () { |
| 25 | + <[T]>::as_ptr(self).cast() |
| 26 | + } |
| 27 | + |
| 28 | + fn len(&self) -> usize { |
| 29 | + N |
| 30 | + } |
| 31 | +} |
| 32 | + |
| 33 | +pub trait Pairs { |
| 34 | + type Keys: AsPtr; |
| 35 | + type Values: AsPtr; |
| 36 | + |
| 37 | + fn into_pairs(self) -> (Self::Keys, Self::Values); |
| 38 | +} |
| 39 | + |
| 40 | +impl<K, V, const N: usize> Pairs for [(K, V); N] { |
| 41 | + type Keys = [K; N]; |
| 42 | + type Values = [V; N]; |
| 43 | + |
| 44 | + fn into_pairs(self) -> (Self::Keys, Self::Values) { |
| 45 | + let mut keys: [MaybeUninit<K>; N] = unsafe { MaybeUninit::uninit().assume_init() }; |
| 46 | + let mut values: [MaybeUninit<V>; N] = unsafe { MaybeUninit::uninit().assume_init() }; |
| 47 | + |
| 48 | + for (idx, (key, val)) in self.into_iter().enumerate() { |
| 49 | + keys[idx].write(key); |
| 50 | + values[idx].write(val); |
| 51 | + } |
| 52 | + |
| 53 | + unsafe { |
| 54 | + ( |
| 55 | + mem::transmute_copy::<_, [K; N]>(&keys), |
| 56 | + mem::transmute_copy::<_, [V; N]>(&values), |
| 57 | + ) |
| 58 | + } |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +impl<K, V> Pairs for Vec<(K, V)> { |
| 63 | + type Keys = Vec<K>; |
| 64 | + type Values = Vec<V>; |
| 65 | + |
| 66 | + fn into_pairs(self) -> (Self::Keys, Self::Values) { |
| 67 | + self.into_iter().unzip() |
| 68 | + } |
| 69 | +} |
| 70 | + |
| 71 | +cfty! { |
| 72 | + CFDictionary<K, V> : CFDictionaryGetTypeID |
| 73 | +} |
| 74 | + |
| 75 | +impl<K: CoreType, V: CoreType> CFDictionary<K, V> { |
| 76 | + pub fn new<P: Pairs>(pairs: P) -> CFDictionary<K, V> { |
| 77 | + let (keys, values) = pairs.into_pairs(); |
| 78 | + |
| 79 | + let ptr = unsafe { |
| 80 | + sys::CFDictionaryCreate( |
| 81 | + ptr::null_mut(), |
| 82 | + keys.as_ptr().cast_mut().cast(), |
| 83 | + values.as_ptr().cast_mut().cast(), |
| 84 | + keys.len() as sys::CFIndex, |
| 85 | + &sys::kCFTypeDictionaryKeyCallBacks, |
| 86 | + &sys::kCFTypeDictionaryValueCallBacks, |
| 87 | + ) |
| 88 | + }; |
| 89 | + CFDictionary::new_owned(NonNull::new(ptr.cast_mut()).unwrap()) |
| 90 | + } |
| 91 | +} |
0 commit comments