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 
12 pub use core_foundation_sys::set::*;
13 use core_foundation_sys::base::{CFTypeRef, CFRelease, kCFAllocatorDefault};
14 
15 use base::{CFIndexConvertible, TCFType};
16 
17 use std::os::raw::c_void;
18 use std::marker::PhantomData;
19 
20 /// An immutable bag of elements.
21 pub struct CFSet<T = *const c_void>(CFSetRef, PhantomData<T>);
22 
23 impl<T> Drop for CFSet<T> {
drop(&mut self)24     fn drop(&mut self) {
25         unsafe { CFRelease(self.as_CFTypeRef()) }
26     }
27 }
28 
29 impl_TCFType!(CFSet<T>, CFSetRef, CFSetGetTypeID);
30 impl_CFTypeDescription!(CFSet);
31 
32 impl CFSet {
33     /// Creates a new set from a list of `CFType` instances.
from_slice<T>(elems: &[T]) -> CFSet<T> where T: TCFType34     pub fn from_slice<T>(elems: &[T]) -> CFSet<T> where T: TCFType {
35         unsafe {
36             let elems: Vec<CFTypeRef> = elems.iter().map(|elem| elem.as_CFTypeRef()).collect();
37             let set_ref = CFSetCreate(kCFAllocatorDefault,
38                                       elems.as_ptr(),
39                                       elems.len().to_CFIndex(),
40                                       &kCFTypeSetCallBacks);
41             TCFType::wrap_under_create_rule(set_ref)
42         }
43     }
44 }
45 
46 impl<T> CFSet<T> {
47     /// Get the number of elements in the CFSet
len(&self) -> usize48     pub fn len(&self) -> usize {
49         unsafe {
50             CFSetGetCount(self.0) as usize
51         }
52     }
53 }
54