Skip to content

Commit 115ac3b

Browse files
committed
feat(allocator): introduce FromIn and IntoIn traits. (#4088)
1 parent 5c31236 commit 115ac3b

File tree

2 files changed

+70
-1
lines changed

2 files changed

+70
-1
lines changed

crates/oxc_allocator/src/convert.rs

+66
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,66 @@
1+
#![allow(clippy::inline_always)]
2+
3+
use 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.
8+
pub trait FromIn<'a, T>: Sized {
9+
fn from_in(value: T, alloc: &'a Allocator) -> Self;
10+
}
11+
12+
/// This trait works similarly to the standard library `Into` trait.
13+
/// It is similar to `FromIn` is reflective, A `FromIn` implementation also implicitly implements
14+
/// `IntoIn` for the opposite type.
15+
pub trait IntoIn<'a, T>: Sized {
16+
fn into_in(self, alloc: &'a Allocator) -> T;
17+
}
18+
19+
/// `FromIn` is reflective
20+
impl<'a, T> FromIn<'a, T> for T {
21+
#[inline(always)]
22+
fn from_in(t: T, _: &'a Allocator) -> T {
23+
t
24+
}
25+
}
26+
27+
/// `FromIn` implicitly implements `IntoIn`.
28+
impl<'a, T, U> IntoIn<'a, U> for T
29+
where
30+
U: FromIn<'a, T>,
31+
{
32+
#[inline]
33+
fn into_in(self, alloc: &'a Allocator) -> U {
34+
U::from_in(self, alloc)
35+
}
36+
}
37+
38+
// ---------------- Primitive allocations ----------------
39+
40+
impl<'a> FromIn<'a, String> for crate::String<'a> {
41+
#[inline(always)]
42+
fn from_in(value: String, alloc: &'a Allocator) -> Self {
43+
crate::String::from_str_in(value.as_str(), alloc)
44+
}
45+
}
46+
47+
impl<'a> FromIn<'a, String> for &'a str {
48+
#[inline(always)]
49+
fn from_in(value: String, alloc: &'a Allocator) -> Self {
50+
crate::String::from_str_in(value.as_str(), alloc).into_bump_str()
51+
}
52+
}
53+
54+
impl<'a, T> FromIn<'a, T> for Box<'a, T> {
55+
#[inline(always)]
56+
fn from_in(value: T, alloc: &'a Allocator) -> Self {
57+
Box::new_in(value, alloc)
58+
}
59+
}
60+
61+
impl<'a, T> FromIn<'a, Option<T>> for Option<Box<'a, T>> {
62+
#[inline(always)]
63+
fn from_in(value: Option<T>, alloc: &'a Allocator) -> Self {
64+
value.map(|it| Box::new_in(it, alloc))
65+
}
66+
}

crates/oxc_allocator/src/lib.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,13 @@ use std::{
44
};
55

66
mod arena;
7+
mod convert;
78

8-
pub use arena::{Box, String, Vec};
99
use bumpalo::Bump;
1010

11+
pub use arena::{Box, String, Vec};
12+
pub use convert::{FromIn, IntoIn};
13+
1114
#[derive(Default)]
1215
pub struct Allocator {
1316
bump: Bump,

0 commit comments

Comments
 (0)