-
Notifications
You must be signed in to change notification settings - Fork 55
/
Copy pathdictionary.rs
498 lines (455 loc) · 17.6 KB
/
dictionary.rs
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
//! Utilities for the `NSDictionary` and `NSMutableDictionary` classes.
use alloc::vec::Vec;
use core::fmt;
use core::mem;
use core::ptr::NonNull;
use objc2::msg_send;
use objc2::rc::Retained;
#[cfg(feature = "NSObject")]
use objc2::runtime::ProtocolObject;
#[cfg(feature = "NSObject")]
use objc2::AllocAnyThread;
use objc2::Message;
#[cfg(feature = "NSEnumerator")]
use crate::iter;
#[cfg(feature = "NSObject")]
use crate::{util, CopyingHelper, NSCopying};
use crate::{NSDictionary, NSMutableDictionary};
#[cfg(feature = "NSObject")]
fn keys_to_ptr<CopiedKey>(keys: &[&CopiedKey]) -> *mut NonNull<ProtocolObject<dyn NSCopying>>
where
CopiedKey: Message + NSCopying,
{
let keys: *mut NonNull<CopiedKey> = util::ref_ptr_cast_const(keys.as_ptr());
// SAFETY: `CopiedKey` is `Message + NSCopying`, and is therefore safe to cast to
// `ProtocolObject<dyn NSCopying>`.
let keys: *mut NonNull<ProtocolObject<dyn NSCopying>> = keys.cast();
keys
}
/// Convenience creation methods.
impl<KeyType: Message, ObjectType: Message> NSDictionary<KeyType, ObjectType> {
/// Create a new dictionary from a slice of keys, and a slice of objects.
///
/// This is a safe interface to `initWithObjects:forKeys:count:`.
///
/// # Panics
///
/// Panics if the slices have different lengths, as this is likely a
/// programmer error.
///
/// # Example
///
/// ```
/// use objc2_foundation::{NSDictionary, ns_string};
///
/// let dict = NSDictionary::from_slices(
/// &[ns_string!("key1"), ns_string!("key2"), ns_string!("key3")],
/// &[ns_string!("value1"), ns_string!("value2"), ns_string!("value3")],
/// );
///
/// assert_eq!(&*dict.objectForKey(ns_string!("key2")).unwrap(), ns_string!("value2"));
/// ```
#[cfg(feature = "NSObject")]
pub fn from_slices<CopiedKey>(keys: &[&CopiedKey], objects: &[&ObjectType]) -> Retained<Self>
where
// The dictionary copies its keys, which is why we require `NSCopying`
// and use `CopyingHelper` on all input data - we want to ensure that
// the type-system knows that it's not actually e.g. `NSMutableString`
// that is being stored, but instead `NSString`.
CopiedKey: Message + NSCopying + CopyingHelper<Result = KeyType>,
{
// Ensure that we don't read too far into one of the buffers.
assert_eq!(
keys.len(),
objects.len(),
"key slice and object slice should have the same length",
);
let count = keys.len();
let keys = keys_to_ptr(keys);
let objects = util::ref_ptr_cast_const(objects.as_ptr());
// SAFETY:
// - All types that are `Message` use interior mutability, and the
// dictionary extends the lifetime of them internally by retaining
// them.
//
// - The pointers are valid until the method has finished executing,
// at which point the dictionary will have created its own internal
// storage for holding the keys and objects.
//
// - The length is lower than or equal to the length of the two
// pointers.
//
// - While recommended against in the below link, the key _can_ be
// mutated, it'll "just" corrupt the collection's invariants (but
// won't cause undefined behaviour).
//
// This is tested via fuzzing in `collection_interior_mut.rs`.
//
// <https://developer.apple.com/library/archive/documentation/General/Conceptual/CocoaEncyclopedia/ObjectMutability/ObjectMutability.html#//apple_ref/doc/uid/TP40010810-CH5-SW69>
unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), objects, keys, count) }
}
#[cfg(feature = "NSObject")]
pub fn from_retained_objects<CopiedKey>(
keys: &[&CopiedKey],
objects: &[Retained<ObjectType>],
) -> Retained<Self>
where
CopiedKey: Message + NSCopying + CopyingHelper<Result = KeyType>,
{
// Ensure that we don't read too far into one of the buffers.
assert_eq!(
keys.len(),
objects.len(),
"key slice and object slice should have the same length",
);
let count = keys.len();
let keys = keys_to_ptr(keys);
let objects = util::retained_ptr_cast_const(objects.as_ptr());
// SAFETY: Same as `from_slices`.
unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), objects, keys, count) }
}
}
/// Convenience creation methods.
impl<KeyType: Message, ObjectType: Message> NSMutableDictionary<KeyType, ObjectType> {
#[cfg(feature = "NSObject")]
pub fn from_slices<CopiedKey>(keys: &[&CopiedKey], objects: &[&ObjectType]) -> Retained<Self>
where
CopiedKey: Message + NSCopying + CopyingHelper<Result = KeyType>,
{
// Ensure that we don't read too far into one of the buffers.
assert_eq!(
keys.len(),
objects.len(),
"key slice and object slice should have the same length",
);
let count = keys.len();
let keys = keys_to_ptr(keys);
let objects = util::ref_ptr_cast_const(objects.as_ptr());
// SAFETY: Same as `NSDictionary::from_slices`.
unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), objects, keys, count) }
}
#[cfg(feature = "NSObject")]
pub fn from_retained_objects<CopiedKey>(
keys: &[&CopiedKey],
objects: &[Retained<ObjectType>],
) -> Retained<Self>
where
CopiedKey: Message + NSCopying + CopyingHelper<Result = KeyType>,
{
// Ensure that we don't read too far into one of the buffers.
assert_eq!(
keys.len(),
objects.len(),
"key slice and object slice should have the same length",
);
let count = keys.len();
let keys = keys_to_ptr(keys);
let objects = util::retained_ptr_cast_const(objects.as_ptr());
// SAFETY: Same as `NSDictionary::from_retained_objects`.
unsafe { Self::initWithObjects_forKeys_count(Self::alloc(), objects, keys, count) }
}
}
// Note: We'd like to make getter methods take `KeyType: Borrow<KeyType>`
// like `std::collections::HashMap`, so that e.g. `NSDictionary<NSString, V>`
// could take a `&NSObject` as input, and still make that work since
// `NSString` borrows to `NSObject`.
//
// But we can't really, at least not with extra `unsafe` / an extra trait,
// since we don't control how the comparisons happen.
//
// The most useful alternative would probably be to take `impl AsRef<KeyType>`, but
// objc2 classes deref to their superclass anyhow, so let's just use a simple,
// normal reference.
/// Direct, unsafe object accessors.
///
/// Foundation's collection types store their items in such a way that they
/// can give out references to their data without having to autorelease it
/// first, see [the docs][collections-own].
///
/// This means that we can more efficiently access the dictionary's keys and
/// objects, but _only_ if the dictionary isn't mutated via e.g.
/// `NSMutableDictionary` methods while doing so - otherwise, we might end up
/// accessing a deallocated object.
///
/// [collections-own]: https://developer.apple.com/library/archive/documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmPractical.html#//apple_ref/doc/uid/TP40004447-SW12
impl<KeyType: Message, ObjectType: Message> NSDictionary<KeyType, ObjectType> {
/// Get a direct reference to the object corresponding to the key.
///
/// Consider using the [`objectForKey`](Self::objectForKey) method
/// instead, unless you're seeing performance issues from the retaining.
///
/// # Safety
///
/// The dictionary must not be mutated while the reference is live.
#[doc(alias = "objectForKey:")]
#[inline]
pub unsafe fn objectForKey_unchecked(&self, key: &KeyType) -> Option<&ObjectType> {
unsafe { msg_send![self, objectForKey: key] }
}
/// Two vectors containing direct references to respectively the
/// dictionary's keys and objects.
///
/// Consider using the [`to_vecs`](Self::to_vecs) method instead, unless
/// you're seeing performance issues from the retaining.
///
/// # Safety
///
/// The dictionary must not be mutated while the returned references are
/// alive.
#[doc(alias = "getObjects:andKeys:")]
pub unsafe fn to_vecs_unchecked(&self) -> (Vec<&KeyType>, Vec<&ObjectType>) {
let len = self.len();
let mut keys = Vec::with_capacity(len);
let mut objs = Vec::with_capacity(len);
// SAFETY: The pointers are valid.
unsafe {
// No reason to use `getObjects:andKeys:count:`, the dictionary is
// not thread safe, so we know it won't change within this scope.
#[allow(deprecated)]
self.getObjects_andKeys(objs.as_mut_ptr(), keys.as_mut_ptr());
}
// SAFETY: The vecs were just initialized by `getObjects:andKeys:`.
unsafe {
keys.set_len(len);
objs.set_len(len);
}
// SAFETY: `NonNull<T>` and `&T` have the same memory layout, and the
// lifetime is upheld by the caller.
unsafe {
(
mem::transmute::<Vec<NonNull<KeyType>>, Vec<&KeyType>>(keys),
mem::transmute::<Vec<NonNull<ObjectType>>, Vec<&ObjectType>>(objs),
)
}
}
/// Iterate over the dictionary's keys without retaining them.
///
/// Consider using the [`keys`](Self::keys) method instead, unless you're
/// seeing performance issues from the retaining.
///
/// # Safety
///
/// The dictionary must not be mutated for the lifetime of the iterator,
/// or the elements it returns.
#[cfg(feature = "NSEnumerator")]
#[doc(alias = "keyEnumerator")]
#[inline]
pub unsafe fn keys_unchecked(&self) -> KeysUnchecked<'_, KeyType, ObjectType> {
KeysUnchecked(iter::IterUnchecked::new(self))
}
/// Iterate over the dictionary's objects / values without retaining them.
///
/// Consider using the [`objects`](Self::objects) method instead, unless
/// you're seeing performance issues from the retaining.
///
/// # Safety
///
/// The dictionary must not be mutated for the lifetime of the iterator,
/// or the elements it returns.
#[cfg(feature = "NSEnumerator")]
#[doc(alias = "objectEnumerator")]
#[inline]
pub unsafe fn objects_unchecked(&self) -> ObjectsUnchecked<'_, KeyType, ObjectType> {
// SAFETY: Avoiding mutation is upheld by caller.
let enumerator = unsafe { self.objectEnumerator() };
// SAFETY: The enumerator came from the dictionary.
ObjectsUnchecked(unsafe { iter::IterUncheckedWithBackingEnum::new(self, enumerator) })
}
}
/// Various accessor methods.
impl<KeyType: Message, ObjectType: Message> NSDictionary<KeyType, ObjectType> {
/// The amount of elements in the dictionary.
#[doc(alias = "count")]
#[inline]
pub fn len(&self) -> usize {
self.count()
}
/// Whether the dictionary is empty or not.
#[inline]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Two vectors containing respectively the dictionary's keys and objects.
///
/// # Example
///
/// Iterate over the keys and values of the dictionary.
///
/// ```
/// use objc2_foundation::{NSDictionary, ns_string};
///
/// let dict = NSDictionary::from_slices(
/// &[ns_string!("a"), ns_string!("b")],
/// &[ns_string!("a"), ns_string!("b")],
/// );
/// let (keys, objects) = dict.to_vecs();
/// for (key, obj) in keys.into_iter().zip(objects) {
/// assert_eq!(key, obj);
/// }
/// ```
#[doc(alias = "getObjects:")]
pub fn to_vecs(&self) -> (Vec<Retained<KeyType>>, Vec<Retained<ObjectType>>) {
// SAFETY: We retain the elements below, so that we know that the
// dictionary isn't mutated while they are alive.
let (keys, objects) = unsafe { self.to_vecs_unchecked() };
(
keys.into_iter().map(KeyType::retain).collect(),
objects.into_iter().map(ObjectType::retain).collect(),
)
}
/// Iterate over the dictionary's keys.
#[cfg(feature = "NSEnumerator")]
#[doc(alias = "keyEnumerator")]
#[inline]
pub fn keys(&self) -> Keys<'_, KeyType, ObjectType> {
Keys(iter::Iter::new(self))
}
/// Iterate over the dictionary's objects / values.
///
/// # Examples
///
#[cfg_attr(feature = "NSString", doc = "```")]
#[cfg_attr(not(feature = "NSString"), doc = "```ignore")]
/// use objc2_foundation::{ns_string, NSMutableDictionary, NSString};
///
/// let dict = NSMutableDictionary::new();
/// dict.insert(ns_string!("key1"), ns_string!("value1"));
/// dict.insert(ns_string!("key2"), ns_string!("value2"));
/// for obj in dict.objects() {
/// assert!(obj.hasPrefix(ns_string!("value")));
/// }
/// ```
#[cfg(feature = "NSEnumerator")]
#[doc(alias = "objectEnumerator")]
#[inline]
pub fn objects(&self) -> Objects<'_, KeyType, ObjectType> {
// SAFETY: The iterator checks for mutation while enumerating.
let enumerator = unsafe { self.objectEnumerator() };
// SAFETY: The enumerator came from the dictionary.
Objects(unsafe { iter::IterWithBackingEnum::new(self, enumerator) })
}
}
/// Convenience mutation methods.
impl<KeyType: Message, ObjectType: Message> NSMutableDictionary<KeyType, ObjectType> {
/// Inserts a key-value pair into the dictionary.
///
/// If the dictionary did not have this key present, the value is
/// inserted. If the dictionary already had this key present, the value
/// and the key is updated.
///
/// # Examples
///
/// ```
/// use objc2_foundation::{ns_string, NSMutableDictionary, NSObject};
///
/// let dict = NSMutableDictionary::new();
/// dict.insert(ns_string!("key"), &*NSObject::new());
/// ```
#[cfg(feature = "NSObject")]
#[doc(alias = "setObject:forKey:")]
#[inline]
pub fn insert<CopiedKey>(&self, key: &CopiedKey, object: &ObjectType)
where
CopiedKey: Message + NSCopying + CopyingHelper<Result = KeyType>,
{
// SAFETY: The key is copied, and then has the correct type `KeyType`.
unsafe { self.setObject_forKey(object, key) };
}
}
#[cfg(feature = "NSEnumerator")]
unsafe impl<KeyType: Message, ObjectType: Message> iter::FastEnumerationHelper
for NSDictionary<KeyType, ObjectType>
{
// Fast enumeration for dictionaries returns the keys.
type Item = KeyType;
#[inline]
fn maybe_len(&self) -> Option<usize> {
Some(self.len())
}
}
#[cfg(feature = "NSEnumerator")]
unsafe impl<KeyType: Message, ObjectType: Message> iter::FastEnumerationHelper
for NSMutableDictionary<KeyType, ObjectType>
{
// The same goes for mutable dictionaries.
type Item = KeyType;
#[inline]
fn maybe_len(&self) -> Option<usize> {
Some(self.len())
}
}
/// An iterator over the keys of a dictionary.
#[derive(Debug)]
#[cfg(feature = "NSEnumerator")]
pub struct Keys<'a, KeyType: Message, ObjectType: Message>(
iter::Iter<'a, NSDictionary<KeyType, ObjectType>>,
);
#[cfg(feature = "NSEnumerator")]
__impl_iter! {
impl<'a, KeyType: Message, ObjectType: Message> Iterator<Item = Retained<KeyType>> for Keys<'a, KeyType, ObjectType> { ... }
}
/// An iterator over unretained keys of a dictionary.
///
/// # Safety
///
/// The dictionary must not be mutated while this is alive.
#[derive(Debug)]
#[cfg(feature = "NSEnumerator")]
pub struct KeysUnchecked<'a, KeyType: Message, ObjectType: Message>(
iter::IterUnchecked<'a, NSDictionary<KeyType, ObjectType>>,
);
#[cfg(feature = "NSEnumerator")]
__impl_iter! {
impl<'a, KeyType: Message, ObjectType: Message> Iterator<Item = &'a KeyType> for KeysUnchecked<'a, KeyType, ObjectType> { ... }
}
/// An iterator over the objects / values in a dictionary.
#[derive(Debug)]
#[cfg(feature = "NSEnumerator")]
pub struct Objects<'a, KeyType: Message, ObjectType: Message>(
iter::IterWithBackingEnum<
'a,
NSDictionary<KeyType, ObjectType>,
crate::NSEnumerator<ObjectType>,
>,
);
#[cfg(feature = "NSEnumerator")]
__impl_iter! {
impl<'a, KeyType: Message, ObjectType: Message> Iterator<Item = Retained<ObjectType>> for Objects<'a, KeyType, ObjectType> { ... }
}
/// An iterator over unretained objects / values of a dictionary.
///
/// # Safety
///
/// The dictionary must not be mutated while this is alive.
#[derive(Debug)]
#[cfg(feature = "NSEnumerator")]
pub struct ObjectsUnchecked<'a, KeyType: Message, ObjectType: Message + 'a>(
iter::IterUncheckedWithBackingEnum<
'a,
NSDictionary<KeyType, ObjectType>,
crate::NSEnumerator<ObjectType>,
>,
);
#[cfg(feature = "NSEnumerator")]
__impl_iter! {
impl<'a, KeyType: Message, ObjectType: Message> Iterator<Item = &'a ObjectType> for ObjectsUnchecked<'a, KeyType, ObjectType> { ... }
}
impl<KeyType: fmt::Debug + Message, ObjectType: fmt::Debug + Message> fmt::Debug
for NSDictionary<KeyType, ObjectType>
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
// SAFETY: Unsound, use `to_vecs` instead when that doesn't have extra bounds
let (keys, objects) = unsafe { self.to_vecs_unchecked() };
let iter = keys.into_iter().zip(objects);
f.debug_map().entries(iter).finish()
}
}
impl<KeyType: fmt::Debug + Message, ObjectType: fmt::Debug + Message> fmt::Debug
for NSMutableDictionary<KeyType, ObjectType>
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&**self, f)
}
}