oxc_str 0.140.0

A collection of JavaScript tools written in Rust.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
use std::{
    borrow::{Borrow, Cow},
    fmt, hash,
    ops::Deref,
};

use oxc_allocator::{Allocator, ArenaStringBuilder, CloneIn, Dummy, FromIn, GetAllocator};
#[cfg(feature = "serialize")]
use oxc_estree::{ESTree, Serializer as ESTreeSerializer};
#[cfg(feature = "serialize")]
use serde::{Serialize, Serializer as SerdeSerializer};

use crate::CompactStr;

/// An inlinable string for oxc_allocator.
///
/// Use [CompactStr] with [Str::to_compact_str] or [Str::into_compact_str] for
/// the lifetimeless form.
#[repr(transparent)]
#[derive(Clone, Copy, Eq)]
pub struct Str<'a>(&'a str);

impl Str<'static> {
    /// Get a [`Str`] containing a static string.
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    pub const fn new_const(s: &'static str) -> Self {
        Str(s)
    }

    /// Get a [`Str`] containing the empty string (`""`).
    #[inline]
    pub const fn empty() -> Self {
        Self::new_const("")
    }
}

impl<'a> Str<'a> {
    /// Allocate provided `&str` into arena, and return a [`Str<'a>`].
    #[inline]
    pub fn from_str_in<A: GetAllocator<'a>>(s: &str, allocator: &A) -> Self {
        Self(allocator.allocator().alloc_str(s))
    }

    /// Borrow a string slice.
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    pub fn as_str(&self) -> &'a str {
        self.0
    }

    /// Convert this [`Str`] into a [`String`].
    ///
    /// This is the explicit form of [`Into<String>`], which [`Str`] also implements.
    #[inline]
    pub fn into_string(self) -> String {
        String::from(self.as_str())
    }

    /// Convert this [`Str`] into a [`CompactStr`].
    ///
    /// This is the explicit form of [`Into<CompactStr>`], which [`Str`] also implements.
    #[inline]
    pub fn into_compact_str(self) -> CompactStr {
        CompactStr::new(self.as_str())
    }

    /// Convert this [`Str`] into a [`CompactStr`] without consuming `self`.
    #[inline]
    pub fn to_compact_str(self) -> CompactStr {
        CompactStr::new(self.as_str())
    }

    /// Create new [`Str`] from a fixed-size array of `&str`s concatenated together,
    /// allocated in the given `allocator`.
    ///
    /// # Panics
    ///
    /// Panics if the sum of length of all strings exceeds `isize::MAX`.
    ///
    /// # Example
    /// ```
    /// use oxc_allocator::Allocator;
    /// use oxc_str::Str;
    ///
    /// let allocator = Allocator::new();
    /// let s = Str::from_strs_array_in(["hello", " ", "world", "!"], &&allocator);
    /// assert_eq!(s.as_str(), "hello world!");
    /// ```
    // `#[inline(always)]` because want compiler to be able to optimize where some of `strings`
    // are statically known. See `Allocator::alloc_concat_strs_array`.
    #[expect(clippy::inline_always)]
    #[inline(always)]
    pub fn from_strs_array_in<const N: usize, A: GetAllocator<'a>>(
        strings: [&str; N],
        allocator: &A,
    ) -> Str<'a> {
        Self::from(allocator.allocator().alloc_concat_strs_array(strings))
    }

    /// Convert a [`Cow<'a, str>`] to a [`Str<'a>`].
    ///
    /// If the `Cow` borrows a string from arena, returns a `Str` which references that same string,
    /// without allocating a new one.
    ///
    /// If the `Cow` is owned, allocates the string into arena to generate a new `Str`.
    #[inline]
    pub fn from_cow_in<A: GetAllocator<'a>>(value: &Cow<'a, str>, allocator: &A) -> Str<'a> {
        match value {
            Cow::Borrowed(s) => Str::from(*s),
            Cow::Owned(s) => Str::from_str_in(s, allocator),
        }
    }
}

impl<'new_alloc> CloneIn<'new_alloc> for Str<'_> {
    type Cloned = Str<'new_alloc>;

    #[inline]
    fn clone_in(&self, allocator: &'new_alloc Allocator) -> Self::Cloned {
        Str::from_in(self.as_str(), allocator)
    }
}

