cidre 0.11.1

Apple frameworks bindings for rust
Documentation
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
use crate::{arc, cf, define_cf_type, define_opts};

#[cfg(feature = "ns")]
use crate::ns;

use super::{String, runtime::Type};
use std::{borrow::Cow, cmp::Ordering, ffi::c_void};

#[doc(alias = "CFIndex")]
pub type Index = isize;

#[doc(alias = "CFTypeID")]
pub type TypeId = usize;

#[doc(alias = "CFHashCode")]
pub type HashCode = usize;

define_opts!(
    #[doc(alias = "CFOptionFlags")]
    pub OptionFlags(usize)
);

impl OptionFlags {
    pub const NONE: Self = Self(0);
}

impl PartialEq<usize> for OptionFlags {
    fn eq(&self, other: &usize) -> bool {
        self.0 == *other
    }
}

pub type ComparatorFn = extern "C" fn(
    val1: *const c_void,
    val2: *const c_void,
    context: *mut c_void,
) -> ComparisonResult;

#[doc(alias = "kCFNotFound")]
pub const NOT_FOUND: Index = -1;

#[doc(alias = "CFRange")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(C)]
pub struct Range {
    pub loc: Index,
    pub len: Index,
}

impl Range {
    #[inline]
    pub const fn new(loc: Index, len: Index) -> Self {
        Self { loc, len }
    }

    pub const fn zero() -> Self {
        Self { loc: 0, len: 0 }
    }
}

#[doc(alias = "CFComparisonResult")]
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
#[repr(isize)]
pub enum ComparisonResult {
    LessThen = -1,
    EqualTo = 0,
    GreaterThen = 1,
}

/// ```
/// use cidre::cf;
///
/// let s = cf::Number::from_i32(10);//from_static_string("hello").unwrap();
/// let t = s.get_type_id();
/// unsafe {
///     let desc = cf::type_id_desc(t).unwrap();
///     assert_eq!("CFNumber", desc.to_string());
/// }
/// ```
#[doc(alias = "CFCopyTypeIDDescription")]
pub unsafe fn type_id_desc(type_id: TypeId) -> Option<arc::R<String>> {
    unsafe { CFCopyTypeIDDescription(type_id) }
}

impl From<ComparisonResult> for Ordering {
    /// ```
    /// use cidre::cf::ComparisonResult as CR;
    /// use core::cmp::Ordering as O;
    ///
    /// let less: O = CR::LessThen.into();
    /// let equal: O = CR::EqualTo.into();
    /// let greater: O = CR::GreaterThen.into();
    ///
    /// assert_eq!(less, O::Less);
    /// assert_eq!(equal, O::Equal);
    /// assert_eq!(greater, O::Greater);
    /// ```
    #[inline]
    fn from(o: ComparisonResult) -> Self {
        unsafe { std::mem::transmute(o as i8) }
    }
}

define_cf_type!(
    #[doc(alias = "CFNullRef")]
    #[doc(alias = "CFNull")]
    Null(Type)
);

impl Type {
    #[inline]
    pub fn show(&self) {
        unsafe { CFShow(Some(self)) }
    }

    #[inline]
    pub fn allocator(&self) -> Option<&Allocator> {
        unsafe { CFGetAllocator(self) }
    }

    #[inline]
    pub fn retain_count(&self) -> isize {
        unsafe { CFGetRetainCount(self) }
    }

    /// ```
    /// use cidre::cf;
    ///
    /// let n1 = cf::Number::from_i8(4);
    /// let n2 = cf::Number::from_i32(4);
    /// let n3 = cf::Number::from_f64(3.0);
    ///
    /// assert!(n1.equal(&n2));
    /// assert_eq!(false, n1.equal(&n3));
    /// ```
    #[inline]
    pub fn equal(&self, other: &Type) -> bool {
        unsafe { CFEqual(self, other) }
    }

    #[inline]
    pub fn hash(&self) -> usize {
        unsafe { CFHash(self) }
    }

    #[inline]
    pub fn desc(&self) -> arc::R<String> {
        unsafe { CFCopyDescription(Some(self)).unwrap_unchecked() }
    }
}

impl std::cmp::PartialEq for Type {
    fn eq(&self, other: &Self) -> bool {
        self.equal(other)
    }
}

impl std::cmp::Eq for Type {}

impl std::hash::Hash for Type {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        state.write_usize(self.hash());
    }
}

impl std::fmt::Debug for Type {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let desc = self.desc();
        f.write_str(&Cow::from(desc.as_ref()))
    }
}

impl Null {
    #[inline]
    pub fn type_id() -> cf::TypeId {
        unsafe { CFNullGetTypeID() }
    }

