From 8b7c5ae09cda7838e0ea64a8a573747b89b161ab Mon Sep 17 00:00:00 2001 From: overlookmotel <557937+overlookmotel@users.noreply.github.com> Date: Wed, 18 Dec 2024 02:25:35 +0000 Subject: [PATCH] feat(ast): add `AstBuilder::atom_from_cow` (#7974) Various methods e.g. `PropertyKey::static_name` return a `Cow<'a, str>`. When we need to create an `Atom` from such a `Cow`, we can avoid reallocating the string into arena again if the `Cow` already borrows an arena string. The `Atom` can reference that same string, rather than making another copy of it in arena. Add `AstBuilder::atom_from_cow` method for this purpose. --- crates/oxc_ast/src/ast_builder_impl.rs | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/crates/oxc_ast/src/ast_builder_impl.rs b/crates/oxc_ast/src/ast_builder_impl.rs index dd290078388c2..f7631bb38e9ff 100644 --- a/crates/oxc_ast/src/ast_builder_impl.rs +++ b/crates/oxc_ast/src/ast_builder_impl.rs @@ -6,7 +6,7 @@ )] #![warn(missing_docs)] -use std::mem; +use std::{borrow::Cow, mem}; use oxc_allocator::{Allocator, Box, FromIn, String, Vec}; use oxc_span::{Atom, GetSpan, Span, SPAN}; @@ -87,6 +87,20 @@ impl<'a> AstBuilder<'a> { Atom::from_in(value, self.allocator) } + /// Convert a [`Cow<'a, str>`] to an [`Atom<'a>`]. + /// + /// If the `Cow` borrows a string from arena, returns an `Atom` which references that same string, + /// without allocating a new one. + /// + /// If the `Cow` is owned, allocates the string into arena to generate a new `Atom`. + #[inline] + pub fn atom_from_cow(self, value: &Cow<'a, str>) -> Atom<'a> { + match value { + Cow::Borrowed(s) => Atom::from(*s), + Cow::Owned(s) => self.atom(s), + } + } + /// # SAFETY /// This method is completely unsound and should not be used. /// We need to remove all uses of it. Please don't add any more!