ouroboros/lib.rs
1//! A crate for creating safe self-referencing structs.
2//!
3//! See the documentation of [`ouroboros_examples`](https://docs.rs/ouroboros_examples) for
4//! sample documentation of structs which have had the macro applied to them.
5
6#![no_std]
7#![allow(clippy::needless_doctest_main)]
8
9/// This macro is used to turn a regular struct into a self-referencing one. An example:
10/// ```rust
11/// use ouroboros::self_referencing;
12///
13/// #[self_referencing]
14/// struct MyStruct {
15/// int_data: i32,
16/// float_data: f32,
17/// #[borrows(int_data)]
18/// // the 'this lifetime is created by the #[self_referencing] macro
19/// // and should be used on all references marked by the #[borrows] macro
20/// int_reference: &'this i32,
21/// #[borrows(mut float_data)]
22/// float_reference: &'this mut f32,
23/// }
24///
25/// fn main() {
26/// // The builder is created by the #[self_referencing] macro
27/// // and is used to create the struct
28/// let mut my_value = MyStructBuilder {
29/// int_data: 42,
30/// float_data: 3.14,
31///
32/// // Note that the name of the field in the builder
33/// // is the name of the field in the struct + `_builder`
34/// // ie: {field_name}_builder
35/// // the closure that assigns the value for the field will be passed
36/// // a reference to the field(s) defined in the #[borrows] macro
37///
38/// int_reference_builder: |int_data: &i32| int_data,
39/// float_reference_builder: |float_data: &mut f32| float_data,
40/// }.build();
41///
42/// // The fields in the original struct can not be accessed directly
43/// // The builder creates accessor methods which are called borrow_{field_name}()
44///
45/// // Prints 42
46/// println!("{:?}", my_value.borrow_int_data());
47/// // Prints 3.14
48/// println!("{:?}", my_value.borrow_float_reference());
49/// // Sets the value of float_data to 84.0
50/// my_value.with_mut(|fields| {
51/// **fields.float_reference = (**fields.int_reference as f32) * 2.0;
52/// });
53///
54/// // We can hold on to this reference...
55/// let int_ref = *my_value.borrow_int_reference();
56/// println!("{:?}", *int_ref);
57/// // As long as the struct is still alive.
58/// drop(my_value);
59/// // This will cause an error!
60/// // println!("{:?}", *int_ref);
61/// }
62/// ```
63/// To explain the features and limitations of this crate, some definitions are necessary:
64/// # Definitions
65/// - **immutably borrowed field**: a field which is immutably borrowed by at least one other field.
66/// - **mutably borrowed field**: a field which is mutably borrowed by exactly one other field.
67/// - **self-referencing field**: a field which borrows at least one other field.
68/// - **head field**: a field which does not borrow any other fields, I.E. not self-referencing.
69/// This does not include fields with empty borrows annotations (`#[borrows()]`.)
70/// - **tail field**: a field which is not borrowed by any other fields.
71///
72/// # Usage
73/// To make a self-referencing struct, you must write a struct definition and place
74/// `#[self_referencing]` on top. For every field that borrows other fields, you must place
75/// `#[borrows()]` on top and place inside the parenthesis a list of fields that it borrows. Mut can
76/// be prefixed to indicate that a mutable borrow is required. For example,
77/// `#[borrows(a, b, mut c)]` indicates that the first two fields need to be borrowed immutably and
78/// the third needs to be borrowed mutably. You can also use `#[borrows()]` without any arguments to
79/// indicate a field that will eventually borrow from the struct, but does not borrow anything when
80/// first created. For example, you could use this on a field like `error: Option<&'this str>`.
81///
82/// # You must comply with these limitations
83/// - Fields must be declared before the first time they are borrowed.
84/// - Normal borrowing rules apply, E.G. a field cannot be borrowed mutably twice.
85/// - Fields that use the `'this` lifetime must have a corresponding `#[borrows()]` annotation.
86/// The error for this needs some work, currently you will get an error saying that `'this` is
87/// undefined at the location it was illegally used in.
88///
89/// Violating them will result in an error message directly pointing out the violated rule.
90///
91/// # Flexibility of this crate
92/// The example above uses plain references as the self-referencing part of the struct, but you can
93/// use anything that is dependent on lifetimes of objects inside the struct. For example, you could
94/// do something like this:
95/// ```rust
96/// use ouroboros::self_referencing;
97///
98/// pub struct ComplexData<'a, 'b> {
99/// aref: &'a i32,
100/// bref: &'b mut i32,
101/// number: i32,
102/// }
103///
104/// impl<'a, 'b> ComplexData<'a, 'b> {
105/// fn new(aref: &'a i32, bref: &'b mut i32, number: i32) -> Self {
106/// Self { aref, bref, number }
107/// }
108///
109/// /// Copies the value aref points to into what bref points to.
110/// fn transfer(&mut self) {
111/// *self.bref = *self.aref;
112/// }
113///
114/// /// Prints the value bref points to.
115/// fn print_bref(&self) {
116/// println!("{}", *self.bref);
117/// }
118/// }
119///
120/// fn main() {
121/// #[self_referencing]
122/// struct DataStorage {
123/// immutable: i32,
124/// mutable: i32,
125/// #[borrows(immutable, mut mutable)]
126/// #[not_covariant]
127/// complex_data: ComplexData<'this, 'this>,
128/// }
129///
130/// let mut data_storage = DataStorageBuilder {
131/// immutable: 10,
132/// mutable: 20,
133/// complex_data_builder: |i: &i32, m: &mut i32| ComplexData::new(i, m, 12345),
134/// }.build();
135/// data_storage.with_complex_data_mut(|data| {
136/// // Copies the value in immutable into mutable.
137/// data.transfer();
138/// // Prints 10
139/// data.print_bref();
140/// });
141/// }
142/// ```
143///
144/// # Covariance
145/// Many types in Rust have a property called "covariance". In practical tearms, this means that a
146/// covariant type like `Box<&'this i32>` can be used as a `Box<&'a i32>` as long as `'a` is
147/// smaller than `'this`. Since the lifetime is smaller, it does not violate the lifetime specified
148/// by the original type. Contrast this to `Fn(&'this i32)`, which is not covariant. You cannot give
149/// this function a reference with a lifetime shorter than `'this` as the function needs something
150/// that lives at *least* as long as `'this`. Unfortunately, there is no easy way to determine
151/// whether or not a type is covariant from inside the macro. As such, you may
152/// receive a compiler error letting you know that the macro is uncertain if a particular field
153/// uses a covariant type. Adding `#[covariant]` or `#[not_covariant]` will resolve this issue.
154///
155/// These annotations control whether or not a `borrow_*` method is generated for that field.
156/// Incorrectly using one of these tags will result in a compilation error. It is impossible to
157/// use them unsoundly.
158///
159/// # Async usage
160/// All self-referencing structs can be initialized asynchronously by using either the
161/// `MyStruct::new_async()` function or the `MyStructAsyncBuilder` builder. Due to limitations of
162/// the rust compiler you closures must return a Future trait object wrapped in a `Pin<Box<_>>`.
163///
164/// Here is the same example as above in its async version:
165///
166/// ```ignore
167/// use ouroboros::self_referencing;
168///
169/// #[self_referencing]
170/// struct MyStruct {
171/// int_data: i32,
172/// float_data: f32,
173/// #[borrows(int_data)]
174/// int_reference: &'this i32,
175/// #[borrows(mut float_data)]
176/// float_reference: &'this mut f32,
177/// }
178///
179/// #[tokio::main]
180/// async fn main() {
181/// let mut my_value = MyStructAsyncBuilder {
182/// int_data: 42,
183/// float_data: 3.14,
184/// int_reference_builder: |int_data: &i32| Box::pin(async move { int_data }),
185/// float_reference_builder: |float_data: &mut f32| Box::pin(async move { float_data }),
186/// }.build().await;
187///
188/// // Prints 42
189/// println!("{:?}", my_value.borrow_int_data());
190/// // Prints 3.14
191/// println!("{:?}", my_value.borrow_float_reference());
192/// // Sets the value of float_data to 84.0
193/// my_value.with_mut(|fields| {
194/// **fields.float_reference = (**fields.int_reference as f32) * 2.0;
195/// });
196///
197/// // We can hold on to this reference...
198/// let int_ref = *my_value.borrow_int_reference();
199/// println!("{:?}", *int_ref);
200/// // As long as the struct is still alive.
201/// drop(my_value);
202/// // This will cause an error!
203/// // println!("{:?}", *int_ref);
204/// }
205/// ```
206///
207/// # Async Send
208/// When Send trait is needed, the Send variant of async methods and builders is available.
209///
210/// Here is the same example as above in its async send version:
211///
212/// ```ignore
213/// use ouroboros::self_referencing;
214///
215/// #[self_referencing]
216/// struct MyStruct {
217/// int_data: i32,
218/// float_data: f32,
219/// #[borrows(int_data)]
220/// int_reference: &'this i32,
221/// #[borrows(mut float_data)]
222/// float_reference: &'this mut f32,
223/// }
224///
225/// #[tokio::main]
226/// async fn main() {
227/// let mut my_value = MyStructAsyncSendBuilder {
228/// int_data: 42,
229/// float_data: 3.14,
230/// int_reference_builder: |int_data: &i32| Box::pin(async move { int_data }),
231/// float_reference_builder: |float_data: &mut f32| Box::pin(async move { float_data }),
232/// }.build().await;
233///
234/// // Prints 42
235/// println!("{:?}", my_value.borrow_int_data());
236/// // Prints 3.14
237/// println!("{:?}", my_value.borrow_float_reference());
238/// // Sets the value of float_data to 84.0
239/// my_value.with_mut(|fields| {
240/// **fields.float_reference = (**fields.int_reference as f32) * 2.0;
241/// });
242///
243/// // We can hold on to this reference...
244/// let int_ref = *my_value.borrow_int_reference();
245/// println!("{:?}", *int_ref);
246/// // As long as the struct is still alive.
247/// drop(my_value);
248/// // This will cause an error!
249/// // println!("{:?}", *int_ref);
250/// }
251/// ```
252///
253/// # What does the macro generate?
254/// The `#[self_referencing]` struct will replace your definition with an unsafe self-referencing
255/// struct with a safe public interface. Many functions will be generated depending on your original
256/// struct definition. Documentation is generated for all items, so building documentation for
257/// your project allows accessing detailed information about available functions. Using
258/// `#[self_referencing(no_doc)]` will hide the generated items from documentation if it is becoming
259/// too cluttered.
260///
261/// ### A quick note on visibility
262/// The visibility of generated items is dependent on one of two things. If the
263/// generated item is related to a specific field of the struct, it uses the visibility of the
264/// original field. (The actual field in the struct will be made private since accessing it could cause
265/// undefined behavior.) If the generated item is not related to any particular field, it will by
266/// default only be visible to the module the struct is declared in. (This includes things like
267/// `new()` and `with()`.) You can use `#[self_referencing(pub_extras)]` to make these items have the
268/// same visibility as the struct itself.
269///
270/// # List of generated items
271/// ### `MyStruct::new(fields...) -> MyStruct`
272/// A basic constructor. It accepts values for each field in the order you declared them in. For
273/// **head fields**, you only need to pass in what value it should have and it will be moved in
274/// to the output. For **self-referencing fields**, you must provide a function or closure which creates
275/// the value based on the values it borrows. A field using the earlier example of
276/// `#[borrow(a, b, mut c)]` would require a function typed as
277/// `FnOnce(a: &_, b: &_, c: &mut _) -> _`. Fields which have an empty borrows annotation
278/// (`#[borrows()]`) should have their value directly passed in. A field using the earlier example
279/// of `Option<&'this str>` would require an input of `None`. Do not pass a function. Do not collect
280/// 200 dollars.
281/// ### `MyStruct::new_async(fields...) -> MyStruct`
282/// A basic async constructor. It works identically to the sync constructor differing only in the
283/// type of closures it expects. Whenever a closure is required it is expected to return a Pinned
284/// and Boxed Future that Outputs the same type as the synchronous version.
285/// ### `MyStruct::new_async_send(fields...) -> MyStruct`
286/// An async send constructor. It works identically to the sync constructor differing only in the
287/// Send trait being specified in the return type.
288/// ### `MyStructBuilder`
289/// This is the preferred way to create a new instance of your struct. It is similar to using the
290/// `MyStruct { a, b, c, d }` syntax instead of `MyStruct::new(a, b, c, d)`. It contains one field
291/// for every argument in the actual constructor. **Head fields** have the same name that you
292/// originally defined them with. **self-referencing fields** are suffixed with `_builder` since you need
293/// to provide a function instead of a value. Fields with an empty borrows annotation are not
294/// initialized using builders. Calling `.build()` on an instance of `MyStructBuilder`
295/// will convert it to an instance of `MyStruct` by calling all `_builder` functions in the order that
296/// they were declared and storing their results.
297/// ### `MyStructAsyncBuilder`
298/// This is the preferred way to asynchronously create a new instance of your struct. It works
299/// identically to the synchronous builder differing only in the type of closures it expects. In
300/// particular, all builder functions are called serially in the order that they were declared.
301/// Whenever a closure is required it is expected to return a Pinned and Boxed Future that Outputs
302/// the same type as the synchronous version.
303/// ### `MyStructAsyncSendBuilder`
304/// Same as MyStructAsyncBuilder, but with Send trait specified in the return type.
305/// ### `MyStruct::try_new<E>(fields...) -> Result<MyStruct, E>`
306/// Similar to the regular `new()` function, except the functions which create values for all
307/// **self-referencing fields** can return `Result<>`s. If any of those are `Err`s, that error will be
308/// returned instead of an instance of `MyStruct`. The preferred way to use this function is through
309/// `MyStructTryBuilder` and its `try_build()` function.
310/// ### `MyStruct::try_new_async<E>(fields...) -> Result<MyStruct, E>`
311/// Similar to the regular `new_async()` function, except the functions which create values for all
312/// **self-referencing fields** can return `Result<>`s. If any of those are `Err`s, that error will be
313/// returned instead of an instance of `MyStruct`. The preferred way to use this function is through
314/// `MyStructAsyncTryBuilder` and its `try_build()` function.
315/// ### `MyStruct::try_new_async_send<E>(fields...) -> Result<MyStruct, E>`
316/// Same as `new_async()` function, but with Send trait specified in the return type.
317/// ### `MyStruct::try_new_or_recover_async<E>(fields...) -> Result<MyStruct, (E, Heads)>`
318/// Similar to the `try_new_async()` function, except that all the **head fields** are returned along side
319/// the original error in case of an error. The preferred way to use this function is through
320/// `MyStructAsyncTryBuilder` and its `try_build_or_recover()` function.
321/// ### `MyStruct::try_new_or_recover_async_send<E>(fields...) -> Result<MyStruct, (E, Heads)>`
322/// Same as `try_new_or_recover_async()` function, but with Send trait specified in the return type.
323/// ### `MyStruct::with_FIELD<R>(&self, user: FnOnce(field: &FieldType) -> R) -> R`
324/// This function is generated for every **tail and immutably-borrowed field** in your struct. It
325/// allows safely accessing
326/// a reference to that value. The function generates the reference and passes it to `user`. You
327/// can do anything you want with the reference, it is constructed to not outlive the struct.
328/// ### `MyStruct::borrow_FIELD(&self) -> &FieldType`
329/// This function is generated for every **tail and immutably-borrowed field** in your struct. It
330/// is equivalent to calling `my_struct.with_FIELD(|field| field)`. It is only generated for types
331/// which are known to be covariant, either through the macro being able to detect it or through the
332/// programmer adding the `#[covariant]` annotation to the field.
333/// There is no `borrow_FIELD_mut`, unfortunately, as Rust's
334/// borrow checker is currently not capable of ensuring that such a method would be used safely.
335/// ### `MyStruct::with_FIELD_mut<R>(&mut self, user: FnOnce(field: &mut FieldType) -> R) -> R`
336/// This function is generated for every **tail field** in your struct. It is the mutable version
337/// of `with_FIELD`.
338/// ### `MyStruct::with<R>(&self, user: FnOnce(fields: AllFields) -> R) -> R`
339/// Allows borrowing all **tail and immutably-borrowed fields** at once. Functions similarly to
340/// `with_FIELD`.
341/// ### `MyStruct::with_mut<R>(&self, user: FnOnce(fields: AllFields) -> R) -> R`
342/// Allows mutably borrowing all **tail fields** and immutably borrowing all **immutably-borrowed**
343/// fields at once. Functions similarly to `with_FIELD_mut`, except that you can borrow multiple
344/// fields as mutable at the same time and also have immutable access to any remaining fields.
345/// ### `MyStruct::into_heads(self) -> Heads`
346/// Drops all self-referencing fields and returns a struct containing all **head fields**.
347pub use ouroboros_macro::self_referencing;
348
349#[doc(hidden)]
350pub mod macro_help {
351 pub extern crate alloc;
352
353 pub use aliasable::boxed::AliasableBox;
354 pub use static_assertions::assert_impl_all;
355 use aliasable::boxed::UniqueBox;
356
357 pub struct CheckIfTypeIsStd<T>(core::marker::PhantomData<T>);
358
359 macro_rules! std_type_check {
360 ($fn_name:ident $T:ident $check_for:ty) => {
361 impl<$T: ?Sized> CheckIfTypeIsStd<$check_for> {
362 pub fn $fn_name() {}
363 }
364 };
365 }
366
367 std_type_check!(is_std_box_type T alloc::boxed::Box<T>);
368 #[cfg(target_has_atomic = "ptr")]
369 std_type_check!(is_std_arc_type T alloc::sync::Arc<T>);
370 std_type_check!(is_std_rc_type T alloc::rc::Rc<T>);
371
372 pub fn aliasable_boxed<T>(data: T) -> AliasableBox<T> {
373 AliasableBox::from_unique(UniqueBox::new(data))
374 }
375
376 pub fn unbox<T>(boxed: AliasableBox<T>) -> T {
377 *AliasableBox::into_unique(boxed)
378 }
379
380 /// Converts a reference to an object to a static reference This is
381 /// obviously unsafe because the compiler can no longer guarantee that the
382 /// data outlives the reference. It is up to the consumer to get rid of the
383 /// reference before the container is dropped. The + 'static ensures that
384 /// whatever we are referring to will remain valid indefinitely, that there
385 /// are no limitations on how long the pointer itself can live.
386 ///
387 /// # Safety
388 ///
389 /// The caller must ensure that the returned reference is not used after the originally passed
390 /// reference would become invalid.
391 pub unsafe fn change_lifetime<'old, 'new: 'old, T: 'new>(data: &'old T) -> &'new T {
392 &*(data as *const _)
393 }
394
395 /// Like change_lifetime, but for mutable references.
396 ///
397 /// # Safety
398 ///
399 /// The caller must ensure that the returned reference is not used after the originally passed
400 /// reference would become invalid.
401 pub unsafe fn change_lifetime_mut<'old, 'new: 'old, T: 'new>(data: &'old mut T) -> &'new mut T {
402 &mut *(data as *mut _)
403 }
404}