    #[inline]
    pub fn value() -> &'static Null {
        unsafe { kCFNull }
    }

    #[cfg(feature = "ns")]
    #[inline]
    pub fn as_ns(&self) -> &ns::Null {
        unsafe { std::mem::transmute(self) }
    }
}

#[cfg(feature = "ns")]
impl AsRef<ns::Id> for Null {
    fn as_ref(&self) -> &ns::Id {
        self.as_ns()
    }
}

define_cf_type!(
    #[doc(alias = "CFAllocator")]
    Allocator(Type)
);

unsafe impl Send for Allocator {}

pub type AllocatorRetainCb<T = c_void> = extern "C" fn(info: *const T) -> *const T;
pub type AllocatorReleaseCb<T = c_void> = extern "C" fn(info: *const T);
pub type AllocatorCopyDescCb<T = c_void> =
    extern "C" fn(info: *const T) -> Option<arc::R<cf::String>>;
pub type AllocatorAllocateCb<T = c_void> =
    extern "C" fn(alloc_size: Index, hint: cf::OptionFlags, info: *mut T) -> *mut c_void;
pub type AllocatorRealloacteCb<T = c_void> = extern "C" fn(
    ptr: *mut c_void,
    new_size: cf::Index,
    hint: cf::OptionFlags,
    info: *mut T,
) -> *mut c_void;
pub type AllocatorDealloacteCb<T = c_void> = extern "C" fn(ptr: *mut c_void, info: *mut T);
pub type AllocatorPreferredSizeCb<T = c_void> =
    extern "C" fn(size: cf::Index, hint: cf::OptionFlags, info: *mut T) -> Index;

/// A structure that defines the context or operating environment for an allocator
/// (cf::Allocator) object. Every Core Foundation allocator object must have a context
/// defined for it.
#[repr(C)]
pub struct AllocatorContext<T = c_void> {
    pub version: Index,

    /// An untyped pointer to program-defined data. Allocate memory for this data and assign a pointer to it.
    /// This data is often control information for the allocator. You may assign NULL.
    pub info: *const T,

    /// A prototype for a function callback that retains the data pointed to by the info field.
    /// In implementing this function, retain the data you have defined for the allocator context
    /// in this field. (This might make sense only if the data is a Core Foundation object.)
    /// You may set this function pointer to None.
    pub retain: Option<AllocatorRetainCb<T>>,

    /// A prototype for a function callback that releases the data pointed to by the info field.
    /// In implementing this function, release (or free) the data you have defined for the allocator
    /// context. You may set this function pointer to None, but doing so might result in memory leaks.
    pub release: Option<AllocatorReleaseCb<T>>,

    /// A prototype for a function callback that provides a description of the data pointed to
    /// by the info field. In implementing this function, return a reference to a cf::String object
    /// that describes your allocator, particularly some characteristics of your program-defined data.
    /// You may set this function pointer to None, in which case Core Foundation will provide a rudimentary
    /// description.
    pub copy_description: Option<AllocatorCopyDescCb<T>>,

    /// A prototype for a function callback that allocates memory of a requested size.
    /// In implementing this function, allocate a block of memory of at least size
    /// bytes and return a pointer to the start of the block. The hint argument is
    /// a bitfield that you should currently not use (that is, assign 0). The size parameter
    /// should always be greater than 0. If it is not, or if problems in allocation occur,
    /// return NULL. This function pointer may not be assigned NULL.
    pub allocate: AllocatorAllocateCb<T>,

    /// A prototype for a function callback that reallocates memory of a requested size
    /// for an existing block of memory.
    pub reallocate: AllocatorRealloacteCb<T>,

    /// A prototype for a function callback that deallocates a given block of memory.
    /// In implementing this function, make the block of memory pointed to by ptr available
    /// for subsequent reuse by the allocator but unavailable for continued use by the program.
    /// The ptr parameter cannot be NULL and if the ptr parameter is not a block of memory that
    /// has been previously allocated by the allocator, the results are undefined; abnormal
    /// program termination can occur. You can set this callback to None, in which case the
    /// CFAllocatorDeallocate function has no effect.
    pub deallocate: Option<AllocatorDealloacteCb<T>>,

    /// A prototype for a function callback that determines whether there is enough free memory
    /// to satisfy a request. In implementing this function, return the actual size the allocator
    /// is likely to allocate given a request for a block of memory of size size. The hint argument
    /// is a bitfield that you should currently not use.
    pub preferred_size: AllocatorPreferredSizeCb<T>,
}

