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
// Copyright 2013 The Servo Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! Dictionaries of key-value pairs.

pub use core_foundation_sys::dictionary::*;

use core_foundation_sys::base::{CFTypeRef, kCFAllocatorDefault};
use libc::c_void;
use std::mem;
use std::ptr;

use base::{CFType, CFIndexConvertible, TCFType, TCFTypeRef};


declare_TCFType!{
    /// An immutable dictionary of key-value pairs.
    CFDictionary, CFDictionaryRef
}
impl_TCFType!(CFDictionary, CFDictionaryRef, CFDictionaryGetTypeID);
impl_CFTypeDescription!(CFDictionary);

impl CFDictionary {
    pub fn from_CFType_pairs<K: TCFType, V: TCFType>(pairs: &[(K, V)]) -> CFDictionary {
        let (keys, values): (Vec<CFTypeRef>, Vec<CFTypeRef>) = pairs
            .iter()
            .map(|&(ref key, ref value)| (key.as_CFTypeRef(), value.as_CFTypeRef()))
            .unzip();

        unsafe {
            let dictionary_ref = CFDictionaryCreate(kCFAllocatorDefault,
                                                    mem::transmute(keys.as_ptr()),
                                                    mem::transmute(values.as_ptr()),
                                                    keys.len().to_CFIndex(),
                                                    &kCFTypeDictionaryKeyCallBacks,
                                                    &kCFTypeDictionaryValueCallBacks);
            TCFType::wrap_under_create_rule(dictionary_ref)
        }
    }

    #[inline]
    pub fn len(&self) -> usize {
        unsafe {
            CFDictionaryGetCount(self.0) as usize
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    pub fn contains_key(&self, key: *const c_void) -> bool {
        unsafe { CFDictionaryContainsKey(self.0, key) != 0 }
    }

    /// Similar to `contains_key` but acts on a higher level, automatically converting from any
    /// `TCFType` to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn contains_key2<K: TCFType>(&self, key: &K) -> bool {
        self.contains_key(key.as_concrete_TypeRef().as_void_ptr())
    }

    #[inline]
    pub fn find(&self, key: *const c_void) -> Option<*const c_void> {
        unsafe {
            let mut value: *const c_void = ptr::null();
            if CFDictionaryGetValueIfPresent(self.0, key, &mut value) != 0 {
                Some(value)
            } else {
                None
            }
        }
    }

    /// Similar to `find` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn find2<K: TCFType>(&self, key: &K) -> Option<*const c_void> {
        self.find(key.as_concrete_TypeRef().as_void_ptr())
    }

    /// # Panics
    ///
    /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead
    /// of panicking.
    #[inline]
    pub fn get(&self, key: *const c_void) -> *const c_void {
        self.find(key).expect(&format!("No entry found for key {:p}", key))
    }

    /// A convenience function to retrieve `CFType` instances.
    #[inline]
    pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType {
        let value: CFTypeRef = mem::transmute(self.get(key));
        TCFType::wrap_under_get_rule(value)
    }

    pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) {
        let length = self.len();
        let mut keys = Vec::with_capacity(length);
        let mut values = Vec::with_capacity(length);

        unsafe {
            CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr());
            keys.set_len(length);
            values.set_len(length);
        }

        (keys, values)
    }
}

declare_TCFType!{
    /// An mutable dictionary of key-value pairs.
    CFMutableDictionary, CFMutableDictionaryRef
}

impl_TCFType!(CFMutableDictionary, CFMutableDictionaryRef, CFDictionaryGetTypeID);
impl_CFTypeDescription!(CFMutableDictionary);

impl CFMutableDictionary {
    pub fn new() -> Self {
        Self::with_capacity(0)
    }

    pub fn with_capacity(capacity: isize) -> Self {
        unsafe {
            let dictionary_ref = CFDictionaryCreateMutable(kCFAllocatorDefault,
                                                           capacity as _,
                                                           &kCFTypeDictionaryKeyCallBacks,
                                                           &kCFTypeDictionaryValueCallBacks);
            TCFType::wrap_under_create_rule(dictionary_ref)
        }
    }