impl<'a> Dummy<'a> for Str<'a> {
    /// Create a dummy [`Str`].
    #[expect(clippy::inline_always)]
    #[inline(always)]
    fn dummy(_allocator: &'a Allocator) -> Self {
        Str::empty()
    }
}

impl<'alloc> FromIn<'alloc, &Str<'alloc>> for Str<'alloc> {
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn from_in(s: &Str<'alloc>, _: &'alloc Allocator) -> Self {
        *s
    }
}

impl<'alloc> FromIn<'alloc, &str> for Str<'alloc> {
    #[inline]
    fn from_in(s: &str, allocator: &'alloc Allocator) -> Self {
        Self::from(allocator.alloc_str(s))
    }
}

impl<'alloc> FromIn<'alloc, String> for Str<'alloc> {
    #[inline]
    fn from_in(s: String, allocator: &'alloc Allocator) -> Self {
        Self::from_in(s.as_str(), allocator)
    }
}

impl<'alloc> FromIn<'alloc, &String> for Str<'alloc> {
    #[inline]
    fn from_in(s: &String, allocator: &'alloc Allocator) -> Self {
        Self::from_in(s.as_str(), allocator)
    }
}

impl<'alloc> FromIn<'alloc, Cow<'_, str>> for Str<'alloc> {
    #[inline]
    fn from_in(s: Cow<'_, str>, allocator: &'alloc Allocator) -> Self {
        Self::from_in(&*s, allocator)
    }
}

impl<'a> From<&'a str> for Str<'a> {
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn from(s: &'a str) -> Self {
        Self(s)
    }
}

impl<'alloc> From<ArenaStringBuilder<'alloc>> for Str<'alloc> {
    #[inline]
    fn from(s: ArenaStringBuilder<'alloc>) -> Self {
        Self::from(s.into_str())
    }
}

impl<'a> From<Str<'a>> for &'a str {
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn from(s: Str<'a>) -> Self {
        s.as_str()
    }
}

impl From<Str<'_>> for CompactStr {
    #[inline]
    fn from(val: Str<'_>) -> Self {
        val.into_compact_str()
    }
}

impl From<Str<'_>> for String {
    #[inline]
    fn from(val: Str<'_>) -> Self {
        val.into_string()
    }
}

impl<'a> From<Str<'a>> for Cow<'a, str> {
    #[inline]
    fn from(value: Str<'a>) -> Self {
        Cow::Borrowed(value.as_str())
    }
}

impl Deref for Str<'_> {
    type Target = str;

    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

impl AsRef<str> for Str<'_> {
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Borrow<str> for Str<'_> {
    #[expect(clippy::inline_always)]
    #[inline(always)] // Because this is a no-op
    fn borrow(&self) -> &str {
        self.as_str()
    }
}

impl<T: AsRef<str>> PartialEq<T> for Str<'_> {
    #[inline]
    fn eq(&self, other: &T) -> bool {
        self.as_str() == other.as_ref()
    }
}

impl PartialEq<Str<'_>> for &str {
    #[inline]
    fn eq(&self, other: &Str<'_>) -> bool {
        *self == other.as_str()
    }
}

impl PartialEq<str> for Str<'_> {
    #[inline]
    fn eq(&self, other: &str) -> bool {
        self.as_str() == other
    }
}

impl PartialEq<Str<'_>> for Cow<'_, str> {
    #[inline]
    fn eq(&self, other: &Str<'_>) -> bool {
        self.as_ref() == other.as_str()
    }
}

impl hash::Hash for Str<'_> {
    #[inline]
    fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
        self.as_str().hash(hasher);
    }
}

impl fmt::Debug for Str<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(self.as_str(), f)
    }
}

impl fmt::Display for Str<'_> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(self.as_str(), f)
    }
}

#[cfg(feature = "serialize")]
impl Serialize for Str<'_> {
    #[inline] // Because it just delegates
    fn serialize<S: SerdeSerializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Serialize::serialize(self.as_str(), serializer)
    }
}

#[cfg(feature = "serialize")]
impl ESTree for Str<'_> {
    #[inline] // Because it just delegates
    fn serialize<S: ESTreeSerializer>(&self, serializer: S) {
        ESTree::serialize(self.as_str(), serializer);
    }
}

