oxc_allocator/
convert.rs

1#![expect(clippy::inline_always)]
2
3use crate::{Allocator, Box};
4
5/// This trait works similarly to the standard library [`From`] trait.
6///
7/// It comes with a similar implementation containing blanket implementation for [`IntoIn`],
8/// reflective implementation and a bunch of primitive conversions from Rust types to their arena equivalent.
9pub trait FromIn<'a, T>: Sized {
10    /// Converts to this type from the input type within the given `allocator`.
11    fn from_in(value: T, allocator: &'a Allocator) -> Self;
12}
13
14/// This trait works similarly to the standard library [`Into`] trait.
15/// It is similar to [`FromIn`] is reflective, A [`FromIn`] implementation also implicitly implements
16/// [`IntoIn`] for the opposite type.
17pub trait IntoIn<'a, T>: Sized {
18    /// Converts this type into the (usually inferred) input type within the given `allocator`.
19    fn into_in(self, allocator: &'a Allocator) -> T;
20}
21
22/// `FromIn` is reflective
23impl<'a, T> FromIn<'a, T> for T {
24    #[inline(always)]
25    fn from_in(t: T, _: &'a Allocator) -> T {
26        t
27    }
28}
29
30/// `FromIn` implicitly implements `IntoIn`.
31impl<'a, T, U> IntoIn<'a, U> for T
32where
33    U: FromIn<'a, T>,
34{
35    #[inline]
36    fn into_in(self, allocator: &'a Allocator) -> U {
37        U::from_in(self, allocator)
38    }
39}
40
41// ---------------- Primitive allocations ----------------
42
43impl<'a> FromIn<'a, String> for &'a str {
44    #[inline(always)]
45    fn from_in(value: String, allocator: &'a Allocator) -> Self {
46        allocator.alloc_str(value.as_str())
47    }
48}
49
50impl<'a, T> FromIn<'a, T> for Box<'a, T> {
51    #[inline(always)]
52    fn from_in(value: T, allocator: &'a Allocator) -> Self {
53        Box::new_in(value, allocator)
54    }
55}
56
57impl<'a, T> FromIn<'a, Option<T>> for Option<Box<'a, T>> {
58    #[inline(always)]
59    fn from_in(value: Option<T>, allocator: &'a Allocator) -> Self {
60        value.map(|it| Box::new_in(it, allocator))
61    }
62}