From 2c5f10b2de836668dd8656e4e4b15a0a216e4b11 Mon Sep 17 00:00:00 2001 From: rzvxa Date: Sun, 7 Jul 2024 21:52:31 +0330 Subject: [PATCH] feat(allocator): introduce `FromIn` and `IntoIn` traits. --- crates/oxc_allocator/src/convert.rs | 53 +++++++++++++++++++++++++++++ crates/oxc_allocator/src/lib.rs | 5 ++- 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 crates/oxc_allocator/src/convert.rs diff --git a/crates/oxc_allocator/src/convert.rs b/crates/oxc_allocator/src/convert.rs new file mode 100644 index 00000000000000..6515c10251d123 --- /dev/null +++ b/crates/oxc_allocator/src/convert.rs @@ -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> for Option> { + #[inline(always)] + fn from_in(value: Option, alloc: &'a Allocator) -> Self { + value.map(|it| Box::new_in(it, alloc)) + } +} diff --git a/crates/oxc_allocator/src/lib.rs b/crates/oxc_allocator/src/lib.rs index 06a73b03d49d6e..a8707326c0c57f 100644 --- a/crates/oxc_allocator/src/lib.rs +++ b/crates/oxc_allocator/src/lib.rs @@ -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,