Skip to content

Commit 8b7c5ae

Browse files
committed
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.
1 parent c30a982 commit 8b7c5ae

File tree

1 file changed

+15
-1
lines changed

1 file changed

+15
-1
lines changed

crates/oxc_ast/src/ast_builder_impl.rs

+15-1
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
)]
77
#![warn(missing_docs)]
88

9-
use std::mem;
9+
use std::{borrow::Cow, mem};
1010

1111
use oxc_allocator::{Allocator, Box, FromIn, String, Vec};
1212
use oxc_span::{Atom, GetSpan, Span, SPAN};
@@ -87,6 +87,20 @@ impl<'a> AstBuilder<'a> {
8787
Atom::from_in(value, self.allocator)
8888
}
8989

90+
/// Convert a [`Cow<'a, str>`] to an [`Atom<'a>`].
91+
///
92+
/// If the `Cow` borrows a string from arena, returns an `Atom` which references that same string,
93+
/// without allocating a new one.
94+
///
95+
/// If the `Cow` is owned, allocates the string into arena to generate a new `Atom`.
96+
#[inline]
97+
pub fn atom_from_cow(self, value: &Cow<'a, str>) -> Atom<'a> {
98+
match value {
99+
Cow::Borrowed(s) => Atom::from(*s),
100+
Cow::Owned(s) => self.atom(s),
101+
}
102+
}
103+
90104
/// # SAFETY
91105
/// This method is completely unsound and should not be used.
92106
/// We need to remove all uses of it. Please don't add any more!

0 commit comments

Comments
 (0)