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
use core::marker::PhantomData;
use core::mem;
use core::ptr;
use core::slice;
use std::os::raw::c_ulong;
use objc2::rc::{Id, Owned};
use objc2::runtime::Object;
use objc2::{msg_send, Encode, Encoding, Message, RefEncode};
pub struct NSEnumerator<'a, T: Message> {
id: Id<Object, Owned>,
item: PhantomData<&'a T>,
}
impl<'a, T: Message> NSEnumerator<'a, T> {
pub unsafe fn from_ptr(ptr: *mut Object) -> Self {
Self {
id: unsafe { Id::retain_autoreleased(ptr) }.unwrap(),
item: PhantomData,
}
}
}
impl<'a, T: Message> Iterator for NSEnumerator<'a, T> {
type Item = &'a T;
fn next(&mut self) -> Option<&'a T> {
unsafe { msg_send![&mut self.id, nextObject] }
}
}
pub unsafe trait NSFastEnumeration: Message {
type Item: Message;
fn iter_fast(&self) -> NSFastEnumerator<'_, Self> {
NSFastEnumerator::new(self)
}
}
#[repr(C)]
struct NSFastEnumerationState<T: Message> {
state: c_ulong,
items_ptr: *const *const T,
mutations_ptr: *mut c_ulong,
extra: [c_ulong; 5],
}
unsafe impl<T: Message> Encode for NSFastEnumerationState<T> {
const ENCODING: Encoding<'static> = Encoding::Struct(
"?",
&[
Encoding::C_U_LONG,
Encoding::Pointer(&Encoding::Object),
Encoding::Pointer(&Encoding::C_U_LONG),
Encoding::Array(5, &Encoding::C_U_LONG),
],
);
}
unsafe impl<T: Message> RefEncode for NSFastEnumerationState<T> {
const ENCODING_REF: Encoding<'static> = Encoding::Pointer(&Self::ENCODING);
}
fn enumerate<'a, 'b: 'a, C: NSFastEnumeration + ?Sized>(
object: &'b C,
state: &mut NSFastEnumerationState<C::Item>,
buf: &'a mut [*const C::Item],
) -> Option<&'a [*const C::Item]> {
let count: usize = unsafe {
let state = &mut *state;
msg_send![
object,
countByEnumeratingWithState: state,
objects: buf.as_mut_ptr(),
count: buf.len(),
]
};
if count > 0 {
unsafe { Some(slice::from_raw_parts(state.items_ptr, count)) }
} else {
None
}
}
const FAST_ENUM_BUF_SIZE: usize = 16;
pub struct NSFastEnumerator<'a, C: 'a + NSFastEnumeration + ?Sized> {
object: &'a C,
ptr: *const *const C::Item,
end: *const *const C::Item,
state: NSFastEnumerationState<C::Item>,
buf: [*const C::Item; FAST_ENUM_BUF_SIZE],
}
impl<'a, C: NSFastEnumeration + ?Sized> NSFastEnumerator<'a, C> {
fn new(object: &'a C) -> Self {
Self {
object,
ptr: ptr::null(),
end: ptr::null(),
state: unsafe { mem::zeroed() },
buf: [ptr::null(); FAST_ENUM_BUF_SIZE],
}
}
fn update_buf(&mut self) -> bool {
let mutations = if !self.ptr.is_null() {
Some(unsafe { *self.state.mutations_ptr })
} else {
None
};
let next_buf = enumerate(self.object, &mut self.state, &mut self.buf);
if let Some(buf) = next_buf {
if let Some(mutations) = mutations {
assert_eq!(
mutations,
unsafe { *self.state.mutations_ptr },
"Mutation detected during enumeration of object {:p}",
self.object
);
}
self.ptr = buf.as_ptr();
self.end = unsafe { self.ptr.add(buf.len()) };
true
} else {
self.ptr = ptr::null();
self.end = ptr::null();
false
}
}
}
impl<'a, C: NSFastEnumeration + ?Sized> Iterator for NSFastEnumerator<'a, C> {
type Item = &'a C::Item;
fn next(&mut self) -> Option<&'a C::Item> {
if self.ptr == self.end && !self.update_buf() {
None
} else {
unsafe {
let obj = *self.ptr;
self.ptr = self.ptr.offset(1);
Some(obj.as_ref().unwrap_unchecked())
}
}
}
}
#[cfg(test)]
mod tests {
use super::NSFastEnumeration;
use crate::{NSArray, NSValue};
#[test]
fn test_enumerator() {
let vec = (0usize..4).map(NSValue::new).collect();
let array = NSArray::from_vec(vec);
let enumerator = array.iter();
assert_eq!(enumerator.count(), 4);
let enumerator = array.iter();
assert!(enumerator.enumerate().all(|(i, obj)| obj.get() == i));
}
#[test]
fn test_fast_enumerator() {
let vec = (0usize..4).map(NSValue::new).collect();
let array = NSArray::from_vec(vec);
let enumerator = array.iter_fast();
assert_eq!(enumerator.count(), 4);
let enumerator = array.iter_fast();
assert!(enumerator.enumerate().all(|(i, obj)| obj.get() == i));
}
}