    pub fn copy_with_capacity(&self, capacity: isize) -> Self {
        unsafe {
            let dictionary_ref = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, capacity as _, self.0);
            TCFType::wrap_under_get_rule(dictionary_ref)
        }
    }

    pub fn from_CFType_pairs<K: TCFType, V: TCFType>(pairs: &[(K, V)]) -> CFMutableDictionary {
        let result = Self::with_capacity(pairs.len() as _);
        unsafe {
            for &(ref key, ref value) in pairs {
                result.add(key.as_CFTypeRef(), value.as_CFTypeRef());
            }
        }
        result
    }

    // Immutable interface

    #[inline]
    pub fn len(&self) -> usize {
        unsafe {
            CFDictionaryGetCount(self.0) as usize
        }
    }

    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    #[inline]
    pub fn contains_key(&self, key: *const c_void) -> bool {
        unsafe {
            CFDictionaryContainsKey(self.0, key) != 0
        }
    }

    /// Similar to `contains_key` but acts on a higher level, automatically converting from any
    /// `TCFType` to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn contains_key2<K: TCFType>(&self, key: &K) -> bool {
        self.contains_key(key.as_concrete_TypeRef().as_void_ptr())
    }

    #[inline]
    pub fn find(&self, key: *const c_void) -> Option<*const c_void> {
        unsafe {
            let mut value: *const c_void = ptr::null();
            if CFDictionaryGetValueIfPresent(self.0, key, &mut value) != 0 {
                Some(value)
            } else {
                None
            }
        }
    }

    /// Similar to `find` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn find2<K: TCFType>(&self, key: &K) -> Option<*const c_void> {
        self.find(key.as_concrete_TypeRef().as_void_ptr())
    }

    /// # Panics
    ///
    /// Panics if the key is not present in the dictionary. Use `find` to get an `Option` instead
    /// of panicking.
    #[inline]
    pub fn get(&self, key: *const c_void) -> *const c_void {
        self.find(key).expect(&format!("No entry found for key {:p}", key))
    }

    /// A convenience function to retrieve `CFType` instances.
    #[inline]
    pub unsafe fn get_CFType(&self, key: *const c_void) -> CFType {
        let value: CFTypeRef = mem::transmute(self.get(key));
        TCFType::wrap_under_get_rule(value)
    }

    pub fn get_keys_and_values(&self) -> (Vec<*const c_void>, Vec<*const c_void>) {
        let length = self.len();
        let mut keys = Vec::with_capacity(length);
        let mut values = Vec::with_capacity(length);

        unsafe {
            CFDictionaryGetKeysAndValues(self.0, keys.as_mut_ptr(), values.as_mut_ptr());
            keys.set_len(length);
            values.set_len(length);
        }

        (keys, values)
    }

    // Mutable interface

    /// Adds the key-value pair to the dictionary if no such key already exist.
    #[inline]
    pub unsafe fn add(&self, key: *const c_void, value: *const c_void) {
        CFDictionaryAddValue(self.0, key, value)
    }

    /// Similar to `add` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn add2<K: TCFType, V: TCFType>(&self, key: &K, value: &V) {
        unsafe {
            self.add(
                key.as_concrete_TypeRef().as_void_ptr(),
                value.as_concrete_TypeRef().as_void_ptr(),
            )
        }
    }

    /// Sets the value of the key in the dictionary.
    #[inline]
    pub unsafe fn set(&self, key: *const c_void, value: *const c_void) {
        CFDictionarySetValue(self.0, key, value)
    }

    /// Similar to `set` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn set2<K: TCFType, V: TCFType>(&self, key: &K, value: &V) {
        unsafe {
            self.set(
                key.as_concrete_TypeRef().as_void_ptr(),
                value.as_concrete_TypeRef().as_void_ptr(),
            )
        }
    }

    /// Replaces the value of the key in the dictionary.
    #[inline]
    pub unsafe fn replace(&self, key: *const c_void, value: *const c_void) {
        CFDictionaryReplaceValue(self.0, key, value)
    }

    /// Similar to `replace` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn replace2<K: TCFType, V: TCFType>(&self, key: &K, value: &V) {
        unsafe {
            self.replace(
                key.as_concrete_TypeRef().as_void_ptr(),
                value.as_concrete_TypeRef().as_void_ptr(),
            )
        }
    }

    /// Removes the value of the key from the dictionary.
    #[inline]
    pub unsafe fn remove(&self, key: *const c_void) {
        CFDictionaryRemoveValue(self.0, key);
    }

    /// Similar to `remove` but acts on a higher level, automatically converting from any `TCFType`
    /// to the raw pointer of its concrete TypeRef.
    #[inline]
    pub fn remove2<K: TCFType>(&self, key: &K) {
        unsafe { self.remove(key.as_concrete_TypeRef().as_void_ptr()) }
    }

    #[inline]
    pub fn remove_all(&self) {
        unsafe { CFDictionaryRemoveAllValues(self.0) }
    }
}


