Skip to content

Commit

Permalink
feat(allocator): introduce FromIn and IntoIn traits.
Browse files Browse the repository at this point in the history
  • Loading branch information
rzvxa committed Jul 7, 2024
1 parent f8d77e4 commit 2c5f10b
Show file tree
Hide file tree
Showing 2 changed files with 57 additions and 1 deletion.
53 changes: 53 additions & 0 deletions crates/oxc_allocator/src/convert.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
#![allow(clippy::inline_always)]

use crate::{Allocator, Box};

pub trait FromIn<'a, T> {
fn from_in(value: T, alloc: &'a Allocator) -> Self;
}

pub trait IntoIn<'a, T> {
fn into_in(self, alloc: &'a Allocator) -> T;
}

/// `FromIn` is reflective
impl<'a, T> FromIn<'a, T> for T {
#[inline(always)]
fn from_in(t: T, _: &'a Allocator) -> T {
t
}
}

/// `FromIn` implicitly implements `IntoIn`.
impl<'a, T, U> IntoIn<'a, U> for T
where
U: FromIn<'a, T>,
{
#[inline]
fn into_in(self, alloc: &'a Allocator) -> U {
U::from_in(self, alloc)
}
}

// ---------------- Primitive allocations ----------------

impl<'a> FromIn<'a, String> for crate::String<'a> {
#[inline(always)]
fn from_in(value: String, alloc: &'a Allocator) -> Self {
crate::String::from_str_in(value.as_str(), alloc)
}
}

impl<'a, T> FromIn<'a, T> for Box<'a, T> {
#[inline(always)]
fn from_in(value: T, alloc: &'a Allocator) -> Self {
Box::new_in(value, alloc)
}
}

impl<'a, T> FromIn<'a, Option<T>> for Option<Box<'a, T>> {
#[inline(always)]
fn from_in(value: Option<T>, alloc: &'a Allocator) -> Self {
value.map(|it| Box::new_in(it, alloc))
}
}
5 changes: 4 additions & 1 deletion crates/oxc_allocator/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,13 @@ use std::{
};

mod arena;
mod convert;

pub use arena::{Box, String, Vec};
use bumpalo::Bump;

pub use arena::{Box, String, Vec};
pub use convert::{FromIn, IntoIn};

#[derive(Default)]
pub struct Allocator {
bump: Bump,
Expand Down

0 comments on commit 2c5f10b

Please sign in to comment.