Skip to main content

fallow_extract/
js_text.rs

1//! Conversion of JavaScript string values to Rust text.
2
3use std::borrow::Cow;
4
5use oxc_ast::StaticPropertyName;
6use oxc_str::JSStr;
7
8/// The text of a JavaScript string value.
9///
10/// A well-formed value is borrowed. A value with a lone surrogate is owned, with
11/// each lone surrogate written as `\uXXXX` (as `JSStr::display` does). Oxc 0.152
12/// also stored a lone surrogate as escaped text (`\u{FFFD}XXXX`), so the text of
13/// every well-formed value is the same as before.
14pub trait JsText<'a> {
15    /// Return the value as UTF-8 text.
16    fn text(self) -> Cow<'a, str>;
17}
18
19impl<'a> JsText<'a> for JSStr<'a> {
20    fn text(self) -> Cow<'a, str> {
21        self.as_str()
22            .map_or_else(|| Cow::Owned(self.display().to_string()), Cow::Borrowed)
23    }
24}
25
26impl<'b> JsText<'b> for &'b StaticPropertyName<'_> {
27    fn text(self) -> Cow<'b, str> {
28        self.as_js_str().text()
29    }
30}
31
32/// The text of a static property name, as [`JsText::text`] gives it, without a
33/// borrow of the name.
34#[must_use]
35pub fn static_name_text(name: StaticPropertyName<'_>) -> Cow<'_, str> {
36    match name {
37        StaticPropertyName::Borrowed(name) => name.text(),
38        StaticPropertyName::Owned(name) => Cow::Owned(name.into_string()),
39    }
40}