/// Creates a [`Str`] using interpolation of runtime expressions.
///
/// Identical to [`std`'s `format!` macro](std::format), except:
///
/// * First argument is the allocator.
/// * Produces a [`Str`] instead of a [`String`].
///
/// The string is built in the arena, without allocating an intermediate `String`.
///
/// # Panics
///
/// Panics if a formatting trait implementation returns an error.
///
/// # Example
///
/// ```
/// use oxc_allocator::Allocator;
/// use oxc_str::format_str;
/// let allocator = Allocator::new();
///
/// let s1 = "foo";
/// let s2 = "bar";
/// let formatted = format_str!(&allocator, "{s1}.{s2}");
/// assert_eq!(formatted, "foo.bar");
/// ```
#[macro_export]
macro_rules! format_str {
    ($alloc:expr, $($arg:tt)*) => {{
        use ::std::{write, fmt::Write};
        use $crate::{Str, __internal::ArenaStringBuilder};

        let mut s = ArenaStringBuilder::new_in($alloc);
        write!(s, $($arg)*).unwrap();
        Str::from(s)
    }}
}

#[cfg(test)]
mod test {
    use oxc_allocator::Allocator;

    use super::*;

    #[test]
    #[expect(clippy::items_after_statements)]
    fn str_from_str_in() {
        let allocator = Allocator::new();
        let allocator = &allocator;

        // Pass an actual `Allocator`
        let s = Str::from_str_in("world", &allocator);
        assert_eq!(s.as_str(), "world");
        assert_eq!(s, Str::from("world"));

        // Pass a struct which implements `GetAllocator`
        struct Wrapper<'a>(&'a Allocator);

        impl<'a> GetAllocator<'a> for Wrapper<'a> {
            fn allocator(&self) -> &'a Allocator {
                self.0
            }
        }

        let wrapper = Wrapper(allocator);
        let s = Str::from_str_in("hello", &wrapper);
        assert_eq!(s.as_str(), "hello");
        assert_eq!(s, Str::from("hello"));
    }

    #[test]
    #[expect(clippy::items_after_statements)]
    fn str_from_strs_array_in() {
        let allocator = Allocator::new();
        let allocator = &allocator;

        // Pass an actual `Allocator`
        let s = Str::from_strs_array_in(["hello", " ", "world", "!"], &allocator);
        assert_eq!(s.as_str(), "hello world!");
        assert_eq!(s, Str::from("hello world!"));

        // Pass a struct which implements `GetAllocator`
        struct Wrapper<'a>(&'a Allocator);

        impl<'a> GetAllocator<'a> for Wrapper<'a> {
            fn allocator(&self) -> &'a Allocator {
                self.0
            }
        }

        let wrapper = Wrapper(allocator);
        let s = Str::from_strs_array_in(["foo", "_", "bar"], &wrapper);
        assert_eq!(s.as_str(), "foo_bar");
        assert_eq!(s, Str::from("foo_bar"));
    }

    #[test]
    #[expect(clippy::items_after_statements)]
    fn str_from_cow_in() {
        let allocator = Allocator::new();
        let allocator = &allocator;

        // `Cow::Borrowed` references the same string, without allocating in arena
        let borrowed = "world";
        let used_before = allocator.used_bytes();
        let s = Str::from_cow_in(&Cow::Borrowed(borrowed), &allocator);
        assert_eq!(s.as_str(), "world");
        assert_eq!(s, Str::from("world"));
        assert_eq!(s.as_str().as_ptr(), borrowed.as_ptr());
        assert_eq!(allocator.used_bytes(), used_before);

        // `Cow::Owned` allocates a new string in arena
        let owned = "owned".to_string();
        let owned_ptr = owned.as_ptr();
        let s = Str::from_cow_in(&Cow::Owned(owned), &allocator);
        assert_eq!(s.as_str(), "owned");
        assert_eq!(s, Str::from("owned"));
        assert_ne!(s.as_str().as_ptr(), owned_ptr);
        assert!(allocator.used_bytes() > used_before);

        // Pass a struct which implements `GetAllocator`
        struct Wrapper<'a>(&'a Allocator);

        impl<'a> GetAllocator<'a> for Wrapper<'a> {
            fn allocator(&self) -> &'a Allocator {
                self.0
            }
        }

        let wrapper = Wrapper(allocator);
        let s = Str::from_cow_in(&Cow::Borrowed("hello"), &wrapper);
        assert_eq!(s.as_str(), "hello");
        assert_eq!(s, Str::from("hello"));
    }
}