core_foundation/
set.rs

1// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution.
3//
4// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
5// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
6// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
7// option. This file may not be copied, modified, or distributed
8// except according to those terms.
9
10//! An immutable bag of elements.
11
12use core_foundation_sys::base::{kCFAllocatorDefault, CFRelease, CFTypeRef};
13pub use core_foundation_sys::set::*;
14
15use crate::base::{CFIndexConvertible, TCFType};
16
17use std::marker::PhantomData;
18use std::os::raw::c_void;
19
20/// An immutable bag of elements.
21pub struct CFSet<T = *const c_void>(CFSetRef, PhantomData<T>);
22
23impl<T> Drop for CFSet<T> {
24    fn drop(&mut self) {
25        unsafe { CFRelease(self.as_CFTypeRef()) }
26    }
27}
28
29impl_TCFType!(CFSet<T>, CFSetRef, CFSetGetTypeID);
30impl_CFTypeDescription!(CFSet);
31
32impl CFSet {
33    /// Creates a new set from a list of `CFType` instances.
34    pub fn from_slice<T>(elems: &[T]) -> CFSet<T>
35    where
36        T: TCFType,
37    {
38        unsafe {
39            let elems: Vec<CFTypeRef> = elems.iter().map(|elem| elem.as_CFTypeRef()).collect();
40            let set_ref = CFSetCreate(
41                kCFAllocatorDefault,
42                elems.as_ptr(),
43                elems.len().to_CFIndex(),
44                &kCFTypeSetCallBacks,
45            );
46            TCFType::wrap_under_create_rule(set_ref)
47        }
48    }
49}
50
51impl<T> CFSet<T> {
52    /// Get the number of elements in the `CFSet`.
53    pub fn len(&self) -> usize {
54        unsafe { CFSetGetCount(self.0) as usize }
55    }
56
57    /// Returns `true` if the set contains no elements.
58    pub fn is_empty(&self) -> bool {
59        self.len() == 0
60    }
61}