Skip to content

Commit

Permalink
feat(ast): add AstBuilder::atom_from_cow (#7974)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
overlookmotel committed Dec 18, 2024
1 parent c30a982 commit 8b7c5ae
Showing 1 changed file with 15 additions and 1 deletion.
16 changes: 15 additions & 1 deletion crates/oxc_ast/src/ast_builder_impl.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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};
Expand Down Expand Up @@ -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!
Expand Down

0 comments on commit 8b7c5ae

Please sign in to comment.