/rust/registry/src/index.crates.io-1949cf8c6b5b557f/yoke-0.8.1/src/yokeable.rs
Line | Count | Source |
1 | | // This file is part of ICU4X. For terms of use, please see the file |
2 | | // called LICENSE at the top level of the ICU4X source tree |
3 | | // (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
4 | | |
5 | | #[cfg(feature = "alloc")] |
6 | | use alloc::borrow::{Cow, ToOwned}; |
7 | | use core::{marker::PhantomData, mem}; |
8 | | |
9 | | /// The `Yokeable<'a>` trait is implemented on the `'static` version of any zero-copy type; for |
10 | | /// example, `Cow<'static, T>` implements `Yokeable<'a>` (for all `'a`). |
11 | | /// |
12 | | /// One can use |
13 | | /// `Yokeable::Output` on this trait to obtain the "lifetime'd" value of the `Cow<'static, T>`, |
14 | | /// e.g. `<Cow<'static, T> as Yokeable<'a>'>::Output` is `Cow<'a, T>`. |
15 | | /// |
16 | | /// A [`Yokeable`] type is essentially one with a covariant lifetime parameter, |
17 | | /// matched to the parameter in the trait definition. The trait allows one to cast |
18 | | /// the covariant lifetime to and from `'static`. |
19 | | /// |
20 | | /// **Most of the time, if you need to implement [`Yokeable`], you should be able to use the safe |
21 | | /// [`#[derive(Yokeable)]`](yoke_derive::Yokeable) custom derive.** |
22 | | /// |
23 | | /// While Rust does not yet have GAT syntax, for the purpose of this documentation |
24 | | /// we shall refer to "`Self` with a lifetime `'a`" with the syntax `Self<'a>`. |
25 | | /// Self<'static> is a stand-in for the HKT Self<'_>: lifetime -> type. |
26 | | /// |
27 | | /// With this terminology, [`Yokeable`] exposes ways to cast between `Self<'static>` and `Self<'a>` generically. |
28 | | /// This is useful for turning covariant lifetimes to _dynamic_ lifetimes, where `'static` is |
29 | | /// used as a way to "erase" the lifetime. |
30 | | /// |
31 | | /// # Safety |
32 | | /// |
33 | | /// This trait is safe to implement on types with a _covariant_ lifetime parameter, i.e. one where |
34 | | /// [`Self::transform()`]'s body can simply be `{ self }`. This will occur when the lifetime |
35 | | /// parameter is used within references, but not in the arguments of function pointers or in mutable |
36 | | /// positions (either in `&mut` or via interior mutability) |
37 | | /// |
38 | | /// This trait must be implemented on the `'static` version of such a type, e.g. one should |
39 | | /// implement `Yokeable<'a>` (for all `'a`) on `Cow<'static, T>`. |
40 | | /// |
41 | | /// This trait is also safe to implement on types that do not borrow memory. |
42 | | /// |
43 | | /// There are further constraints on implementation safety on individual methods. |
44 | | /// |
45 | | /// # Implementation example |
46 | | /// |
47 | | /// Implementing this trait manually is unsafe. Where possible, you should use the safe |
48 | | /// [`#[derive(Yokeable)]`](yoke_derive::Yokeable) custom derive instead. We include an example |
49 | | /// in case you have your own zero-copy abstractions you wish to make yokeable. |
50 | | /// |
51 | | /// ```rust |
52 | | /// # use yoke::Yokeable; |
53 | | /// # use std::borrow::Cow; |
54 | | /// # use std::{mem, ptr}; |
55 | | /// struct Bar<'a> { |
56 | | /// numbers: Cow<'a, [u8]>, |
57 | | /// string: Cow<'a, str>, |
58 | | /// owned: Vec<u8>, |
59 | | /// } |
60 | | /// |
61 | | /// unsafe impl<'a> Yokeable<'a> for Bar<'static> { |
62 | | /// type Output = Bar<'a>; |
63 | | /// fn transform(&'a self) -> &'a Bar<'a> { |
64 | | /// // covariant lifetime cast, can be done safely |
65 | | /// self |
66 | | /// } |
67 | | /// |
68 | | /// fn transform_owned(self) -> Bar<'a> { |
69 | | /// // covariant lifetime cast, can be done safely |
70 | | /// self |
71 | | /// } |
72 | | /// |
73 | | /// unsafe fn make(from: Bar<'a>) -> Self { |
74 | | /// unsafe { mem::transmute(from) } |
75 | | /// } |
76 | | /// |
77 | | /// fn transform_mut<F>(&'a mut self, f: F) |
78 | | /// where |
79 | | /// F: 'static + FnOnce(&'a mut Self::Output), |
80 | | /// { |
81 | | /// unsafe { f(mem::transmute::<&mut Self, &mut Self::Output>(self)) } |
82 | | /// } |
83 | | /// } |
84 | | /// ``` |
85 | | pub unsafe trait Yokeable<'a>: 'static { |
86 | | /// This type MUST be `Self` with the `'static` replaced with `'a`, i.e. `Self<'a>` |
87 | | type Output: 'a; |
88 | | |
89 | | /// This method must cast `self` between `&'a Self<'static>` and `&'a Self<'a>`. |
90 | | /// |
91 | | /// # Implementation safety |
92 | | /// |
93 | | /// If the invariants of [`Yokeable`] are being satisfied, the body of this method |
94 | | /// should simply be `{ self }`, though it's acceptable to include additional assertions |
95 | | /// if desired. |
96 | | fn transform(&'a self) -> &'a Self::Output; |
97 | | |
98 | | /// This method must cast `self` between `Self<'static>` and `Self<'a>`. |
99 | | /// |
100 | | /// # Implementation safety |
101 | | /// |
102 | | /// If the invariants of [`Yokeable`] are being satisfied, the body of this method |
103 | | /// should simply be `{ self }`, though it's acceptable to include additional assertions |
104 | | /// if desired. |
105 | | fn transform_owned(self) -> Self::Output; |
106 | | |
107 | | /// This method can be used to cast away `Self<'a>`'s lifetime. |
108 | | /// |
109 | | /// # Safety |
110 | | /// |
111 | | /// The returned value must be destroyed before the data `from` was borrowing from is. |
112 | | /// |
113 | | /// # Implementation safety |
114 | | /// |
115 | | /// A safe implementation of this method must be equivalent to a transmute between |
116 | | /// `Self<'a>` and `Self<'static>` |
117 | | unsafe fn make(from: Self::Output) -> Self; |
118 | | |
119 | | /// This method must cast `self` between `&'a mut Self<'static>` and `&'a mut Self<'a>`, |
120 | | /// and pass it to `f`. |
121 | | /// |
122 | | /// # Implementation safety |
123 | | /// |
124 | | /// A safe implementation of this method must be equivalent to a pointer cast/transmute between |
125 | | /// `&mut Self<'a>` and `&mut Self<'static>` being passed to `f` |
126 | | /// |
127 | | /// # Why is this safe? |
128 | | /// |
129 | | /// Typically covariant lifetimes become invariant when hidden behind an `&mut`, |
130 | | /// which is why the implementation of this method cannot just be `f(self)`. |
131 | | /// The reason behind this is that while _reading_ a covariant lifetime that has been cast to a shorter |
132 | | /// one is always safe (this is roughly the definition of a covariant lifetime), writing |
133 | | /// may not necessarily be safe since you could write a smaller reference to it. For example, |
134 | | /// the following code is unsound because it manages to stuff a `'a` lifetime into a `Cow<'static>` |
135 | | /// |
136 | | /// ```rust,compile_fail |
137 | | /// # use std::borrow::Cow; |
138 | | /// # use yoke::Yokeable; |
139 | | /// struct Foo { |
140 | | /// str: String, |
141 | | /// cow: Cow<'static, str>, |
142 | | /// } |
143 | | /// |
144 | | /// fn unsound<'a>(foo: &'a mut Foo) { |
145 | | /// let a: &str = &foo.str; |
146 | | /// foo.cow.transform_mut(|cow| *cow = Cow::Borrowed(a)); |
147 | | /// } |
148 | | /// ``` |
149 | | /// |
150 | | /// However, this code will not compile because [`Yokeable::transform_mut()`] requires `F: 'static`. |
151 | | /// This enforces that while `F` may mutate `Self<'a>`, it can only mutate it in a way that does |
152 | | /// not insert additional references. For example, `F` may call `to_owned()` on a `Cow` and mutate it, |
153 | | /// but it cannot insert a new _borrowed_ reference because it has nowhere to borrow _from_ -- |
154 | | /// `f` does not contain any borrowed references, and while we give it `Self<'a>` (which contains borrowed |
155 | | /// data), that borrowed data is known to be valid |
156 | | /// |
157 | | /// Note that the `for<'b>` is also necessary, otherwise the following code would compile: |
158 | | /// |
159 | | /// ```rust,compile_fail |
160 | | /// # use std::borrow::Cow; |
161 | | /// # use yoke::Yokeable; |
162 | | /// # use std::mem; |
163 | | /// # |
164 | | /// // also safely implements Yokeable<'a> |
165 | | /// struct Bar<'a> { |
166 | | /// num: u8, |
167 | | /// cow: Cow<'a, u8>, |
168 | | /// } |
169 | | /// |
170 | | /// fn unsound<'a>(bar: &'a mut Bar<'static>) { |
171 | | /// bar.transform_mut(move |bar| bar.cow = Cow::Borrowed(&bar.num)); |
172 | | /// } |
173 | | /// # |
174 | | /// # unsafe impl<'a> Yokeable<'a> for Bar<'static> { |
175 | | /// # type Output = Bar<'a>; |
176 | | /// # fn transform(&'a self) -> &'a Bar<'a> { |
177 | | /// # self |
178 | | /// # } |
179 | | /// # |
180 | | /// # fn transform_owned(self) -> Bar<'a> { |
181 | | /// # // covariant lifetime cast, can be done safely |
182 | | /// # self |
183 | | /// # } |
184 | | /// # |
185 | | /// # unsafe fn make(from: Bar<'a>) -> Self { |
186 | | /// # let ret = mem::transmute_copy(&from); |
187 | | /// # mem::forget(from); |
188 | | /// # ret |
189 | | /// # } |
190 | | /// # |
191 | | /// # fn transform_mut<F>(&'a mut self, f: F) |
192 | | /// # where |
193 | | /// # F: 'static + FnOnce(&'a mut Self::Output), |
194 | | /// # { |
195 | | /// # unsafe { f(mem::transmute(self)) } |
196 | | /// # } |
197 | | /// # } |
198 | | /// ``` |
199 | | /// |
200 | | /// which is unsound because `bar` could be moved later, and we do not want to be able to |
201 | | /// self-insert references to it. |
202 | | /// |
203 | | /// The `for<'b>` enforces this by stopping the author of the closure from matching up the input |
204 | | /// `&'b Self::Output` lifetime with `'a` and borrowing directly from it. |
205 | | /// |
206 | | /// Thus the only types of mutations allowed are ones that move around already-borrowed data, or |
207 | | /// introduce new owned data: |
208 | | /// |
209 | | /// ```rust |
210 | | /// # use std::borrow::Cow; |
211 | | /// # use yoke::Yokeable; |
212 | | /// struct Foo { |
213 | | /// str: String, |
214 | | /// cow: Cow<'static, str>, |
215 | | /// } |
216 | | /// |
217 | | /// fn sound(foo: &mut Foo) { |
218 | | /// foo.cow.transform_mut(move |cow| cow.to_mut().push('a')); |
219 | | /// } |
220 | | /// ``` |
221 | | /// |
222 | | /// More formally, a reference to an object that `f` assigns to a reference |
223 | | /// in Self<'a> could be obtained from: |
224 | | /// - a local variable: the compiler rejects the assignment because 'a certainly |
225 | | /// outlives local variables in f. |
226 | | /// - a field in its argument: because of the for<'b> bound, the call to `f` |
227 | | /// must be valid for a particular 'b that is strictly shorter than 'a. Thus, |
228 | | /// the compiler rejects the assignment. |
229 | | /// - a reference field in Self<'a>: this does not extend the set of |
230 | | /// non-static lifetimes reachable from Self<'a>, so this is fine. |
231 | | /// - one of f's captures: since F: 'static, the resulting reference must refer |
232 | | /// to 'static data. |
233 | | /// - a static or thread_local variable: ditto. |
234 | | fn transform_mut<F>(&'a mut self, f: F) |
235 | | where |
236 | | // be VERY CAREFUL changing this signature, it is very nuanced (see above) |
237 | | F: 'static + for<'b> FnOnce(&'b mut Self::Output); |
238 | | } |
239 | | |
240 | | #[cfg(feature = "alloc")] |
241 | | // Safety: Cow<'a, _> is covariant in 'a. |
242 | | unsafe impl<'a, T: 'static + ToOwned + ?Sized> Yokeable<'a> for Cow<'static, T> |
243 | | where |
244 | | <T as ToOwned>::Owned: Sized, |
245 | | { |
246 | | type Output = Cow<'a, T>; |
247 | | #[inline] |
248 | | fn transform(&'a self) -> &'a Cow<'a, T> { |
249 | | // Doesn't need unsafe: `'a` is covariant so this lifetime cast is always safe |
250 | | self |
251 | | } |
252 | | #[inline] |
253 | | fn transform_owned(self) -> Cow<'a, T> { |
254 | | // Doesn't need unsafe: `'a` is covariant so this lifetime cast is always safe |
255 | | self |
256 | | } |
257 | | #[inline] |
258 | | unsafe fn make(from: Cow<'a, T>) -> Self { |
259 | | // i hate this |
260 | | // unfortunately Rust doesn't think `mem::transmute` is possible since it's not sure the sizes |
261 | | // are the same |
262 | | debug_assert!(mem::size_of::<Cow<'a, T>>() == mem::size_of::<Self>()); |
263 | | let ptr: *const Self = (&from as *const Self::Output).cast(); |
264 | | let _ = core::mem::ManuallyDrop::new(from); |
265 | | // Safety: `ptr` is certainly valid, aligned and points to a properly initialized value, as |
266 | | // it comes from a value that was moved into a ManuallyDrop. |
267 | | unsafe { core::ptr::read(ptr) } |
268 | | } |
269 | | #[inline] |
270 | | fn transform_mut<F>(&'a mut self, f: F) |
271 | | where |
272 | | F: 'static + for<'b> FnOnce(&'b mut Self::Output), |
273 | | { |
274 | | // Cast away the lifetime of Self |
275 | | // Safety: this is equivalent to f(transmute(self)), and the documentation of the trait |
276 | | // method explains why doing so is sound. |
277 | | unsafe { f(mem::transmute::<&'a mut Self, &'a mut Self::Output>(self)) } |
278 | | } |
279 | | } |
280 | | |
281 | | // Safety: &'a T is covariant in 'a. |
282 | | unsafe impl<'a, T: 'static + ?Sized> Yokeable<'a> for &'static T { |
283 | | type Output = &'a T; |
284 | | #[inline] |
285 | 0 | fn transform(&'a self) -> &'a &'a T { |
286 | | // Doesn't need unsafe: `'a` is covariant so this lifetime cast is always safe |
287 | 0 | self |
288 | 0 | } |
289 | | #[inline] |
290 | 0 | fn transform_owned(self) -> &'a T { |
291 | | // Doesn't need unsafe: `'a` is covariant so this lifetime cast is always safe |
292 | 0 | self |
293 | 0 | } |
294 | | #[inline] |
295 | 0 | unsafe fn make(from: &'a T) -> Self { |
296 | | // Safety: function safety invariant guarantees that the returned reference |
297 | | // will never be used beyond its original lifetime. |
298 | 0 | unsafe { mem::transmute(from) } |
299 | 0 | } |
300 | | #[inline] |
301 | 0 | fn transform_mut<F>(&'a mut self, f: F) |
302 | 0 | where |
303 | 0 | F: 'static + for<'b> FnOnce(&'b mut Self::Output), |
304 | | { |
305 | | // Cast away the lifetime of Self |
306 | | // Safety: this is equivalent to f(transmute(self)), and the documentation of the trait |
307 | | // method explains why doing so is sound. |
308 | 0 | unsafe { f(mem::transmute::<&'a mut Self, &'a mut Self::Output>(self)) } |
309 | 0 | } |
310 | | } |
311 | | |
312 | | #[cfg(feature = "alloc")] |
313 | | // Safety: Vec<T: 'static> never borrows. |
314 | | unsafe impl<'a, T: 'static> Yokeable<'a> for alloc::vec::Vec<T> { |
315 | | type Output = alloc::vec::Vec<T>; |
316 | | #[inline] |
317 | | fn transform(&'a self) -> &'a alloc::vec::Vec<T> { |
318 | | self |
319 | | } |
320 | | #[inline] |
321 | | fn transform_owned(self) -> alloc::vec::Vec<T> { |
322 | | self |
323 | | } |
324 | | #[inline] |
325 | | unsafe fn make(from: alloc::vec::Vec<T>) -> Self { |
326 | | from |
327 | | } |
328 | | #[inline] |
329 | | fn transform_mut<F>(&'a mut self, f: F) |
330 | | where |
331 | | F: 'static + for<'b> FnOnce(&'b mut Self::Output), |
332 | | { |
333 | | f(self) |
334 | | } |
335 | | } |
336 | | |
337 | | // Safety: PhantomData is a ZST. |
338 | | unsafe impl<'a, T: ?Sized + 'static> Yokeable<'a> for PhantomData<T> { |
339 | | type Output = PhantomData<T>; |
340 | | |
341 | 0 | fn transform(&'a self) -> &'a Self::Output { |
342 | 0 | self |
343 | 0 | } |
344 | | |
345 | 0 | fn transform_owned(self) -> Self::Output { |
346 | 0 | self |
347 | 0 | } |
348 | | |
349 | 0 | unsafe fn make(from: Self::Output) -> Self { |
350 | 0 | from |
351 | 0 | } |
352 | | |
353 | 0 | fn transform_mut<F>(&'a mut self, f: F) |
354 | 0 | where |
355 | 0 | // be VERY CAREFUL changing this signature, it is very nuanced (see above) |
356 | 0 | F: 'static + for<'b> FnOnce(&'b mut Self::Output), |
357 | | { |
358 | 0 | f(self) |
359 | 0 | } |
360 | | } |