]>
Commit | Line | Data |
---|---|---|
ff7c6d11 XL |
1 | #![warn(missing_docs)] |
2 | ||
3 | /*! | |
4 | # An owning reference. | |
5 | ||
6 | This crate provides the _owning reference_ types `OwningRef` and `OwningRefMut` | |
7 | that enables it to bundle a reference together with the owner of the data it points to. | |
8 | This allows moving and dropping of a `OwningRef` without needing to recreate the reference. | |
9 | ||
10 | This can sometimes be useful because Rust borrowing rules normally prevent | |
11 | moving a type that has been moved from. For example, this kind of code gets rejected: | |
12 | ||
416331ca | 13 | ```compile_fail,E0515 |
ff7c6d11 XL |
14 | fn return_owned_and_referenced<'a>() -> (Vec<u8>, &'a [u8]) { |
15 | let v = vec![1, 2, 3, 4]; | |
16 | let s = &v[1..3]; | |
17 | (v, s) | |
18 | } | |
19 | ``` | |
20 | ||
21 | Even though, from a memory-layout point of view, this can be entirely safe | |
22 | if the new location of the vector still lives longer than the lifetime `'a` | |
23 | of the reference because the backing allocation of the vector does not change. | |
24 | ||
25 | This library enables this safe usage by keeping the owner and the reference | |
26 | bundled together in a wrapper type that ensure that lifetime constraint: | |
27 | ||
28 | ```rust | |
29 | # extern crate owning_ref; | |
30 | # use owning_ref::OwningRef; | |
31 | # fn main() { | |
32 | fn return_owned_and_referenced() -> OwningRef<Vec<u8>, [u8]> { | |
33 | let v = vec![1, 2, 3, 4]; | |
34 | let or = OwningRef::new(v); | |
35 | let or = or.map(|v| &v[1..3]); | |
36 | or | |
37 | } | |
38 | # } | |
39 | ``` | |
40 | ||
41 | It works by requiring owner types to dereference to stable memory locations | |
42 | and preventing mutable access to root containers, which in practice requires heap allocation | |
43 | as provided by `Box<T>`, `Rc<T>`, etc. | |
44 | ||
45 | Also provided are typedefs for common owner type combinations, | |
416331ca XL |
46 | which allow for less verbose type signatures. |
47 | For example, `BoxRef<T>` instead of `OwningRef<Box<T>, T>`. | |
ff7c6d11 XL |
48 | |
49 | The crate also provides the more advanced `OwningHandle` type, | |
50 | which allows more freedom in bundling a dependent handle object | |
51 | along with the data it depends on, at the cost of some unsafe needed in the API. | |
52 | See the documentation around `OwningHandle` for more details. | |
53 | ||
54 | # Examples | |
55 | ||
56 | ## Basics | |
57 | ||
58 | ``` | |
59 | extern crate owning_ref; | |
60 | use owning_ref::BoxRef; | |
61 | ||
62 | fn main() { | |
63 | // Create an array owned by a Box. | |
64 | let arr = Box::new([1, 2, 3, 4]) as Box<[i32]>; | |
65 | ||
66 | // Transfer into a BoxRef. | |
67 | let arr: BoxRef<[i32]> = BoxRef::new(arr); | |
68 | assert_eq!(&*arr, &[1, 2, 3, 4]); | |
69 | ||
70 | // We can slice the array without losing ownership or changing type. | |
71 | let arr: BoxRef<[i32]> = arr.map(|arr| &arr[1..3]); | |
72 | assert_eq!(&*arr, &[2, 3]); | |
73 | ||
74 | // Also works for Arc, Rc, String and Vec! | |
75 | } | |
76 | ``` | |
77 | ||
78 | ## Caching a reference to a struct field | |
79 | ||
80 | ``` | |
81 | extern crate owning_ref; | |
82 | use owning_ref::BoxRef; | |
83 | ||
84 | fn main() { | |
85 | struct Foo { | |
86 | tag: u32, | |
87 | x: u16, | |
88 | y: u16, | |
89 | z: u16, | |
90 | } | |
91 | let foo = Foo { tag: 1, x: 100, y: 200, z: 300 }; | |
92 | ||
93 | let or = BoxRef::new(Box::new(foo)).map(|foo| { | |
94 | match foo.tag { | |
95 | 0 => &foo.x, | |
96 | 1 => &foo.y, | |
97 | 2 => &foo.z, | |
98 | _ => panic!(), | |
99 | } | |
100 | }); | |
101 | ||
102 | assert_eq!(*or, 200); | |
103 | } | |
104 | ``` | |
105 | ||
106 | ## Caching a reference to an entry in a vector | |
107 | ||
108 | ``` | |
109 | extern crate owning_ref; | |
110 | use owning_ref::VecRef; | |
111 | ||
112 | fn main() { | |
113 | let v = VecRef::new(vec![1, 2, 3, 4, 5]).map(|v| &v[3]); | |
114 | assert_eq!(*v, 4); | |
115 | } | |
116 | ``` | |
117 | ||
118 | ## Caching a subslice of a String | |
119 | ||
120 | ``` | |
121 | extern crate owning_ref; | |
122 | use owning_ref::StringRef; | |
123 | ||
124 | fn main() { | |
125 | let s = StringRef::new("hello world".to_owned()) | |
126 | .map(|s| s.split(' ').nth(1).unwrap()); | |
127 | ||
128 | assert_eq!(&*s, "world"); | |
129 | } | |
130 | ``` | |
131 | ||
132 | ## Reference counted slices that share ownership of the backing storage | |
133 | ||
134 | ``` | |
135 | extern crate owning_ref; | |
136 | use owning_ref::RcRef; | |
137 | use std::rc::Rc; | |
138 | ||
139 | fn main() { | |
140 | let rc: RcRef<[i32]> = RcRef::new(Rc::new([1, 2, 3, 4]) as Rc<[i32]>); | |
141 | assert_eq!(&*rc, &[1, 2, 3, 4]); | |
142 | ||
143 | let rc_a: RcRef<[i32]> = rc.clone().map(|s| &s[0..2]); | |
144 | let rc_b = rc.clone().map(|s| &s[1..3]); | |
145 | let rc_c = rc.clone().map(|s| &s[2..4]); | |
146 | assert_eq!(&*rc_a, &[1, 2]); | |
147 | assert_eq!(&*rc_b, &[2, 3]); | |
148 | assert_eq!(&*rc_c, &[3, 4]); | |
149 | ||
150 | let rc_c_a = rc_c.clone().map(|s| &s[1]); | |
151 | assert_eq!(&*rc_c_a, &4); | |
152 | } | |
153 | ``` | |
154 | ||
155 | ## Atomic reference counted slices that share ownership of the backing storage | |
156 | ||
157 | ``` | |
158 | extern crate owning_ref; | |
159 | use owning_ref::ArcRef; | |
160 | use std::sync::Arc; | |
161 | ||
162 | fn main() { | |
163 | use std::thread; | |
164 | ||
165 | fn par_sum(rc: ArcRef<[i32]>) -> i32 { | |
166 | if rc.len() == 0 { | |
167 | return 0; | |
168 | } else if rc.len() == 1 { | |
169 | return rc[0]; | |
170 | } | |
171 | let mid = rc.len() / 2; | |
172 | let left = rc.clone().map(|s| &s[..mid]); | |
173 | let right = rc.map(|s| &s[mid..]); | |
174 | ||
175 | let left = thread::spawn(move || par_sum(left)); | |
176 | let right = thread::spawn(move || par_sum(right)); | |
177 | ||
178 | left.join().unwrap() + right.join().unwrap() | |
179 | } | |
180 | ||
181 | let rc: Arc<[i32]> = Arc::new([1, 2, 3, 4]); | |
182 | let rc: ArcRef<[i32]> = rc.into(); | |
183 | ||
184 | assert_eq!(par_sum(rc), 10); | |
185 | } | |
186 | ``` | |
187 | ||
188 | ## References into RAII locks | |
189 | ||
190 | ``` | |
191 | extern crate owning_ref; | |
192 | use owning_ref::RefRef; | |
193 | use std::cell::{RefCell, Ref}; | |
194 | ||
195 | fn main() { | |
196 | let refcell = RefCell::new((1, 2, 3, 4)); | |
197 | // Also works with Mutex and RwLock | |
198 | ||
199 | let refref = { | |
200 | let refref = RefRef::new(refcell.borrow()).map(|x| &x.3); | |
201 | assert_eq!(*refref, 4); | |
202 | ||
203 | // We move the RAII lock and the reference to one of | |
204 | // the subfields in the data it guards here: | |
205 | refref | |
206 | }; | |
207 | ||
208 | assert_eq!(*refref, 4); | |
209 | ||
210 | drop(refref); | |
211 | ||
212 | assert_eq!(*refcell.borrow(), (1, 2, 3, 4)); | |
213 | } | |
214 | ``` | |
215 | ||
216 | ## Mutable reference | |
217 | ||
218 | When the owned container implements `DerefMut`, it is also possible to make | |
0731742a | 219 | a _mutable owning reference_. (e.g., with `Box`, `RefMut`, `MutexGuard`) |
ff7c6d11 XL |
220 | |
221 | ``` | |
222 | extern crate owning_ref; | |
223 | use owning_ref::RefMutRefMut; | |
224 | use std::cell::{RefCell, RefMut}; | |
225 | ||
226 | fn main() { | |
227 | let refcell = RefCell::new((1, 2, 3, 4)); | |
228 | ||
229 | let mut refmut_refmut = { | |
230 | let mut refmut_refmut = RefMutRefMut::new(refcell.borrow_mut()).map_mut(|x| &mut x.3); | |
231 | assert_eq!(*refmut_refmut, 4); | |
232 | *refmut_refmut *= 2; | |
233 | ||
234 | refmut_refmut | |
235 | }; | |
236 | ||
237 | assert_eq!(*refmut_refmut, 8); | |
238 | *refmut_refmut *= 2; | |
239 | ||
240 | drop(refmut_refmut); | |
241 | ||
242 | assert_eq!(*refcell.borrow(), (1, 2, 3, 16)); | |
243 | } | |
244 | ``` | |
245 | */ | |
246 | ||
dfeec247 XL |
247 | pub use stable_deref_trait::{ |
248 | CloneStableDeref as CloneStableAddress, StableDeref as StableAddress, | |
249 | }; | |
0531ce1d | 250 | use std::mem; |
ff7c6d11 XL |
251 | |
252 | /// An owning reference. | |
253 | /// | |
254 | /// This wraps an owner `O` and a reference `&T` pointing | |
255 | /// at something reachable from `O::Target` while keeping | |
256 | /// the ability to move `self` around. | |
257 | /// | |
258 | /// The owner is usually a pointer that points at some base type. | |
259 | /// | |
260 | /// For more details and examples, see the module and method docs. | |
261 | pub struct OwningRef<O, T: ?Sized> { | |
262 | owner: O, | |
263 | reference: *const T, | |
264 | } | |
265 | ||
266 | /// An mutable owning reference. | |
267 | /// | |
268 | /// This wraps an owner `O` and a reference `&mut T` pointing | |
269 | /// at something reachable from `O::Target` while keeping | |
270 | /// the ability to move `self` around. | |
271 | /// | |
272 | /// The owner is usually a pointer that points at some base type. | |
273 | /// | |
274 | /// For more details and examples, see the module and method docs. | |
275 | pub struct OwningRefMut<O, T: ?Sized> { | |
276 | owner: O, | |
277 | reference: *mut T, | |
278 | } | |
279 | ||
280 | /// Helper trait for an erased concrete type an owner dereferences to. | |
281 | /// This is used in form of a trait object for keeping | |
282 | /// something around to (virtually) call the destructor. | |
283 | pub trait Erased {} | |
284 | impl<T> Erased for T {} | |
285 | ||
0531ce1d | 286 | /// Helper trait for erasing the concrete type of what an owner dereferences to, |
ff7c6d11 XL |
287 | /// for example `Box<T> -> Box<Erased>`. This would be unneeded with |
288 | /// higher kinded types support in the language. | |
416331ca | 289 | #[allow(unused_lifetimes)] |
ff7c6d11 XL |
290 | pub unsafe trait IntoErased<'a> { |
291 | /// Owner with the dereference type substituted to `Erased`. | |
292 | type Erased; | |
9fa01778 | 293 | /// Performs the type erasure. |
ff7c6d11 XL |
294 | fn into_erased(self) -> Self::Erased; |
295 | } | |
296 | ||
0531ce1d XL |
297 | /// Helper trait for erasing the concrete type of what an owner dereferences to, |
298 | /// for example `Box<T> -> Box<Erased + Send>`. This would be unneeded with | |
299 | /// higher kinded types support in the language. | |
416331ca | 300 | #[allow(unused_lifetimes)] |
0531ce1d XL |
301 | pub unsafe trait IntoErasedSend<'a> { |
302 | /// Owner with the dereference type substituted to `Erased + Send`. | |
303 | type Erased: Send; | |
9fa01778 | 304 | /// Performs the type erasure. |
0531ce1d XL |
305 | fn into_erased_send(self) -> Self::Erased; |
306 | } | |
307 | ||
308 | /// Helper trait for erasing the concrete type of what an owner dereferences to, | |
ff7c6d11 XL |
309 | /// for example `Box<T> -> Box<Erased + Send + Sync>`. This would be unneeded with |
310 | /// higher kinded types support in the language. | |
416331ca | 311 | #[allow(unused_lifetimes)] |
0531ce1d | 312 | pub unsafe trait IntoErasedSendSync<'a> { |
ff7c6d11 XL |
313 | /// Owner with the dereference type substituted to `Erased + Send + Sync`. |
314 | type Erased: Send + Sync; | |
9fa01778 | 315 | /// Performs the type erasure. |
ff7c6d11 XL |
316 | fn into_erased_send_sync(self) -> Self::Erased; |
317 | } | |
318 | ||
319 | ///////////////////////////////////////////////////////////////////////////// | |
320 | // OwningRef | |
321 | ///////////////////////////////////////////////////////////////////////////// | |
322 | ||
323 | impl<O, T: ?Sized> OwningRef<O, T> { | |
324 | /// Creates a new owning reference from a owner | |
325 | /// initialized to the direct dereference of it. | |
326 | /// | |
327 | /// # Example | |
328 | /// ``` | |
329 | /// extern crate owning_ref; | |
330 | /// use owning_ref::OwningRef; | |
331 | /// | |
332 | /// fn main() { | |
333 | /// let owning_ref = OwningRef::new(Box::new(42)); | |
334 | /// assert_eq!(*owning_ref, 42); | |
335 | /// } | |
336 | /// ``` | |
337 | pub fn new(o: O) -> Self | |
dfeec247 XL |
338 | where |
339 | O: StableAddress, | |
340 | O: Deref<Target = T>, | |
ff7c6d11 | 341 | { |
dfeec247 | 342 | OwningRef { reference: &*o, owner: o } |
ff7c6d11 XL |
343 | } |
344 | ||
345 | /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait. | |
346 | /// Instead, the caller is responsible to make the same promises as implementing the trait. | |
347 | /// | |
348 | /// This is useful for cases where coherence rules prevents implementing the trait | |
349 | /// without adding a dependency to this crate in a third-party library. | |
350 | pub unsafe fn new_assert_stable_address(o: O) -> Self | |
dfeec247 XL |
351 | where |
352 | O: Deref<Target = T>, | |
ff7c6d11 | 353 | { |
dfeec247 | 354 | OwningRef { reference: &*o, owner: o } |
ff7c6d11 XL |
355 | } |
356 | ||
357 | /// Converts `self` into a new owning reference that points at something reachable | |
358 | /// from the previous one. | |
359 | /// | |
360 | /// This can be a reference to a field of `U`, something reachable from a field of | |
361 | /// `U`, or even something unrelated with a `'static` lifetime. | |
362 | /// | |
363 | /// # Example | |
364 | /// ``` | |
365 | /// extern crate owning_ref; | |
366 | /// use owning_ref::OwningRef; | |
367 | /// | |
368 | /// fn main() { | |
369 | /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); | |
370 | /// | |
371 | /// // create a owning reference that points at the | |
372 | /// // third element of the array. | |
373 | /// let owning_ref = owning_ref.map(|array| &array[2]); | |
374 | /// assert_eq!(*owning_ref, 3); | |
375 | /// } | |
376 | /// ``` | |
377 | pub fn map<F, U: ?Sized>(self, f: F) -> OwningRef<O, U> | |
dfeec247 XL |
378 | where |
379 | O: StableAddress, | |
380 | F: FnOnce(&T) -> &U, | |
ff7c6d11 | 381 | { |
dfeec247 | 382 | OwningRef { reference: f(&self), owner: self.owner } |
ff7c6d11 XL |
383 | } |
384 | ||
385 | /// Tries to convert `self` into a new owning reference that points | |
386 | /// at something reachable from the previous one. | |
387 | /// | |
388 | /// This can be a reference to a field of `U`, something reachable from a field of | |
389 | /// `U`, or even something unrelated with a `'static` lifetime. | |
390 | /// | |
391 | /// # Example | |
392 | /// ``` | |
393 | /// extern crate owning_ref; | |
394 | /// use owning_ref::OwningRef; | |
395 | /// | |
396 | /// fn main() { | |
397 | /// let owning_ref = OwningRef::new(Box::new([1, 2, 3, 4])); | |
398 | /// | |
399 | /// // create a owning reference that points at the | |
400 | /// // third element of the array. | |
401 | /// let owning_ref = owning_ref.try_map(|array| { | |
402 | /// if array[2] == 3 { Ok(&array[2]) } else { Err(()) } | |
403 | /// }); | |
404 | /// assert_eq!(*owning_ref.unwrap(), 3); | |
405 | /// } | |
406 | /// ``` | |
407 | pub fn try_map<F, U: ?Sized, E>(self, f: F) -> Result<OwningRef<O, U>, E> | |
dfeec247 XL |
408 | where |
409 | O: StableAddress, | |
410 | F: FnOnce(&T) -> Result<&U, E>, | |
ff7c6d11 | 411 | { |
dfeec247 | 412 | Ok(OwningRef { reference: f(&self)?, owner: self.owner }) |
ff7c6d11 XL |
413 | } |
414 | ||
415 | /// Converts `self` into a new owning reference with a different owner type. | |
416 | /// | |
417 | /// The new owner type needs to still contain the original owner in some way | |
418 | /// so that the reference into it remains valid. This function is marked unsafe | |
419 | /// because the user needs to manually uphold this guarantee. | |
420 | pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRef<P, T> | |
dfeec247 XL |
421 | where |
422 | O: StableAddress, | |
423 | P: StableAddress, | |
424 | F: FnOnce(O) -> P, | |
ff7c6d11 | 425 | { |
dfeec247 | 426 | OwningRef { reference: self.reference, owner: f(self.owner) } |
ff7c6d11 XL |
427 | } |
428 | ||
429 | /// Converts `self` into a new owning reference where the owner is wrapped | |
430 | /// in an additional `Box<O>`. | |
431 | /// | |
432 | /// This can be used to safely erase the owner of any `OwningRef<O, T>` | |
433 | /// to a `OwningRef<Box<Erased>, T>`. | |
434 | pub fn map_owner_box(self) -> OwningRef<Box<O>, T> { | |
dfeec247 | 435 | OwningRef { reference: self.reference, owner: Box::new(self.owner) } |
ff7c6d11 XL |
436 | } |
437 | ||
438 | /// Erases the concrete base type of the owner with a trait object. | |
439 | /// | |
440 | /// This allows mixing of owned references with different owner base types. | |
441 | /// | |
442 | /// # Example | |
443 | /// ``` | |
444 | /// extern crate owning_ref; | |
445 | /// use owning_ref::{OwningRef, Erased}; | |
446 | /// | |
447 | /// fn main() { | |
0731742a | 448 | /// // N.B., using the concrete types here for explicitness. |
ff7c6d11 XL |
449 | /// // For less verbose code type aliases like `BoxRef` are provided. |
450 | /// | |
451 | /// let owning_ref_a: OwningRef<Box<[i32; 4]>, [i32; 4]> | |
452 | /// = OwningRef::new(Box::new([1, 2, 3, 4])); | |
453 | /// | |
454 | /// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>> | |
455 | /// = OwningRef::new(Box::new(vec![(0, false), (1, true)])); | |
456 | /// | |
457 | /// let owning_ref_a: OwningRef<Box<[i32; 4]>, i32> | |
458 | /// = owning_ref_a.map(|a| &a[0]); | |
459 | /// | |
460 | /// let owning_ref_b: OwningRef<Box<Vec<(i32, bool)>>, i32> | |
461 | /// = owning_ref_b.map(|a| &a[1].0); | |
462 | /// | |
463 | /// let owning_refs: [OwningRef<Box<Erased>, i32>; 2] | |
464 | /// = [owning_ref_a.erase_owner(), owning_ref_b.erase_owner()]; | |
465 | /// | |
466 | /// assert_eq!(*owning_refs[0], 1); | |
467 | /// assert_eq!(*owning_refs[1], 1); | |
468 | /// } | |
469 | /// ``` | |
470 | pub fn erase_owner<'a>(self) -> OwningRef<O::Erased, T> | |
dfeec247 XL |
471 | where |
472 | O: IntoErased<'a>, | |
ff7c6d11 | 473 | { |
dfeec247 | 474 | OwningRef { reference: self.reference, owner: self.owner.into_erased() } |
ff7c6d11 XL |
475 | } |
476 | ||
0531ce1d XL |
477 | /// Erases the concrete base type of the owner with a trait object which implements `Send`. |
478 | /// | |
479 | /// This allows mixing of owned references with different owner base types. | |
480 | pub fn erase_send_owner<'a>(self) -> OwningRef<O::Erased, T> | |
dfeec247 XL |
481 | where |
482 | O: IntoErasedSend<'a>, | |
0531ce1d | 483 | { |
dfeec247 | 484 | OwningRef { reference: self.reference, owner: self.owner.into_erased_send() } |
0531ce1d XL |
485 | } |
486 | ||
416331ca XL |
487 | /// Erases the concrete base type of the owner with a trait object |
488 | /// which implements `Send` and `Sync`. | |
ff7c6d11 XL |
489 | /// |
490 | /// This allows mixing of owned references with different owner base types. | |
491 | pub fn erase_send_sync_owner<'a>(self) -> OwningRef<O::Erased, T> | |
dfeec247 XL |
492 | where |
493 | O: IntoErasedSendSync<'a>, | |
ff7c6d11 | 494 | { |
dfeec247 | 495 | OwningRef { reference: self.reference, owner: self.owner.into_erased_send_sync() } |
ff7c6d11 XL |
496 | } |
497 | ||
416331ca | 498 | // UNIMPLEMENTED: wrap_owner |
ff7c6d11 XL |
499 | |
500 | // FIXME: Naming convention? | |
501 | /// A getter for the underlying owner. | |
502 | pub fn owner(&self) -> &O { | |
503 | &self.owner | |
504 | } | |
505 | ||
506 | // FIXME: Naming convention? | |
507 | /// Discards the reference and retrieves the owner. | |
508 | pub fn into_inner(self) -> O { | |
509 | self.owner | |
510 | } | |
511 | } | |
512 | ||
513 | impl<O, T: ?Sized> OwningRefMut<O, T> { | |
514 | /// Creates a new owning reference from a owner | |
515 | /// initialized to the direct dereference of it. | |
516 | /// | |
517 | /// # Example | |
518 | /// ``` | |
519 | /// extern crate owning_ref; | |
520 | /// use owning_ref::OwningRefMut; | |
521 | /// | |
522 | /// fn main() { | |
523 | /// let owning_ref_mut = OwningRefMut::new(Box::new(42)); | |
524 | /// assert_eq!(*owning_ref_mut, 42); | |
525 | /// } | |
526 | /// ``` | |
527 | pub fn new(mut o: O) -> Self | |
dfeec247 XL |
528 | where |
529 | O: StableAddress, | |
530 | O: DerefMut<Target = T>, | |
ff7c6d11 | 531 | { |
dfeec247 | 532 | OwningRefMut { reference: &mut *o, owner: o } |
ff7c6d11 XL |
533 | } |
534 | ||
535 | /// Like `new`, but doesn’t require `O` to implement the `StableAddress` trait. | |
536 | /// Instead, the caller is responsible to make the same promises as implementing the trait. | |
537 | /// | |
538 | /// This is useful for cases where coherence rules prevents implementing the trait | |
539 | /// without adding a dependency to this crate in a third-party library. | |
540 | pub unsafe fn new_assert_stable_address(mut o: O) -> Self | |
dfeec247 XL |
541 | where |
542 | O: DerefMut<Target = T>, | |
ff7c6d11 | 543 | { |
dfeec247 | 544 | OwningRefMut { reference: &mut *o, owner: o } |
ff7c6d11 XL |
545 | } |
546 | ||
547 | /// Converts `self` into a new _shared_ owning reference that points at | |
548 | /// something reachable from the previous one. | |
549 | /// | |
550 | /// This can be a reference to a field of `U`, something reachable from a field of | |
551 | /// `U`, or even something unrelated with a `'static` lifetime. | |
552 | /// | |
553 | /// # Example | |
554 | /// ``` | |
555 | /// extern crate owning_ref; | |
556 | /// use owning_ref::OwningRefMut; | |
557 | /// | |
558 | /// fn main() { | |
559 | /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); | |
560 | /// | |
561 | /// // create a owning reference that points at the | |
562 | /// // third element of the array. | |
563 | /// let owning_ref = owning_ref_mut.map(|array| &array[2]); | |
564 | /// assert_eq!(*owning_ref, 3); | |
565 | /// } | |
566 | /// ``` | |
567 | pub fn map<F, U: ?Sized>(mut self, f: F) -> OwningRef<O, U> | |
dfeec247 XL |
568 | where |
569 | O: StableAddress, | |
570 | F: FnOnce(&mut T) -> &U, | |
ff7c6d11 | 571 | { |
dfeec247 | 572 | OwningRef { reference: f(&mut self), owner: self.owner } |
ff7c6d11 XL |
573 | } |
574 | ||
575 | /// Converts `self` into a new _mutable_ owning reference that points at | |
576 | /// something reachable from the previous one. | |
577 | /// | |
578 | /// This can be a reference to a field of `U`, something reachable from a field of | |
579 | /// `U`, or even something unrelated with a `'static` lifetime. | |
580 | /// | |
581 | /// # Example | |
582 | /// ``` | |
583 | /// extern crate owning_ref; | |
584 | /// use owning_ref::OwningRefMut; | |
585 | /// | |
586 | /// fn main() { | |
587 | /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); | |
588 | /// | |
589 | /// // create a owning reference that points at the | |
590 | /// // third element of the array. | |
591 | /// let owning_ref_mut = owning_ref_mut.map_mut(|array| &mut array[2]); | |
592 | /// assert_eq!(*owning_ref_mut, 3); | |
593 | /// } | |
594 | /// ``` | |
595 | pub fn map_mut<F, U: ?Sized>(mut self, f: F) -> OwningRefMut<O, U> | |
dfeec247 XL |
596 | where |
597 | O: StableAddress, | |
598 | F: FnOnce(&mut T) -> &mut U, | |
ff7c6d11 | 599 | { |
dfeec247 | 600 | OwningRefMut { reference: f(&mut self), owner: self.owner } |
ff7c6d11 XL |
601 | } |
602 | ||
603 | /// Tries to convert `self` into a new _shared_ owning reference that points | |
604 | /// at something reachable from the previous one. | |
605 | /// | |
606 | /// This can be a reference to a field of `U`, something reachable from a field of | |
607 | /// `U`, or even something unrelated with a `'static` lifetime. | |
608 | /// | |
609 | /// # Example | |
610 | /// ``` | |
611 | /// extern crate owning_ref; | |
612 | /// use owning_ref::OwningRefMut; | |
613 | /// | |
614 | /// fn main() { | |
615 | /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); | |
616 | /// | |
617 | /// // create a owning reference that points at the | |
618 | /// // third element of the array. | |
619 | /// let owning_ref = owning_ref_mut.try_map(|array| { | |
620 | /// if array[2] == 3 { Ok(&array[2]) } else { Err(()) } | |
621 | /// }); | |
622 | /// assert_eq!(*owning_ref.unwrap(), 3); | |
623 | /// } | |
624 | /// ``` | |
625 | pub fn try_map<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRef<O, U>, E> | |
dfeec247 XL |
626 | where |
627 | O: StableAddress, | |
628 | F: FnOnce(&mut T) -> Result<&U, E>, | |
ff7c6d11 | 629 | { |
dfeec247 | 630 | Ok(OwningRef { reference: f(&mut self)?, owner: self.owner }) |
ff7c6d11 XL |
631 | } |
632 | ||
633 | /// Tries to convert `self` into a new _mutable_ owning reference that points | |
634 | /// at something reachable from the previous one. | |
635 | /// | |
636 | /// This can be a reference to a field of `U`, something reachable from a field of | |
637 | /// `U`, or even something unrelated with a `'static` lifetime. | |
638 | /// | |
639 | /// # Example | |
640 | /// ``` | |
641 | /// extern crate owning_ref; | |
642 | /// use owning_ref::OwningRefMut; | |
643 | /// | |
644 | /// fn main() { | |
645 | /// let owning_ref_mut = OwningRefMut::new(Box::new([1, 2, 3, 4])); | |
646 | /// | |
647 | /// // create a owning reference that points at the | |
648 | /// // third element of the array. | |
649 | /// let owning_ref_mut = owning_ref_mut.try_map_mut(|array| { | |
650 | /// if array[2] == 3 { Ok(&mut array[2]) } else { Err(()) } | |
651 | /// }); | |
652 | /// assert_eq!(*owning_ref_mut.unwrap(), 3); | |
653 | /// } | |
654 | /// ``` | |
655 | pub fn try_map_mut<F, U: ?Sized, E>(mut self, f: F) -> Result<OwningRefMut<O, U>, E> | |
dfeec247 XL |
656 | where |
657 | O: StableAddress, | |
658 | F: FnOnce(&mut T) -> Result<&mut U, E>, | |
ff7c6d11 | 659 | { |
dfeec247 | 660 | Ok(OwningRefMut { reference: f(&mut self)?, owner: self.owner }) |
ff7c6d11 XL |
661 | } |
662 | ||
663 | /// Converts `self` into a new owning reference with a different owner type. | |
664 | /// | |
665 | /// The new owner type needs to still contain the original owner in some way | |
666 | /// so that the reference into it remains valid. This function is marked unsafe | |
667 | /// because the user needs to manually uphold this guarantee. | |
668 | pub unsafe fn map_owner<F, P>(self, f: F) -> OwningRefMut<P, T> | |
dfeec247 XL |
669 | where |
670 | O: StableAddress, | |
671 | P: StableAddress, | |
672 | F: FnOnce(O) -> P, | |
ff7c6d11 | 673 | { |
dfeec247 | 674 | OwningRefMut { reference: self.reference, owner: f(self.owner) } |
ff7c6d11 XL |
675 | } |
676 | ||
677 | /// Converts `self` into a new owning reference where the owner is wrapped | |
678 | /// in an additional `Box<O>`. | |
679 | /// | |
680 | /// This can be used to safely erase the owner of any `OwningRefMut<O, T>` | |
681 | /// to a `OwningRefMut<Box<Erased>, T>`. | |
682 | pub fn map_owner_box(self) -> OwningRefMut<Box<O>, T> { | |
dfeec247 | 683 | OwningRefMut { reference: self.reference, owner: Box::new(self.owner) } |
ff7c6d11 XL |
684 | } |
685 | ||
686 | /// Erases the concrete base type of the owner with a trait object. | |
687 | /// | |
688 | /// This allows mixing of owned references with different owner base types. | |
689 | /// | |
690 | /// # Example | |
691 | /// ``` | |
692 | /// extern crate owning_ref; | |
693 | /// use owning_ref::{OwningRefMut, Erased}; | |
694 | /// | |
695 | /// fn main() { | |
0731742a | 696 | /// // N.B., using the concrete types here for explicitness. |
ff7c6d11 XL |
697 | /// // For less verbose code type aliases like `BoxRef` are provided. |
698 | /// | |
699 | /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, [i32; 4]> | |
700 | /// = OwningRefMut::new(Box::new([1, 2, 3, 4])); | |
701 | /// | |
702 | /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, Vec<(i32, bool)>> | |
703 | /// = OwningRefMut::new(Box::new(vec![(0, false), (1, true)])); | |
704 | /// | |
705 | /// let owning_ref_mut_a: OwningRefMut<Box<[i32; 4]>, i32> | |
706 | /// = owning_ref_mut_a.map_mut(|a| &mut a[0]); | |
707 | /// | |
708 | /// let owning_ref_mut_b: OwningRefMut<Box<Vec<(i32, bool)>>, i32> | |
709 | /// = owning_ref_mut_b.map_mut(|a| &mut a[1].0); | |
710 | /// | |
711 | /// let owning_refs_mut: [OwningRefMut<Box<Erased>, i32>; 2] | |
712 | /// = [owning_ref_mut_a.erase_owner(), owning_ref_mut_b.erase_owner()]; | |
713 | /// | |
714 | /// assert_eq!(*owning_refs_mut[0], 1); | |
715 | /// assert_eq!(*owning_refs_mut[1], 1); | |
716 | /// } | |
717 | /// ``` | |
718 | pub fn erase_owner<'a>(self) -> OwningRefMut<O::Erased, T> | |
dfeec247 XL |
719 | where |
720 | O: IntoErased<'a>, | |
ff7c6d11 | 721 | { |
dfeec247 | 722 | OwningRefMut { reference: self.reference, owner: self.owner.into_erased() } |
ff7c6d11 XL |
723 | } |
724 | ||
416331ca | 725 | // UNIMPLEMENTED: wrap_owner |
ff7c6d11 XL |
726 | |
727 | // FIXME: Naming convention? | |
728 | /// A getter for the underlying owner. | |
729 | pub fn owner(&self) -> &O { | |
730 | &self.owner | |
731 | } | |
732 | ||
733 | // FIXME: Naming convention? | |
734 | /// Discards the reference and retrieves the owner. | |
735 | pub fn into_inner(self) -> O { | |
736 | self.owner | |
737 | } | |
738 | } | |
739 | ||
740 | ///////////////////////////////////////////////////////////////////////////// | |
741 | // OwningHandle | |
742 | ///////////////////////////////////////////////////////////////////////////// | |
743 | ||
744 | use std::ops::{Deref, DerefMut}; | |
745 | ||
746 | /// `OwningHandle` is a complement to `OwningRef`. Where `OwningRef` allows | |
747 | /// consumers to pass around an owned object and a dependent reference, | |
748 | /// `OwningHandle` contains an owned object and a dependent _object_. | |
749 | /// | |
750 | /// `OwningHandle` can encapsulate a `RefMut` along with its associated | |
751 | /// `RefCell`, or an `RwLockReadGuard` along with its associated `RwLock`. | |
752 | /// However, the API is completely generic and there are no restrictions on | |
753 | /// what types of owning and dependent objects may be used. | |
754 | /// | |
755 | /// `OwningHandle` is created by passing an owner object (which dereferences | |
756 | /// to a stable address) along with a callback which receives a pointer to | |
757 | /// that stable location. The callback may then dereference the pointer and | |
758 | /// mint a dependent object, with the guarantee that the returned object will | |
759 | /// not outlive the referent of the pointer. | |
760 | /// | |
761 | /// Since the callback needs to dereference a raw pointer, it requires `unsafe` | |
762 | /// code. To avoid forcing this unsafety on most callers, the `ToHandle` trait is | |
763 | /// implemented for common data structures. Types that implement `ToHandle` can | |
764 | /// be wrapped into an `OwningHandle` without passing a callback. | |
765 | pub struct OwningHandle<O, H> | |
dfeec247 XL |
766 | where |
767 | O: StableAddress, | |
768 | H: Deref, | |
ff7c6d11 XL |
769 | { |
770 | handle: H, | |
771 | _owner: O, | |
772 | } | |
773 | ||
774 | impl<O, H> Deref for OwningHandle<O, H> | |
dfeec247 XL |
775 | where |
776 | O: StableAddress, | |
777 | H: Deref, | |
ff7c6d11 XL |
778 | { |
779 | type Target = H::Target; | |
780 | fn deref(&self) -> &H::Target { | |
781 | self.handle.deref() | |
782 | } | |
783 | } | |
784 | ||
785 | unsafe impl<O, H> StableAddress for OwningHandle<O, H> | |
dfeec247 XL |
786 | where |
787 | O: StableAddress, | |
788 | H: StableAddress, | |
789 | { | |
790 | } | |
ff7c6d11 XL |
791 | |
792 | impl<O, H> DerefMut for OwningHandle<O, H> | |
dfeec247 XL |
793 | where |
794 | O: StableAddress, | |
795 | H: DerefMut, | |
ff7c6d11 XL |
796 | { |
797 | fn deref_mut(&mut self) -> &mut H::Target { | |
798 | self.handle.deref_mut() | |
799 | } | |
800 | } | |
801 | ||
802 | /// Trait to implement the conversion of owner to handle for common types. | |
803 | pub trait ToHandle { | |
804 | /// The type of handle to be encapsulated by the OwningHandle. | |
805 | type Handle: Deref; | |
806 | ||
807 | /// Given an appropriately-long-lived pointer to ourselves, create a | |
808 | /// handle to be encapsulated by the `OwningHandle`. | |
809 | unsafe fn to_handle(x: *const Self) -> Self::Handle; | |
810 | } | |
811 | ||
812 | /// Trait to implement the conversion of owner to mutable handle for common types. | |
813 | pub trait ToHandleMut { | |
814 | /// The type of handle to be encapsulated by the OwningHandle. | |
815 | type HandleMut: DerefMut; | |
816 | ||
817 | /// Given an appropriately-long-lived pointer to ourselves, create a | |
818 | /// mutable handle to be encapsulated by the `OwningHandle`. | |
819 | unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut; | |
820 | } | |
821 | ||
822 | impl<O, H> OwningHandle<O, H> | |
416331ca XL |
823 | where |
824 | O: StableAddress<Target: ToHandle<Handle = H>>, | |
825 | H: Deref, | |
ff7c6d11 | 826 | { |
9fa01778 | 827 | /// Creates a new `OwningHandle` for a type that implements `ToHandle`. For types |
ff7c6d11 XL |
828 | /// that don't implement `ToHandle`, callers may invoke `new_with_fn`, which accepts |
829 | /// a callback to perform the conversion. | |
830 | pub fn new(o: O) -> Self { | |
831 | OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle(x) }) | |
832 | } | |
833 | } | |
834 | ||
835 | impl<O, H> OwningHandle<O, H> | |
416331ca XL |
836 | where |
837 | O: StableAddress<Target: ToHandleMut<HandleMut = H>>, | |
838 | H: DerefMut, | |
ff7c6d11 | 839 | { |
9fa01778 | 840 | /// Creates a new mutable `OwningHandle` for a type that implements `ToHandleMut`. |
ff7c6d11 XL |
841 | pub fn new_mut(o: O) -> Self { |
842 | OwningHandle::new_with_fn(o, |x| unsafe { O::Target::to_handle_mut(x) }) | |
843 | } | |
844 | } | |
845 | ||
846 | impl<O, H> OwningHandle<O, H> | |
dfeec247 XL |
847 | where |
848 | O: StableAddress, | |
849 | H: Deref, | |
ff7c6d11 | 850 | { |
9fa01778 | 851 | /// Creates a new OwningHandle. The provided callback will be invoked with |
ff7c6d11 XL |
852 | /// a pointer to the object owned by `o`, and the returned value is stored |
853 | /// as the object to which this `OwningHandle` will forward `Deref` and | |
854 | /// `DerefMut`. | |
855 | pub fn new_with_fn<F>(o: O, f: F) -> Self | |
dfeec247 XL |
856 | where |
857 | F: FnOnce(*const O::Target) -> H, | |
ff7c6d11 XL |
858 | { |
859 | let h: H; | |
860 | { | |
861 | h = f(o.deref() as *const O::Target); | |
862 | } | |
863 | ||
dfeec247 | 864 | OwningHandle { handle: h, _owner: o } |
ff7c6d11 XL |
865 | } |
866 | ||
9fa01778 | 867 | /// Creates a new OwningHandle. The provided callback will be invoked with |
ff7c6d11 XL |
868 | /// a pointer to the object owned by `o`, and the returned value is stored |
869 | /// as the object to which this `OwningHandle` will forward `Deref` and | |
870 | /// `DerefMut`. | |
871 | pub fn try_new<F, E>(o: O, f: F) -> Result<Self, E> | |
dfeec247 XL |
872 | where |
873 | F: FnOnce(*const O::Target) -> Result<H, E>, | |
ff7c6d11 XL |
874 | { |
875 | let h: H; | |
876 | { | |
877 | h = f(o.deref() as *const O::Target)?; | |
878 | } | |
879 | ||
dfeec247 | 880 | Ok(OwningHandle { handle: h, _owner: o }) |
ff7c6d11 XL |
881 | } |
882 | } | |
883 | ||
884 | ///////////////////////////////////////////////////////////////////////////// | |
885 | // std traits | |
886 | ///////////////////////////////////////////////////////////////////////////// | |
887 | ||
dfeec247 XL |
888 | use std::borrow::Borrow; |
889 | use std::cmp::{Eq, Ord, Ordering, PartialEq, PartialOrd}; | |
ff7c6d11 XL |
890 | use std::convert::From; |
891 | use std::fmt::{self, Debug}; | |
ff7c6d11 | 892 | use std::hash::{Hash, Hasher}; |
dfeec247 | 893 | use std::marker::{Send, Sync}; |
ff7c6d11 XL |
894 | |
895 | impl<O, T: ?Sized> Deref for OwningRef<O, T> { | |
896 | type Target = T; | |
897 | ||
898 | fn deref(&self) -> &T { | |
dfeec247 | 899 | unsafe { &*self.reference } |
ff7c6d11 XL |
900 | } |
901 | } | |
902 | ||
903 | impl<O, T: ?Sized> Deref for OwningRefMut<O, T> { | |
904 | type Target = T; | |
905 | ||
906 | fn deref(&self) -> &T { | |
dfeec247 | 907 | unsafe { &*self.reference } |
ff7c6d11 XL |
908 | } |
909 | } | |
910 | ||
911 | impl<O, T: ?Sized> DerefMut for OwningRefMut<O, T> { | |
912 | fn deref_mut(&mut self) -> &mut T { | |
dfeec247 | 913 | unsafe { &mut *self.reference } |
ff7c6d11 XL |
914 | } |
915 | } | |
916 | ||
917 | unsafe impl<O, T: ?Sized> StableAddress for OwningRef<O, T> {} | |
918 | ||
919 | impl<O, T: ?Sized> AsRef<T> for OwningRef<O, T> { | |
920 | fn as_ref(&self) -> &T { | |
921 | &*self | |
922 | } | |
923 | } | |
924 | ||
925 | impl<O, T: ?Sized> AsRef<T> for OwningRefMut<O, T> { | |
926 | fn as_ref(&self) -> &T { | |
927 | &*self | |
928 | } | |
929 | } | |
930 | ||
931 | impl<O, T: ?Sized> AsMut<T> for OwningRefMut<O, T> { | |
932 | fn as_mut(&mut self) -> &mut T { | |
933 | &mut *self | |
934 | } | |
935 | } | |
936 | ||
937 | impl<O, T: ?Sized> Borrow<T> for OwningRef<O, T> { | |
938 | fn borrow(&self) -> &T { | |
939 | &*self | |
940 | } | |
941 | } | |
942 | ||
943 | impl<O, T: ?Sized> From<O> for OwningRef<O, T> | |
dfeec247 XL |
944 | where |
945 | O: StableAddress, | |
946 | O: Deref<Target = T>, | |
ff7c6d11 XL |
947 | { |
948 | fn from(owner: O) -> Self { | |
949 | OwningRef::new(owner) | |
950 | } | |
951 | } | |
952 | ||
953 | impl<O, T: ?Sized> From<O> for OwningRefMut<O, T> | |
dfeec247 XL |
954 | where |
955 | O: StableAddress, | |
956 | O: DerefMut<Target = T>, | |
ff7c6d11 XL |
957 | { |
958 | fn from(owner: O) -> Self { | |
959 | OwningRefMut::new(owner) | |
960 | } | |
961 | } | |
962 | ||
963 | impl<O, T: ?Sized> From<OwningRefMut<O, T>> for OwningRef<O, T> | |
dfeec247 XL |
964 | where |
965 | O: StableAddress, | |
966 | O: DerefMut<Target = T>, | |
ff7c6d11 XL |
967 | { |
968 | fn from(other: OwningRefMut<O, T>) -> Self { | |
dfeec247 | 969 | OwningRef { owner: other.owner, reference: other.reference } |
ff7c6d11 XL |
970 | } |
971 | } | |
972 | ||
973 | // ^ FIXME: Is a Into impl for calling into_inner() possible as well? | |
974 | ||
975 | impl<O, T: ?Sized> Debug for OwningRef<O, T> | |
dfeec247 XL |
976 | where |
977 | O: Debug, | |
978 | T: Debug, | |
ff7c6d11 | 979 | { |
9fa01778 | 980 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
dfeec247 | 981 | write!(f, "OwningRef {{ owner: {:?}, reference: {:?} }}", self.owner(), &**self) |
ff7c6d11 XL |
982 | } |
983 | } | |
984 | ||
985 | impl<O, T: ?Sized> Debug for OwningRefMut<O, T> | |
dfeec247 XL |
986 | where |
987 | O: Debug, | |
988 | T: Debug, | |
ff7c6d11 | 989 | { |
9fa01778 | 990 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
dfeec247 | 991 | write!(f, "OwningRefMut {{ owner: {:?}, reference: {:?} }}", self.owner(), &**self) |
ff7c6d11 XL |
992 | } |
993 | } | |
994 | ||
995 | impl<O, T: ?Sized> Clone for OwningRef<O, T> | |
dfeec247 XL |
996 | where |
997 | O: CloneStableAddress, | |
ff7c6d11 XL |
998 | { |
999 | fn clone(&self) -> Self { | |
dfeec247 | 1000 | OwningRef { owner: self.owner.clone(), reference: self.reference } |
ff7c6d11 XL |
1001 | } |
1002 | } | |
1003 | ||
dfeec247 | 1004 | unsafe impl<O, T: ?Sized> CloneStableAddress for OwningRef<O, T> where O: CloneStableAddress {} |
ff7c6d11 XL |
1005 | |
1006 | unsafe impl<O, T: ?Sized> Send for OwningRef<O, T> | |
dfeec247 XL |
1007 | where |
1008 | O: Send, | |
1009 | for<'a> &'a T: Send, | |
1010 | { | |
1011 | } | |
ff7c6d11 | 1012 | unsafe impl<O, T: ?Sized> Sync for OwningRef<O, T> |
dfeec247 XL |
1013 | where |
1014 | O: Sync, | |
1015 | for<'a> &'a T: Sync, | |
1016 | { | |
1017 | } | |
ff7c6d11 XL |
1018 | |
1019 | unsafe impl<O, T: ?Sized> Send for OwningRefMut<O, T> | |
dfeec247 XL |
1020 | where |
1021 | O: Send, | |
1022 | for<'a> &'a mut T: Send, | |
1023 | { | |
1024 | } | |
ff7c6d11 | 1025 | unsafe impl<O, T: ?Sized> Sync for OwningRefMut<O, T> |
dfeec247 XL |
1026 | where |
1027 | O: Sync, | |
1028 | for<'a> &'a mut T: Sync, | |
1029 | { | |
1030 | } | |
ff7c6d11 | 1031 | |
8faf50e0 | 1032 | impl Debug for dyn Erased { |
9fa01778 | 1033 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
ff7c6d11 XL |
1034 | write!(f, "<Erased>",) |
1035 | } | |
1036 | } | |
1037 | ||
dfeec247 XL |
1038 | impl<O, T: ?Sized> PartialEq for OwningRef<O, T> |
1039 | where | |
1040 | T: PartialEq, | |
1041 | { | |
ff7c6d11 XL |
1042 | fn eq(&self, other: &Self) -> bool { |
1043 | (&*self as &T).eq(&*other as &T) | |
dfeec247 | 1044 | } |
ff7c6d11 XL |
1045 | } |
1046 | ||
1047 | impl<O, T: ?Sized> Eq for OwningRef<O, T> where T: Eq {} | |
1048 | ||
dfeec247 XL |
1049 | impl<O, T: ?Sized> PartialOrd for OwningRef<O, T> |
1050 | where | |
1051 | T: PartialOrd, | |
1052 | { | |
ff7c6d11 XL |
1053 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
1054 | (&*self as &T).partial_cmp(&*other as &T) | |
1055 | } | |
1056 | } | |
1057 | ||
dfeec247 XL |
1058 | impl<O, T: ?Sized> Ord for OwningRef<O, T> |
1059 | where | |
1060 | T: Ord, | |
1061 | { | |
ff7c6d11 XL |
1062 | fn cmp(&self, other: &Self) -> Ordering { |
1063 | (&*self as &T).cmp(&*other as &T) | |
1064 | } | |
1065 | } | |
1066 | ||
dfeec247 XL |
1067 | impl<O, T: ?Sized> Hash for OwningRef<O, T> |
1068 | where | |
1069 | T: Hash, | |
1070 | { | |
ff7c6d11 XL |
1071 | fn hash<H: Hasher>(&self, state: &mut H) { |
1072 | (&*self as &T).hash(state); | |
1073 | } | |
1074 | } | |
1075 | ||
dfeec247 XL |
1076 | impl<O, T: ?Sized> PartialEq for OwningRefMut<O, T> |
1077 | where | |
1078 | T: PartialEq, | |
1079 | { | |
ff7c6d11 XL |
1080 | fn eq(&self, other: &Self) -> bool { |
1081 | (&*self as &T).eq(&*other as &T) | |
dfeec247 | 1082 | } |
ff7c6d11 XL |
1083 | } |
1084 | ||
1085 | impl<O, T: ?Sized> Eq for OwningRefMut<O, T> where T: Eq {} | |
1086 | ||
dfeec247 XL |
1087 | impl<O, T: ?Sized> PartialOrd for OwningRefMut<O, T> |
1088 | where | |
1089 | T: PartialOrd, | |
1090 | { | |
ff7c6d11 XL |
1091 | fn partial_cmp(&self, other: &Self) -> Option<Ordering> { |
1092 | (&*self as &T).partial_cmp(&*other as &T) | |
1093 | } | |
1094 | } | |
1095 | ||
dfeec247 XL |
1096 | impl<O, T: ?Sized> Ord for OwningRefMut<O, T> |
1097 | where | |
1098 | T: Ord, | |
1099 | { | |
ff7c6d11 XL |
1100 | fn cmp(&self, other: &Self) -> Ordering { |
1101 | (&*self as &T).cmp(&*other as &T) | |
1102 | } | |
1103 | } | |
1104 | ||
dfeec247 XL |
1105 | impl<O, T: ?Sized> Hash for OwningRefMut<O, T> |
1106 | where | |
1107 | T: Hash, | |
1108 | { | |
ff7c6d11 XL |
1109 | fn hash<H: Hasher>(&self, state: &mut H) { |
1110 | (&*self as &T).hash(state); | |
1111 | } | |
1112 | } | |
1113 | ||
1114 | ///////////////////////////////////////////////////////////////////////////// | |
1115 | // std types integration and convenience type defs | |
1116 | ///////////////////////////////////////////////////////////////////////////// | |
1117 | ||
1118 | use std::boxed::Box; | |
dfeec247 | 1119 | use std::cell::{Ref, RefCell, RefMut}; |
ff7c6d11 XL |
1120 | use std::rc::Rc; |
1121 | use std::sync::Arc; | |
1122 | use std::sync::{MutexGuard, RwLockReadGuard, RwLockWriteGuard}; | |
ff7c6d11 XL |
1123 | |
1124 | impl<T: 'static> ToHandle for RefCell<T> { | |
1125 | type Handle = Ref<'static, T>; | |
dfeec247 XL |
1126 | unsafe fn to_handle(x: *const Self) -> Self::Handle { |
1127 | (*x).borrow() | |
1128 | } | |
ff7c6d11 XL |
1129 | } |
1130 | ||
1131 | impl<T: 'static> ToHandleMut for RefCell<T> { | |
1132 | type HandleMut = RefMut<'static, T>; | |
dfeec247 XL |
1133 | unsafe fn to_handle_mut(x: *const Self) -> Self::HandleMut { |
1134 | (*x).borrow_mut() | |
1135 | } | |
ff7c6d11 XL |
1136 | } |
1137 | ||
0731742a XL |
1138 | // N.B., implementing ToHandle{,Mut} for Mutex and RwLock requires a decision |
1139 | // about which handle creation to use (i.e., read() vs try_read()) as well as | |
ff7c6d11 XL |
1140 | // what to do with error results. |
1141 | ||
1142 | /// Typedef of a owning reference that uses a `Box` as the owner. | |
1143 | pub type BoxRef<T, U = T> = OwningRef<Box<T>, U>; | |
1144 | /// Typedef of a owning reference that uses a `Vec` as the owner. | |
1145 | pub type VecRef<T, U = T> = OwningRef<Vec<T>, U>; | |
1146 | /// Typedef of a owning reference that uses a `String` as the owner. | |
1147 | pub type StringRef = OwningRef<String, str>; | |
1148 | ||
1149 | /// Typedef of a owning reference that uses a `Rc` as the owner. | |
1150 | pub type RcRef<T, U = T> = OwningRef<Rc<T>, U>; | |
1151 | /// Typedef of a owning reference that uses a `Arc` as the owner. | |
1152 | pub type ArcRef<T, U = T> = OwningRef<Arc<T>, U>; | |
1153 | ||
1154 | /// Typedef of a owning reference that uses a `Ref` as the owner. | |
1155 | pub type RefRef<'a, T, U = T> = OwningRef<Ref<'a, T>, U>; | |
1156 | /// Typedef of a owning reference that uses a `RefMut` as the owner. | |
1157 | pub type RefMutRef<'a, T, U = T> = OwningRef<RefMut<'a, T>, U>; | |
1158 | /// Typedef of a owning reference that uses a `MutexGuard` as the owner. | |
1159 | pub type MutexGuardRef<'a, T, U = T> = OwningRef<MutexGuard<'a, T>, U>; | |
1160 | /// Typedef of a owning reference that uses a `RwLockReadGuard` as the owner. | |
1161 | pub type RwLockReadGuardRef<'a, T, U = T> = OwningRef<RwLockReadGuard<'a, T>, U>; | |
1162 | /// Typedef of a owning reference that uses a `RwLockWriteGuard` as the owner. | |
1163 | pub type RwLockWriteGuardRef<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>; | |
1164 | ||
1165 | /// Typedef of a mutable owning reference that uses a `Box` as the owner. | |
1166 | pub type BoxRefMut<T, U = T> = OwningRefMut<Box<T>, U>; | |
1167 | /// Typedef of a mutable owning reference that uses a `Vec` as the owner. | |
1168 | pub type VecRefMut<T, U = T> = OwningRefMut<Vec<T>, U>; | |
1169 | /// Typedef of a mutable owning reference that uses a `String` as the owner. | |
1170 | pub type StringRefMut = OwningRefMut<String, str>; | |
1171 | ||
1172 | /// Typedef of a mutable owning reference that uses a `RefMut` as the owner. | |
1173 | pub type RefMutRefMut<'a, T, U = T> = OwningRefMut<RefMut<'a, T>, U>; | |
1174 | /// Typedef of a mutable owning reference that uses a `MutexGuard` as the owner. | |
1175 | pub type MutexGuardRefMut<'a, T, U = T> = OwningRefMut<MutexGuard<'a, T>, U>; | |
1176 | /// Typedef of a mutable owning reference that uses a `RwLockWriteGuard` as the owner. | |
1177 | pub type RwLockWriteGuardRefMut<'a, T, U = T> = OwningRef<RwLockWriteGuard<'a, T>, U>; | |
1178 | ||
1179 | unsafe impl<'a, T: 'a> IntoErased<'a> for Box<T> { | |
8faf50e0 | 1180 | type Erased = Box<dyn Erased + 'a>; |
ff7c6d11 XL |
1181 | fn into_erased(self) -> Self::Erased { |
1182 | self | |
1183 | } | |
1184 | } | |
1185 | unsafe impl<'a, T: 'a> IntoErased<'a> for Rc<T> { | |
8faf50e0 | 1186 | type Erased = Rc<dyn Erased + 'a>; |
ff7c6d11 XL |
1187 | fn into_erased(self) -> Self::Erased { |
1188 | self | |
1189 | } | |
1190 | } | |
1191 | unsafe impl<'a, T: 'a> IntoErased<'a> for Arc<T> { | |
8faf50e0 | 1192 | type Erased = Arc<dyn Erased + 'a>; |
ff7c6d11 XL |
1193 | fn into_erased(self) -> Self::Erased { |
1194 | self | |
1195 | } | |
1196 | } | |
1197 | ||
0531ce1d | 1198 | unsafe impl<'a, T: Send + 'a> IntoErasedSend<'a> for Box<T> { |
8faf50e0 | 1199 | type Erased = Box<dyn Erased + Send + 'a>; |
0531ce1d | 1200 | fn into_erased_send(self) -> Self::Erased { |
ff7c6d11 XL |
1201 | self |
1202 | } | |
1203 | } | |
1204 | ||
0531ce1d | 1205 | unsafe impl<'a, T: Send + 'a> IntoErasedSendSync<'a> for Box<T> { |
8faf50e0 | 1206 | type Erased = Box<dyn Erased + Sync + Send + 'a>; |
0531ce1d | 1207 | fn into_erased_send_sync(self) -> Self::Erased { |
8faf50e0 | 1208 | let result: Box<dyn Erased + Send + 'a> = self; |
0531ce1d XL |
1209 | // This is safe since Erased can always implement Sync |
1210 | // Only the destructor is available and it takes &mut self | |
dfeec247 | 1211 | unsafe { mem::transmute(result) } |
0531ce1d XL |
1212 | } |
1213 | } | |
1214 | ||
ff7c6d11 | 1215 | unsafe impl<'a, T: Send + Sync + 'a> IntoErasedSendSync<'a> for Arc<T> { |
8faf50e0 | 1216 | type Erased = Arc<dyn Erased + Send + Sync + 'a>; |
ff7c6d11 XL |
1217 | fn into_erased_send_sync(self) -> Self::Erased { |
1218 | self | |
1219 | } | |
1220 | } | |
1221 | ||
1222 | /// Typedef of a owning reference that uses an erased `Box` as the owner. | |
8faf50e0 | 1223 | pub type ErasedBoxRef<U> = OwningRef<Box<dyn Erased>, U>; |
ff7c6d11 | 1224 | /// Typedef of a owning reference that uses an erased `Rc` as the owner. |
8faf50e0 | 1225 | pub type ErasedRcRef<U> = OwningRef<Rc<dyn Erased>, U>; |
ff7c6d11 | 1226 | /// Typedef of a owning reference that uses an erased `Arc` as the owner. |
8faf50e0 | 1227 | pub type ErasedArcRef<U> = OwningRef<Arc<dyn Erased>, U>; |
ff7c6d11 XL |
1228 | |
1229 | /// Typedef of a mutable owning reference that uses an erased `Box` as the owner. | |
8faf50e0 | 1230 | pub type ErasedBoxRefMut<U> = OwningRefMut<Box<dyn Erased>, U>; |
ff7c6d11 XL |
1231 | |
1232 | #[cfg(test)] | |
dc9dc135 | 1233 | mod tests; |