/// Most of the time when specifying an allocator to Create functions, the None
/// argument indicates "use the default"; this is the same as using Allocator::default()
/// or the return value from cf::Allocator::default().  This assures that you will use
/// the allocator in effect at that time.
impl Allocator {
    #[doc(alias = "CFAllocatorCreate")]
    #[inline]
    pub fn new<T>(context: &mut AllocatorContext<T>) -> Option<arc::R<Allocator>> {
        Self::new_in(context, None)
    }

    #[doc(alias = "CFAllocatorCreate")]
    #[inline]
    pub fn new_in<T>(
        context: &mut AllocatorContext<T>,
        allocator: Option<&Allocator>,
    ) -> Option<arc::R<Allocator>> {
        unsafe { CFAllocatorCreate(allocator, std::mem::transmute(context)) }
    }

    /// This is a synonym for NULL, if you'd rather use a named constant.
    #[doc(alias = "kCFAllocatorDefault")]
    #[inline]
    pub fn default() -> Option<&'static Allocator> {
        unsafe { kCFAllocatorDefault }
    }

    /// Default system allocator; you rarely need to use this.
    #[doc(alias = "kCFAllocatorSystemDefault")]
    #[inline]
    pub fn system_default() -> Option<&'static Allocator> {
        unsafe { kCFAllocatorSystemDefault }
    }

    /// Null allocator which does nothing and allocates no memory. This allocator
    /// is useful as the `bytes_deallocator` in [`cf::Data`] or `contents_deallocator`
    /// in cf::String where the memory should not be freed.
    #[doc(alias = "kCFAllocatorNull")]
    #[inline]
    pub fn null() -> Option<&'static Allocator> {
        unsafe { kCFAllocatorNull }
    }

    /// Special allocator argument to cf::Allocator::create() which means
    /// "use the functions given in the context to allocate the allocator
    /// itself as well
    #[doc(alias = "kCFAllocatorUseContext")]
    #[inline]
    pub fn use_context() -> Option<&'static Allocator> {
        unsafe { kCFAllocatorUseContext }
    }

    #[doc(alias = "CFAllocatorAllocate")]
    #[inline]
    pub unsafe fn allocate(&self, size: Index, hint: OptionFlags) -> *mut c_void {
        unsafe { CFAllocatorAllocate(Some(self), size, hint) }
    }

    #[doc(alias = "CFAllocatorAllocate")]
    #[inline]
    pub unsafe fn allocate_size(size: usize) -> *mut c_void {
        unsafe { CFAllocatorAllocate(None, size as isize, OptionFlags::default()) }
    }

    #[doc(alias = "CFAllocatorReallocate")]
    #[inline]
    pub unsafe fn reallocate(
        &self,
        ptr: *mut c_void,
        new_size: Index,
        hint: OptionFlags,
    ) -> *mut c_void {
        unsafe { CFAllocatorReallocate(self, ptr, new_size, hint) }
    }

    #[doc(alias = "CFAllocatorDeallocate")]
    #[inline]
    pub unsafe fn deallocate(&self, ptr: *mut c_void) {
        unsafe { CFAllocatorDeallocate(self, ptr) }
    }

    #[doc(alias = "CFAllocatorGetPreferredSizeForSize")]
    #[inline]
    pub fn preferred_size(&self, size: Index, hint: cf::OptionFlags) -> Index {
        unsafe { CFAllocatorGetPreferredSizeForSize(self, size, hint) }
    }
}

#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern "C-unwind" {
    fn CFCopyTypeIDDescription(type_id: TypeId) -> Option<arc::R<String>>;

    static kCFNull: &'static Null;

    fn CFNullGetTypeID() -> cf::TypeId;

    static kCFAllocatorDefault: Option<&'static Allocator>;
    static kCFAllocatorSystemDefault: Option<&'static Allocator>;
    static kCFAllocatorNull: Option<&'static Allocator>;
    static kCFAllocatorUseContext: Option<&'static Allocator>;

    fn CFGetAllocator<'a>(cf: &Type) -> Option<&'a Allocator>;
    fn CFShow(cf: Option<&Type>);
    fn CFGetRetainCount(cf: &Type) -> Index;

    fn CFHash(cf: &Type) -> usize;

    fn CFEqual(cf1: &Type, cf2: &Type) -> bool;
    fn CFCopyDescription(cf: Option<&Type>) -> Option<arc::R<String>>;

    fn CFAllocatorAllocate(
        allocator: Option<&Allocator>,
        size: Index,
        hint: OptionFlags,
    ) -> *mut c_void;
    fn CFAllocatorReallocate(
        allocator: &Allocator,
        ptr: *mut c_void,
        new_size: Index,
        hint: OptionFlags,
    ) -> *mut c_void;
    fn CFAllocatorDeallocate(allocator: &Allocator, ptr: *mut c_void);
    fn CFAllocatorCreate(
        allocator: Option<&Allocator>,
        context: &mut AllocatorContext,
    ) -> Option<arc::R<Allocator>>;

    fn CFAllocatorGetPreferredSizeForSize(
        allocator: &Allocator,
        size: Index,
        hint: cf::OptionFlags,
    ) -> Index;
}