#[cfg(test)]
pub mod test {
    use super::*;
    use base::TCFType;
    use boolean::{CFBoolean, CFBooleanRef};
    use number::CFNumber;
    use string::CFString;


    #[test]
    fn dictionary() {
        let bar = CFString::from_static_string("Bar");
        let baz = CFString::from_static_string("Baz");
        let boo = CFString::from_static_string("Boo");
        let foo = CFString::from_static_string("Foo");
        let tru = CFBoolean::true_value();
        let n42 = CFNumber::from(42);

        let d = CFDictionary::from_CFType_pairs(&[
            (bar.as_CFType(), boo.as_CFType()),
            (baz.as_CFType(), tru.as_CFType()),
            (foo.as_CFType(), n42.as_CFType()),
        ]);

        let (v1, v2) = d.get_keys_and_values();
        assert!(v1 == &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]);
        assert!(v2 == &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]);
    }

    #[test]
    fn mutable_dictionary() {
        let bar = CFString::from_static_string("Bar");
        let baz = CFString::from_static_string("Baz");
        let boo = CFString::from_static_string("Boo");
        let foo = CFString::from_static_string("Foo");
        let tru = CFBoolean::true_value();
        let n42 = CFNumber::from(42);

        let d = CFMutableDictionary::new();
        d.add2(&bar, &boo);
        d.add2(&baz, &tru);
        d.add2(&foo, &n42);
        assert_eq!(d.len(), 3);

        let (v1, v2) = d.get_keys_and_values();
        assert!(v1 == &[bar.as_CFTypeRef(), baz.as_CFTypeRef(), foo.as_CFTypeRef()]);
        assert!(v2 == &[boo.as_CFTypeRef(), tru.as_CFTypeRef(), n42.as_CFTypeRef()]);

        d.remove2(&baz);
        assert_eq!(d.len(), 2);

        let (v1, v2) = d.get_keys_and_values();
        assert!(v1 == &[bar.as_CFTypeRef(), foo.as_CFTypeRef()]);
        assert!(v2 == &[boo.as_CFTypeRef(), n42.as_CFTypeRef()]);

        d.remove_all();
        assert_eq!(d.len(), 0)
    }

    #[test]
    fn dict_find2_and_contains_key2() {
        let dict = CFDictionary::from_CFType_pairs(&[
            (
                CFString::from_static_string("hello"),
                CFBoolean::true_value(),
            ),
        ]);
        let key = CFString::from_static_string("hello");
        let invalid_key = CFString::from_static_string("foobar");

        assert!(dict.contains_key2(&key));
        assert!(!dict.contains_key2(&invalid_key));

        let value = unsafe { CFBoolean::wrap_under_get_rule(dict.find2(&key).unwrap() as CFBooleanRef) };
        assert_eq!(value, CFBoolean::true_value());
        assert_eq!(dict.find2(&invalid_key), None);
    }
}