relaxed_ref/lib.rs
1//! This crate provides [`RelaxedRef<'a, T>`] and [`RelaxedRefMut<'a, T>`],
2//! relaxed versions of `&'a T` and `&'a mut T`, respectively, that are
3//! well-formed without requiring `T: 'a`.
4//! Instead, this bound is statically verified at the use site.
5//! This is useful in GAT-based type families and other contexts where imposing
6//! `T: 'a` on the surrounding interface is not always possible or desirable.
7//!
8//! # Motivation
9//!
10//! The reference types `&'a T` and `&'a mut T` require the
11//! [implied `T: 'a` bound][implied-bounds] to hold in order to be well-formed.
12//! This is for a good reason, since it should not be possible for a reference
13//! to outlive its referent.
14//! In some contexts, it is not possible to impose `T: 'a` due to interface
15//! constraints.
16//! This commonly occurs with type families based on generic associated types
17//! (GATs):
18//!
19//! ```compile_fail,E0309
20//! # use std::marker::PhantomData;
21//! #
22//! trait ValueFamily {
23//! type Of<T>;
24//! }
25//!
26//! struct RefFamily<'a>(PhantomData<&'a ()>);
27//! impl<'a> ValueFamily for RefFamily<'a> {
28//! // error[E0309]: the parameter type `T` may not live long enough
29//! type Of<T> = &'a T;
30//! }
31//! ```
32//!
33//! In many cases, a pragmatic solution is to replace `type Of<T>` in
34//! `ValueFamily` with `type Of<T: 'static>`, or `type Of<'a, T: 'a>` if `T`
35//! need not be `'static`.
36//! However, this requires changing the definition of `ValueFamily`,
37//! which is impossible if it is defined in another crate and possibly a
38//! breaking change otherwise.
39//! Moreover, `type Of<'a, T: 'a>` imposes `T: 'a` on every use of `Of`,
40//! even for implementations that do not use `'a`.
41//! In such cases, `type Of<T> = RelaxedRef<'a, T>` provides an alternative that
42//! keeps the lifetime constraints local to the implementations that use them:
43//!
44//! ```
45//! # use std::marker::PhantomData;
46//! # use relaxed_ref::RelaxedRef;
47//! # trait ValueFamily {
48//! # type Of<T>;
49//! # }
50//! #
51//! # struct RefFamily<'a>(PhantomData<&'a ()>);
52//! impl<'a> ValueFamily for RefFamily<'a> {
53//! type Of<T> = RelaxedRef<'a, T>; // OK
54//! }
55//! ```
56//!
57//! See [`examples/value_family.rs`][example-value-family] for a slightly more
58//! complete example.
59//!
60//! # Usage and Examples
61//!
62//! [`RelaxedRef<'a, T>`] and [`RelaxedRefMut<'a, T>`] behave similarly to their
63//! `&'a T` and `&'a mut T` counterparts.
64//! They implement `Deref`, enabling methods on `T` to be called directly.
65//! To avoid name clashes with methods on `T`, the wrappers expose their own
66//! functionality through associated functions.
67//! For example, [`RelaxedRef::into_ref`] converts a `RelaxedRef<'a, T>` into
68//! `&'a T` (if `T: 'a`).
69//!
70//! ```
71//! # use relaxed_ref::RelaxedRef;
72//! #
73//! # fn f<'a>() {
74//! #
75//! let int_ref: &'a i32 = todo!();
76//!
77//! // construct a `RelaxedRef<'a, i32>`
78//! let int_rref: RelaxedRef<'a, i32> = RelaxedRef::new(int_ref);
79//! // or
80//! let int_rref: RelaxedRef<'a, i32> = int_ref.into();
81//!
82//! // convert it back
83//! let _: &'a i32 = RelaxedRef::into_ref(int_rref);
84//! #
85//! # }
86//! ```
87//!
88//! `RelaxedRef<'a, T>` and `RelaxedRefMut<'a, T>` implement many common traits
89//! also implemented by `&'a T` and `&'a mut T`, such as `Copy` and `Clone`
90//! for `RelaxedRef<'a, T>`, `Deref` for both, and `DerefMut` for
91//! `RelaxedRefMut<'a, T>`.
92//! Traits like `Display` and `PartialEq` are implemented conditionally on `T`
93//! implementing these.
94//!
95//! ```
96//! # use relaxed_ref::RelaxedRef;
97//! #
98//! let i = 0;
99//! let r = RelaxedRef::new(&i);
100//!
101//! // like a reference, `RelaxedRef<'a, T>` is `Copy`
102//! let copies = (r, r, r);
103//!
104//! // prints, e.g., "r: 0, ptr: 0x7ffd2616e6c0"
105//! println!("r: {r}, ptr: {ptr:p}", ptr = RelaxedRef::as_ptr(&r));
106//!
107//! let x = RelaxedRef::new(&1);
108//! let y = RelaxedRef::new(&1);
109//!
110//! // `RelaxedRef<'a, T>` implements `PartialEq` if `T` does
111//! assert_eq!(x, y);
112//!
113//! // we can dereference `RelaxedRef<'a, T>` using `*`
114//! let sum = *x + *y;
115//! assert_eq!(sum, 2);
116//!
117//! // we can also call methods of `T` directly
118//! let s = RelaxedRef::new("test");
119//! assert_eq!(s.len(), 4);
120//! ```
121//!
122//! `RelaxedRefMut<'a, T>` is similar to `RelaxedRef<'a, T>`, but also allows
123//! mutating the referent:
124//!
125//! ```
126//! # use relaxed_ref::RelaxedRefMut;
127//! #
128//! let mut i = 0;
129//! let mut r = RelaxedRefMut::new(&mut i);
130//! *r = 1;
131//! assert_eq!(i, 1);
132//! ```
133//!
134//! # Soundness
135//!
136//! Even though [`RelaxedRef<'a, T>`] and [`RelaxedRefMut<'a, T>`] are
137//! well-formed independently of whether `T: 'a`, they cannot be used to create
138//! invalid references.
139//! The documentation for each type explains why its implementation is sound.
140//!
141//! # Internals
142//!
143//! [`RelaxedRef<'a, T>`] and [`RelaxedRefMut<'a, T>`] internally store a
144//! [`NonNull<T>`](core::ptr::NonNull) pointer.
145//! (They cannot simply wrap a `&'a T` or `&'a mut T`, since that would impose
146//! `T: 'a`, defeating the purpose of these types.)
147//!
148//! Both types are `#[repr(transparent)]` and are guaranteed to have the same
149//! size and alignment as their corresponding reference types.
150//! They also benefit from the null pointer optimization, so it is guaranteed
151//! that
152//! `size_of::<Option<RelaxedRef<'a, T>>>() == size_of::<RelaxedRef<'a, T>>()`
153//! and
154//! `size_of::<Option<RelaxedRefMut<'a, T>>>() == size_of::<RelaxedRefMut<'a, T>>()`
155//! for all types `T` (and lifetimes `'a`).
156//!
157//! # MSRV
158//!
159//! The minimum supported Rust version (MSRV) is 1.56.0.
160//! Note that GATs, the main use case of this crate, were stabilized in Rust
161//! 1.65.0.
162//! The crate itself does not use them, but some examples do.
163//!
164//! Some functions are only `const fn` on Rust 1.58.0+ or 1.83.0+.
165//! This is documented per function.
166//!
167//! [implied-bounds]: https://doc.rust-lang.org/reference/trait-bounds.html#implied-bounds
168//! [example-value-family]: https://github.com/mdjpoppe/relaxed-ref/blob/main/examples/value_family.rs
169
170#![no_std]
171#![deny(unsafe_op_in_unsafe_fn)]
172#![warn(missing_docs)]
173
174mod relaxed_ref;
175mod relaxed_ref_mut;
176
177pub use relaxed_ref::RelaxedRef;
178pub use relaxed_ref_mut::RelaxedRefMut;