#[derive(Debug, Eq, PartialEq, Copy, Clone)]
#[repr(isize)]
pub enum PlistFormat {
    #[doc(alias = "kCFPropertyListOpenStepFormat")]
    OpenStep = 1,

    #[doc(alias = "kCFPropertyListXMLFormat_v1_0")]
    XmlV1_0 = 100,

    #[doc(alias = "kCFPropertyListBinaryFormat_v1_0")]
    BinaryV1_0 = 200,
}

define_opts!(
    #[doc(alias = "CFPropertyListMutabilityOptions")]
    pub PlistMutabilityOpts(cf::OptionFlags)
);

impl PlistMutabilityOpts {
    pub const IMMUTABLE: Self = Self(cf::OptionFlags(0));
    pub const MUTABLE_CONTAINERS: Self = Self(cf::OptionFlags(1 << 0));
    pub const MUTABLE_CONTAINERS_AND_LEAVES: Self = Self(cf::OptionFlags(1 << 1));
}

define_cf_type!(
    #[doc(alias = "CFProperyListRef")]
    Plist(Type)
);

#[cfg(test)]
mod tests {
    use std::ffi::c_void;

    use crate::{arc, cf};

    #[test]
    fn custom_allocator_with_padding() {
        let system = cf::Allocator::system_default().unwrap();
        const PADDING: isize = 10isize;

        extern "C" fn retain(info: *const cf::Allocator) -> *const cf::Allocator {
            eprintln!("retain");
            unsafe {
                let rf = info.as_ref().unwrap().retained();
                let res = rf.as_ref() as *const cf::Allocator;
                std::mem::forget(rf);
                res
            }
        }
        extern "C" fn release(info: *const cf::Allocator) {
            eprintln!("release");
            let retained: arc::R<cf::Allocator> = unsafe { std::mem::transmute(info) };
            std::mem::drop(retained);
        }

        extern "C" fn copy_desc(info: *const cf::Allocator) -> Option<arc::R<cf::String>> {
            unsafe { info.as_ref().map(|a| a.desc()) }
        }

        extern "C" fn allocate(
            size: cf::Index,
            hint: cf::OptionFlags,
            info: *mut cf::Allocator,
        ) -> *mut c_void {
            unsafe {
                info.as_ref()
                    .map(|a| a.allocate(size + PADDING, hint).offset(PADDING))
                    .unwrap_or(std::ptr::null_mut())
            }
        }

        extern "C" fn reallocate(
            ptr: *mut c_void,
            new_size: cf::Index,
            hint: cf::OptionFlags,
            info: *mut cf::Allocator,
        ) -> *mut c_void {
            unsafe {
                info.as_ref()
                    .map(|a| {
                        a.reallocate(ptr.offset(-PADDING), new_size + PADDING, hint)
                            .offset(PADDING)
                    })
                    .unwrap_or(std::ptr::null_mut())
            }
        }

        extern "C" fn deallocate(ptr: *mut c_void, info: *mut cf::Allocator) {
            unsafe { info.as_ref().unwrap().deallocate(ptr.offset(-PADDING)) }
        }

        extern "C" fn preferred_size(
            size: cf::Index,
            hint: cf::OptionFlags,
            info: *mut cf::Allocator,
        ) -> cf::Index {
            unsafe { info.as_ref().unwrap().preferred_size(size + PADDING, hint) - PADDING }
        }

        let mut context = cf::AllocatorContext::<cf::Allocator> {
            version: 0,
            info: system as *const _,
            retain: Some(retain),
            release: Some(release),
            copy_description: Some(copy_desc),
            allocate,
            reallocate,
            deallocate: Some(deallocate),
            preferred_size,
        };

        let alloc = cf::Allocator::new(&mut context).unwrap();

        assert_eq!(alloc.preferred_size(10, cf::OptionFlags::NONE), 10);

        let mem = unsafe { alloc.allocate(10, cf::OptionFlags::NONE) };
        assert!(!mem.is_null());
        let buf: *mut u8 = mem.cast();
        let slice = unsafe { std::slice::from_raw_parts_mut(buf, 10) };
        slice[0] = 10;
        let bigger =
            unsafe { std::slice::from_raw_parts_mut(buf.offset(-PADDING), 10 + PADDING as usize) };

        bigger[0] = 1;
        assert_eq!(bigger[PADDING as usize], 10);
        unsafe { alloc.deallocate(mem) };
    }
}