Debian Codegraph @

third_party/rust/windows-core/src/event.rs

raw
1 use super::*;
2 use core::ffi::c_void;
3 use core::marker::PhantomData;
4 use core::mem::{size_of, transmute_copy};
5 use core::ptr::null_mut;
6 use std::sync::Mutex;
7
8 /// A type that you can use to declare and implement an event of a specified delegate type.
9 ///
10 /// The implementation is thread-safe and designed to avoid contention between events being
11 /// raised and delegates being added or removed.
12 pub struct Event<T: Interface> {
13 swap: Mutex<()>,
14 change: Mutex<()>,
15 delegates: Array<T>,
16 }
17
18 impl<T: Interface> Default for Event<T> {
19 fn default() -> Self {
20 Self::new()
21 }
22 }
23
24 impl<T: Interface> Event<T> {
25 /// Creates a new, empty `Event<T>`.
26 pub fn new() -> Self {
27 Self {
28 delegates: Array::new(),
29 swap: Mutex::default(),
30 change: Mutex::default(),
31 }
32 }
33
34 /// Registers a delegate with the event object.
35 pub fn add(&mut self, delegate: &T) -> Result<i64> {
36 let mut _lock_free_drop = Array::new();
37 Ok({
38 let _change_lock = self.change.lock().unwrap();
39 let mut new_delegates = Array::with_capacity(self.delegates.len() + 1)?;
40 for delegate in self.delegates.as_slice() {
41 new_delegates.push(delegate.clone());
42 }
43 let delegate = Delegate::new(delegate)?;
44 let token = delegate.to_token();
45 new_delegates.push(delegate);
46
47 let _swap_lock = self.swap.lock().unwrap();
48 _lock_free_drop = self.delegates.swap(new_delegates);
49 token
50 })
51 }
52
53 /// Revokes a delegate's registration from the event object.
54 pub fn remove(&mut self, token: i64) -> Result<()> {
55 let mut _lock_free_drop = Array::new();
56 {
57 let _change_lock = self.change.lock().unwrap();
58 if self.delegates.is_empty() {
59 return Ok(());
60 }
61 let mut capacity = self.delegates.len() - 1;
62 let mut new_delegates = Array::new();
63 let mut removed = false;
64 if capacity == 0 {
65 removed = self.delegates.as_slice()[0].to_token() == token;
66 } else {
67 new_delegates = Array::with_capacity(capacity)?;
68 for delegate in self.delegates.as_slice() {
69 if !removed && delegate.to_token() == token {
70 removed = true;
71 continue;
72 }
73 if capacity == 0 {
74 break;
75 }
76 new_delegates.push(delegate.clone());
77 capacity -= 1;
78 }
79 }
80 if removed {
81 let _swap_lock = self.swap.lock().unwrap();
82 _lock_free_drop = self.delegates.swap(new_delegates);
83 }
84 }
85 Ok(())
86 }
87
88 /// Clears the event, removing all delegates.
89 pub fn clear(&mut self) {
90 let mut _lock_free_drop = Array::new();
91 {
92 let _change_lock = self.change.lock().unwrap();
93 if self.delegates.is_empty() {
94 return;
95 }
96 let _swap_lock = self.swap.lock().unwrap();
97 _lock_free_drop = self.delegates.swap(Array::new());
98 }
99 }
100
101 /// Invokes all of the event object's registered delegates with the provided callback.
102 pub fn call<F: FnMut(&T) -> Result<()>>(&mut self, mut callback: F) -> Result<()> {
103 let lock_free_calls = {
104 let _swap_lock = self.swap.lock().unwrap();
105 self.delegates.clone()
106 };
107 for delegate in lock_free_calls.as_slice() {
108 if let Err(error) = delegate.call(&mut callback) {
109 const RPC_E_SERVER_UNAVAILABLE: HRESULT = HRESULT(-2147023174); // HRESULT_FROM_WIN32(RPC_S_SERVER_UNAVAILABLE)
110 if matches!(
111 error.code(),
112 imp::RPC_E_DISCONNECTED | imp::JSCRIPT_E_CANTEXECUTE | RPC_E_SERVER_UNAVAILABLE
113 ) {
114 self.remove(delegate.to_token())?;
115 }
116 }
117 }
118 Ok(())
119 }
120 }
121
122 /// A thread-safe reference-counted array of delegates.
123 struct Array<T: Interface> {
124 buffer: *mut Buffer<T>,
125 len: usize,
126 _phantom: PhantomData<T>,
127 }
128
129 impl<T: Interface> Default for Array<T> {
130 fn default() -> Self {
131 Self::new()
132 }
133 }
134
135 impl<T: Interface> Array<T> {
136 /// Creates a new, empty `Array<T>` with no capacity.
137 fn new() -> Self {
138 Self {
139 buffer: null_mut(),
140 len: 0,
141 _phantom: PhantomData,
142 }
143 }
144
145 /// Creates a new, empty `Array<T>` with the specified capacity.
146 fn with_capacity(capacity: usize) -> Result<Self> {
147 Ok(Self {
148 buffer: Buffer::new(capacity)?,
149 len: 0,
150 _phantom: PhantomData,
151 })
152 }
153
154 /// Swaps the contents of two `Array<T>` objects.
155 fn swap(&mut self, mut other: Self) -> Self {
156 unsafe { core::ptr::swap(&mut self.buffer, &mut other.buffer) };
157 core::mem::swap(&mut self.len, &mut other.len);
158 other
159 }
160
161 /// Returns `true` if the array contains no delegates.
162 fn is_empty(&self) -> bool {
163 self.len == 0
164 }
165
166 /// Returns the number of delegates in the array.
167 fn len(&self) -> usize {
168 self.len
169 }
170
171 /// Appends a delegate to the back of the array.
172 fn push(&mut self, delegate: Delegate<T>) {
173 unsafe {
174 (*self.buffer).as_mut_ptr().add(self.len).write(delegate);
175 self.len += 1;
176 }
177 }
178
179 /// Returns a slice containing of all delegates.
180 fn as_slice(&self) -> &[Delegate<T>] {
181 if self.is_empty() {
182 &[]
183 } else {
184 unsafe { core::slice::from_raw_parts((*self.buffer).as_ptr(), self.len) }
185 }
186 }
187
188 /// Returns a mutable slice of all delegates.
189 fn as_mut_slice(&mut self) -> &mut [Delegate<T>] {
190 if self.is_empty() {
191 &mut []
192 } else {
193 unsafe { core::slice::from_raw_parts_mut((*self.buffer).as_mut_ptr(), self.len) }
194 }
195 }
196 }
197
198 impl<T: Interface> Clone for Array<T> {
199 fn clone(&self) -> Self {
200 if !self.is_empty() {
201 unsafe { (*self.buffer).0.add_ref() };
202 }
203 Self {
204 buffer: self.buffer,
205 len: self.len,
206 _phantom: PhantomData,
207 }
208 }
209 }
210
211 impl<T: Interface> Drop for Array<T> {
212 fn drop(&mut self) {
213 unsafe {
214 if !self.is_empty() && (*self.buffer).0.release() == 0 {
215 core::ptr::drop_in_place(self.as_mut_slice());
216 heap_free(self.buffer as _)
217 }
218 }
219 }
220 }
221
222 /// A reference-counted buffer.
223 #[repr(C)]
224 #[repr(align(8))]
225 struct Buffer<T>(imp::RefCount, PhantomData<T>);
226
227 impl<T: Interface> Buffer<T> {
228 /// Creates a new `Buffer` with the specified size in bytes.
229 fn new(len: usize) -> Result<*mut Self> {
230 if len == 0 {
231 Ok(null_mut())
232 } else {
233 let alloc_size = size_of::<Self>() + len * size_of::<Delegate<T>>();
234 let header = heap_alloc(alloc_size)? as *mut Self;
235 unsafe {
236 header.write(Self(imp::RefCount::new(1), PhantomData));
237 }
238 Ok(header)
239 }
240 }
241
242 /// Returns a raw pointer to the buffer's contents. The resulting pointer might be uninititalized.
243 fn as_ptr(&self) -> *const Delegate<T> {
244 unsafe { (self as *const Self).add(1) as *const _ }
245 }
246
247 /// Returns a raw mutable pointer to the buffer's contents. The resulting pointer might be uninititalized.
248 fn as_mut_ptr(&mut self) -> *mut Delegate<T> {
249 unsafe { (self as *mut Self).add(1) as *mut _ }
250 }
251 }
252
253 /// Holds either a direct or indirect reference to a delegate. A direct reference is typically
254 /// agile while an indirect reference is an agile wrapper.
255 #[derive(Clone)]
256 enum Delegate<T> {
257 Direct(T),
258 Indirect(AgileReference<T>),
259 }
260
261 impl<T: Interface> Delegate<T> {
262 /// Creates a new `Delegate<T>`, containing a suitable reference to the specified delegate.
263 fn new(delegate: &T) -> Result<Self> {
264 if delegate.cast::<imp::IAgileObject>().is_ok() {
265 Ok(Self::Direct(delegate.clone()))
266 } else {
267 Ok(Self::Indirect(AgileReference::new(delegate)?))
268 }
269 }
270
271 /// Returns an encoded token to identify the delegate.
272 fn to_token(&self) -> i64 {
273 unsafe {
274 match self {
275 Self::Direct(delegate) => imp::EncodePointer(transmute_copy(delegate)) as i64,
276 Self::Indirect(delegate) => imp::EncodePointer(transmute_copy(delegate)) as i64,
277 }
278 }
279 }
280
281 /// Invokes the delegates with the provided callback.
282 fn call<F: FnMut(&T) -> Result<()>>(&self, mut callback: F) -> Result<()> {
283 match self {
284 Self::Direct(delegate) => callback(delegate),
285 Self::Indirect(delegate) => callback(&delegate.resolve()?),
286 }
287 }
288 }
289
290 /// Allocate memory of size `bytes` using `malloc` - the `Event` implementation does not
291 /// need to use any particular allocator so `HeapAlloc` need not be used.
292 fn heap_alloc(bytes: usize) -> crate::Result<*mut c_void> {
293 let ptr: *mut c_void = unsafe {
294 extern "C" {
295 fn malloc(bytes: usize) -> *mut c_void;
296 }
297
298 malloc(bytes)
299 };
300
301 if ptr.is_null() {
302 Err(Error::from_hresult(imp::E_OUTOFMEMORY))
303 } else {
304 Ok(ptr)
305 }
306 }
307
308 /// Free memory allocated by `heap_alloc`.
309 unsafe fn heap_free(ptr: *mut c_void) {
310 extern "C" {
311 fn free(ptr: *mut c_void);
312 }
313
314 free(ptr);
315 }