Skip to main content

arena_box/
lib.rs

1#![no_std]
2#![doc = include_str!("../README.md")]
3
4extern crate alloc;
5
6use alloc::boxed::Box;
7use bumpalo::Bump;
8use core::ops::{Deref, DerefMut};
9use core::pin::Pin;
10use core::ptr::NonNull;
11
12/// A trait for types that have a lifetime parameter.
13pub trait WithLifetime {
14    /// The type with a lifetime parameter.
15    type With<'a>;
16}
17
18/// A macro to create a convenient alias for the smart pointer and also
19/// implement the required traits.
20///
21/// You can control the visibility of the alias, so you can make your
22/// struct public as part of your API, while keeping the arena implementation
23/// private.
24///
25/// ```ignore
26/// // Generated alias can have different visibility
27/// make_arena_version!(Data, pub ArenaData);         // public
28/// make_arena_version!(Data, pub(crate) ArenaData);  // crate-only
29/// make_arena_version!(Data, ArenaData);             // private
30/// ```
31///
32/// # Example
33///
34/// ```
35/// # use arena_box::*;
36///
37/// pub struct Data<'a> {
38///    msg: &'a str,
39/// }
40///
41/// make_arena_version!(Data, pub ArenaData);
42/// ```
43#[macro_export]
44macro_rules! make_arena_version {
45    ($name:ident, $vis:vis $alias:ident) => {
46        $vis type $alias = ArenaBox<$name<'static>>;
47
48        impl WithLifetime for $name<'static> {
49            type With<'a> = $name<'a>;
50        }
51    };
52}
53
54/// A handle for mutating the data in an `ArenaBox`.
55///
56/// This struct is created by the [`ArenaBox::mutate`] method.
57pub struct MutHandle<'b, T: WithLifetime> {
58    data: &'b mut <T as WithLifetime>::With<'b>,
59    arena: &'b Bump,
60}
61
62impl<'b, T: WithLifetime> MutHandle<'b, T> {
63    /// Returns a reference to the arena.
64    pub fn arena(&self) -> &'b Bump {
65        self.arena
66    }
67}
68
69impl<'b, T: WithLifetime> Deref for MutHandle<'b, T> {
70    type Target = <T as WithLifetime>::With<'b>;
71
72    fn deref(&self) -> &Self::Target {
73        self.data
74    }
75}
76
77impl<'b, T: WithLifetime> DerefMut for MutHandle<'b, T> {
78    fn deref_mut(&mut self) -> &mut Self::Target {
79        self.data
80    }
81}
82
83/// A smart pointer that holds a struct with arena allocated objects and the arena in the same struct.
84///
85/// This is useful for creating self-referential structs.
86///
87/// # Example
88///
89/// ```
90/// # use arena_box::*;
91///
92/// pub struct Data<'a> {
93///    msg: &'a str,
94/// }
95///
96/// make_arena_version!(Data, pub ArenaData);
97///
98/// let boxed = ArenaData::new(|arena| Data {
99///     msg: arena.alloc_str("Something"),
100/// });
101///
102/// assert_eq!(boxed.get().msg, "Something");
103/// ```
104pub struct ArenaBox<T: WithLifetime> {
105    arena: Pin<Box<Bump>>,
106    data: NonNull<T>,
107}
108
109impl<T: WithLifetime> ArenaBox<T> {
110    /// Creates a new `ArenaBox`.
111    ///
112    /// # Example
113    ///
114    /// ```
115    /// # use arena_box::*;
116    ///
117    /// pub struct Data<'a> {
118    ///    msg: &'a str,
119    /// }
120    ///
121    /// make_arena_version!(Data, pub ArenaData);
122    ///
123    /// let boxed = ArenaData::new(|arena| Data {
124    ///     msg: arena.alloc_str("Something"),
125    /// });
126    ///
127    /// assert_eq!(boxed.get().msg, "Something");
128    /// ```
129    pub fn new<F>(build: F) -> Self
130    where
131        F: for<'a> FnOnce(&'a Bump) -> <T as WithLifetime>::With<'a>,
132    {
133        let arena = Box::pin(Bump::new());
134        let arena_ref: &Bump = arena.as_ref().get_ref();
135        let data_ref = arena_ref.alloc(build(arena_ref));
136        let data = unsafe {
137            // SAFETY: The arena is pinned, so the pointer to the data will be valid for the lifetime of the `ArenaBox`.
138            NonNull::new_unchecked(data_ref as *mut <T as WithLifetime>::With<'_> as *mut T)
139        };
140        ArenaBox { arena, data }
141    }
142
143    /// Creates a new `ArenaBox` by transforming data from another `ArenaBox`, reusing its arena.
144    ///
145    /// This allows you to build up data structures incrementally, where new types can reference
146    /// data from the original type. The source `ArenaBox` is consumed and its arena is moved
147    /// into the new `ArenaBox`.
148    ///
149    /// # Example
150    ///
151    /// ```
152    /// # use arena_box::*;
153    ///
154    /// #[derive(Debug, PartialEq)]
155    /// pub struct Data<'a> {
156    ///     msg: &'a str,
157    /// }
158    ///
159    /// #[derive(Debug, PartialEq)]
160    /// pub struct AugmentedData<'a> {
161    ///     original: &'a Data<'a>,
162    ///     extra: &'a str,
163    /// }
164    ///
165    /// make_arena_version!(Data, pub ArenaData);
166    /// make_arena_version!(AugmentedData, pub ArenaAugmentedData);
167    ///
168    /// let data = ArenaData::new(|arena| Data {
169    ///     msg: arena.alloc_str("hello"),
170    /// });
171    ///
172    /// // Transform Data into AugmentedData, reusing the arena
173    /// let augmented = ArenaAugmentedData::new_from(data, |arena, original| {
174    ///     AugmentedData {
175    ///         original, // Reference to the original Data!
176    ///         extra: arena.alloc_str("extra info"),
177    ///     }
178    /// });
179    ///
180    /// assert_eq!(augmented.get().original.msg, "hello");
181    /// assert_eq!(augmented.get().extra, "extra info");
182    /// ```
183    pub fn new_from<U: WithLifetime, F>(source: ArenaBox<U>, build: F) -> Self
184    where
185        F: for<'a> FnOnce(
186            &'a Bump,
187            &'a <U as WithLifetime>::With<'a>,
188        ) -> <T as WithLifetime>::With<'a>,
189    {
190        let ArenaBox { arena, data } = source;
191        let arena_ref = arena.as_ref().get_ref();
192
193        let source_data = unsafe { &*(data.as_ptr() as *const <U as WithLifetime>::With<'_>) };
194
195        let new_data_ref = arena_ref.alloc(build(arena_ref, source_data));
196        let new_data = unsafe {
197            NonNull::new_unchecked(new_data_ref as *mut <T as WithLifetime>::With<'_> as *mut T)
198        };
199
200        ArenaBox {
201            arena,
202            data: new_data,
203        }
204    }
205
206    /// Get a reference to the data within the arena.
207    ///
208    /// # Safety
209    ///
210    /// The returned reference is valid for the lifetime of the `ArenaBox`.
211    /// # Negative compilation test
212    ///
213    /// The following code should fail to compile because the lifetime of the
214    /// reference to the `Data` struct is tied to the `ArenaData` instance, and
215    /// cannot be extended beyond the lifetime of the `ArenaData` instance.
216    ///
217    /// ```compile_fail
218    /// # use arena_box::*;
219    /// # pub struct Data<'a> {
220    /// #     msg: &'a str,
221    /// # }
222    /// # make_arena_version!(Data, ArenaData);
223    /// let message: &str;
224    /// {
225    ///     let boxed = ArenaData::new(|arena| Data {
226    ///         msg: arena.alloc_str("Something"),
227    ///     });
228    ///     message = boxed.get().msg; // Should fail: cannot extend lifetime
229    /// }
230    /// assert_eq!(message, "Something");
231    /// ```
232    pub fn get<'b>(&'b self) -> &'b <T as WithLifetime>::With<'b> {
233        // SAFETY: The data is guaranteed to be valid for the lifetime of the `ArenaBox`.
234        unsafe { &*(self.data.as_ptr() as *const <T as WithLifetime>::With<'b>) }
235    }
236
237    /// Mutates the data in the `ArenaBox`.
238    ///
239    /// This method returns a [`MutHandle`] that can be used to mutate the data.
240    ///
241    /// # Example
242    ///
243    /// ```
244    /// # use arena_box::*;
245    ///
246    /// pub struct Data<'a> {
247    ///   msg: &'a str,
248    /// }
249    ///
250    /// make_arena_version!(Data, pub ArenaData);
251    ///
252    /// let mut boxed = ArenaData::new(|arena| Data {
253    ///    msg: arena.alloc_str("Something"),
254    /// });
255    ///
256    /// assert_eq!(boxed.get().msg, "Something");
257    ///
258    /// {
259    ///    let mut handle = boxed.mutate();
260    ///    handle.msg = handle.arena().alloc_str("Something different");
261    /// }
262    ///
263    /// assert_eq!(boxed.get().msg, "Something different");
264    /// ```
265    pub fn mutate<'b>(&'b mut self) -> MutHandle<'b, T> {
266        // SAFETY: The data is guaranteed to be valid for the lifetime of the `ArenaBox`.
267        let data = unsafe { &mut *(self.data.as_ptr() as *mut <T as WithLifetime>::With<'b>) };
268        let arena = self.arena.as_ref().get_ref();
269        MutHandle { data, arena }
270    }
271}
272
273impl<T: core::fmt::Display + WithLifetime> core::fmt::Display for ArenaBox<T>
274where
275    for<'a> T::With<'a>: core::fmt::Display,
276{
277    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
278        core::fmt::Display::fmt(self.get(), f)
279    }
280}
281
282impl<T: core::fmt::Debug + WithLifetime> core::fmt::Debug for ArenaBox<T>
283where
284    for<'a> T::With<'a>: core::fmt::Debug,
285{
286    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
287        core::fmt::Debug::fmt(self.get(), f)
288    }
289}
290
291impl<T: WithLifetime> PartialEq for ArenaBox<T>
292where
293    for<'a> T::With<'a>: PartialEq,
294{
295    fn eq(&self, other: &Self) -> bool {
296        self.data == other.data || self.get() == other.get()
297    }
298}
299
300#[cfg(test)]
301mod tests {
302    use super::*;
303
304    #[derive(Debug, PartialEq)]
305    struct Data<'a> {
306        msg: &'a str,
307    }
308    make_arena_version!(Data, ArenaData);
309
310    #[test]
311    fn test_build() {
312        let boxed = ArenaData::new(|arena| Data {
313            msg: arena.alloc_str("Something"),
314        });
315        assert_eq!(boxed.get().msg, "Something");
316    }
317
318    #[test]
319    fn test_update() {
320        let mut boxed = ArenaData::new(|arena| Data {
321            msg: arena.alloc_str("Something"),
322        });
323        assert_eq!(boxed.get().msg, "Something");
324
325        {
326            let mut handle = boxed.mutate();
327            handle.msg = handle.arena().alloc_str("Something different"); // DerefMut
328        }
329
330        let message = boxed.get().msg;
331        assert_eq!(message, "Something different");
332    }
333
334    #[test]
335    fn test_update_twice() {
336        let mut boxed = ArenaData::new(|arena| Data {
337            msg: arena.alloc_str("Something"),
338        });
339        assert_eq!(boxed.get().msg, "Something");
340
341        {
342            let mut handle = boxed.mutate();
343            handle.msg = handle.arena().alloc_str("Something different"); // DerefMut
344        }
345
346        assert_eq!(boxed.get().msg, "Something different");
347
348        {
349            let mut handle = boxed.mutate();
350            handle.msg = handle.arena().alloc_str("Something else"); // DerefMut
351        }
352        assert_eq!(boxed.get().msg, "Something else");
353    }
354
355    fn do_something(boxed: ArenaData) {
356        // ArenaBox moved here
357        assert_eq!(boxed.get().msg, "Foo");
358    }
359
360    #[test]
361    fn test_move() {
362        let boxed = ArenaData::new(|arena| Data {
363            msg: arena.alloc_str("Foo"),
364        });
365        let r = boxed.get();
366        assert_eq!(r.msg, "Foo");
367        do_something(boxed);
368    }
369
370    #[derive(Debug, PartialEq)]
371    struct AugmentedData<'arena> {
372        data: &'arena Data<'arena>,
373        extra: &'arena str,
374    }
375
376    make_arena_version!(AugmentedData, ArenaAugmentedData);
377
378    #[test]
379    fn test_new_from() {
380        let a = ArenaData::new(|arena| Data {
381            msg: arena.alloc_str("hello"),
382        });
383
384        let b = ArenaAugmentedData::new_from(a, |arena, data| AugmentedData {
385            data, // Reference to the original!
386            extra: arena.alloc_str("extra info"),
387        });
388
389        assert_eq!(
390            *b.get(),
391            AugmentedData {
392                data: &Data { msg: "hello" },
393                extra: "extra info",
394            }
395        );
396    }
397
398    #[derive(Debug, PartialEq)]
399    struct MyError<'arena> {
400        message: &'arena str,
401        details: &'arena str,
402    }
403    make_arena_version!(MyError, ArenaMyError);
404    impl core::fmt::Display for MyError<'_> {
405        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
406            write!(f, "{}", self.message)
407        }
408    }
409
410    #[test]
411    fn test_as_an_error() {
412        fn return_err() -> Result<(), ArenaMyError> {
413            Err(ArenaMyError::new(|arena| MyError {
414                message: arena.alloc_str("an error happened"),
415                details: "",
416            }))
417        }
418        let result = return_err().map_err(|mut e| {
419            // Handle the error here
420            let mut handle = e.mutate();
421            handle.details = handle.arena().alloc_str("while running this test case");
422            e
423        });
424        let Err(e) = result else {
425            panic!("Expected an error");
426        };
427        assert_eq!(
428            *e.get(),
429            MyError {
430                message: "an error happened",
431                details: "while running this test case",
432            }
433        );
434        assert_eq!("an error happened", alloc::format!("{}", e));
435        assert_eq!(
436            r#"MyError { message: "an error happened", details: "while running this test case" }"#,
437            alloc::format!("{:?}", e)
438        );
439    }
440
441    #[test]
442    fn test_equality() {
443        let a = ArenaMyError::new(|arena| MyError {
444            message: arena.alloc_str("an error happened"),
445            details: arena.alloc_str("while running this test case"),
446        });
447        let mut b = ArenaMyError::new(|arena| MyError {
448            message: arena.alloc_str("an error happened"),
449            details: arena.alloc_str("while running this test case"),
450        });
451        assert_eq!(a, b);
452        {
453            let mut handle = b.mutate();
454            handle.details = "";
455        }
456        assert_ne!(a, b);
457    }
458}