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