Skip to main content

deno_core/
fast_string.rs

1// Copyright 2018-2026 the Deno authors. MIT license.
2
3use std::borrow::Borrow;
4use std::ffi::OsStr;
5use std::fmt::Debug;
6use std::fmt::Display;
7use std::fmt::Formatter;
8use std::hash::Hash;
9use std::ops::Deref;
10use std::sync::Arc;
11
12use serde::Deserializer;
13use serde::Serializer;
14use url::Url;
15use v8::NewStringType;
16
17use crate::ToV8;
18
19static EMPTY_STRING: v8::OneByteConst =
20  v8::String::create_external_onebyte_const("".as_bytes());
21
22/// A static string that is compile-time checked to be ASCII and is stored in the
23/// most efficient possible way to create V8 strings.
24#[derive(Clone, Copy)]
25#[repr(transparent)]
26pub struct FastStaticString {
27  s: &'static v8::OneByteConst,
28}
29
30impl FastStaticString {
31  pub const fn new(s: &'static v8::OneByteConst) -> Self {
32    FastStaticString { s }
33  }
34
35  pub fn as_str(&self) -> &'static str {
36    self.s.as_ref()
37  }
38
39  pub fn as_bytes(&self) -> &'static [u8] {
40    self.s.as_ref()
41  }
42
43  #[doc(hidden)]
44  pub const fn create_external_onebyte_const(
45    s: &'static [u8],
46  ) -> v8::OneByteConst {
47    v8::String::create_external_onebyte_const(s)
48  }
49
50  /// Create an external one-byte string resource for runtime setup sources.
51  ///
52  /// # Safety
53  ///
54  /// In release builds, `s` must contain only ASCII data and must not exceed
55  /// `v8::String::kMaxLength`.
56  #[doc(hidden)]
57  #[inline(always)]
58  pub unsafe fn create_external_onebyte_const_unchecked_in_release(
59    s: &'static [u8],
60  ) -> v8::OneByteConst {
61    #[cfg(debug_assertions)]
62    {
63      v8::String::create_external_onebyte_const(s)
64    }
65    #[cfg(not(debug_assertions))]
66    {
67      // SAFETY: The caller guarantees that `s` is valid ASCII and within V8's
68      // maximum string length. Debug builds use the checked constructor above.
69      unsafe { v8::String::create_external_onebyte_const_unchecked(s) }
70    }
71  }
72
73  pub fn v8_string<'s, 'i>(
74    &self,
75    scope: &mut v8::PinScope<'s, 'i>,
76  ) -> Result<v8::Local<'s, v8::String>, FastStringV8AllocationError> {
77    FastString::from(*self).v8_string(scope)
78  }
79
80  pub const fn into_v8_const_ptr(&self) -> *const v8::OneByteConst {
81    self.s as _
82  }
83}
84
85impl From<&'static v8::OneByteConst> for FastStaticString {
86  fn from(s: &'static v8::OneByteConst) -> Self {
87    Self::new(s)
88  }
89}
90
91impl From<FastStaticString> for *const v8::OneByteConst {
92  fn from(val: FastStaticString) -> Self {
93    val.into_v8_const_ptr()
94  }
95}
96
97impl Hash for FastStaticString {
98  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
99    self.as_str().hash(state)
100  }
101}
102
103impl AsRef<str> for FastStaticString {
104  fn as_ref(&self) -> &str {
105    self.as_str()
106  }
107}
108
109impl Deref for FastStaticString {
110  type Target = str;
111  fn deref(&self) -> &Self::Target {
112    self.as_str()
113  }
114}
115
116impl Borrow<str> for FastStaticString {
117  fn borrow(&self) -> &str {
118    self.as_str()
119  }
120}
121
122impl Debug for FastStaticString {
123  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
124    Debug::fmt(self.as_str(), f)
125  }
126}
127
128impl Default for FastStaticString {
129  fn default() -> Self {
130    FastStaticString { s: &EMPTY_STRING }
131  }
132}
133
134impl PartialEq for FastStaticString {
135  fn eq(&self, other: &Self) -> bool {
136    self.as_bytes() == other.as_bytes()
137  }
138}
139
140impl Eq for FastStaticString {}
141
142impl Display for FastStaticString {
143  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
144    f.write_str(self.as_str())
145  }
146}
147
148#[derive(Debug, deno_error::JsError)]
149#[class(type)]
150pub struct FastStringV8AllocationError;
151
152impl std::error::Error for FastStringV8AllocationError {}
153impl std::fmt::Display for FastStringV8AllocationError {
154  fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
155    write!(
156      f,
157      "failed to allocate string; buffer exceeds maximum length"
158    )
159  }
160}
161
162/// Module names and code can be sourced from strings or bytes that are either owned or borrowed. This enumeration allows us
163/// to perform a minimal amount of cloning and format-shifting of the underlying data.
164///
165/// Note that any [`FastString`] created using [`ascii_str!`] must contain only ASCII characters. Other [`FastString`] types
166/// may be UTF-8, though this will incur a small performance penalty. It is recommended that large, static strings always
167/// use [`ascii_str!`].
168///
169/// Examples of ways to construct a [`FastString`]:
170///
171/// ```rust
172/// # use deno_core::{ascii_str, FastString};
173///
174/// let code: FastString = ascii_str!("a string").into();
175/// let code: FastString = format!("a string").into();
176/// ```
177pub struct FastString {
178  inner: FastStringInner,
179}
180
181enum FastStringInner {
182  /// Created from static data.
183  Static(&'static str),
184
185  /// Created from static ascii, known to contain only ASCII chars.
186  StaticAscii(&'static str),
187
188  /// Created from static data, known to contain only ASCII chars.
189  StaticConst(FastStaticString),
190
191  /// An owned chunk of data. Note that we use `Box` rather than `Vec` to avoid the
192  /// storage overhead.
193  Owned(Box<str>),
194
195  // Scripts loaded from the `deno_graph` infrastructure.
196  Arc(Arc<str>),
197}
198
199impl FastString {
200  /// Create a [`FastString`] from a static string. The string may contain
201  /// non-ASCII characters, and if so, will take the slower path when used
202  /// in v8.
203  pub const fn from_static(s: &'static str) -> Self {
204    if s.is_ascii() {
205      Self {
206        inner: FastStringInner::StaticAscii(s),
207      }
208    } else {
209      Self {
210        inner: FastStringInner::Static(s),
211      }
212    }
213  }
214
215  /// Create a [`FastString`] from a static string that is known to contain
216  /// only ASCII characters.
217  ///
218  /// Note: This function is deliberately not `const fn`. Use `from_static`
219  /// in const contexts.
220  ///
221  /// # Safety
222  ///
223  /// It is unsafe to specify a non-ASCII string here because this will be
224  /// referenced in an external one byte static string in v8, which requires
225  /// the data be Latin-1 or ASCII.
226  ///
227  /// This should only be used in scenarios where you know a string is ASCII
228  /// and you want to avoid the performance overhead of checking if a string
229  /// is ASCII that `from_static` does.
230  pub unsafe fn from_ascii_static_unchecked(s: &'static str) -> Self {
231    debug_assert!(
232      s.is_ascii(),
233      "use `from_non_ascii_static_unsafe` for non-ASCII strings",
234    );
235    Self {
236      inner: FastStringInner::StaticAscii(s),
237    }
238  }
239
240  /// Create a [`FastString`] from a static string that may contain non-ASCII
241  /// characters.
242  ///
243  /// This should only be used in scenarios where you know a string is not ASCII
244  /// and you want to avoid the performance overhead of checking if the string
245  /// is ASCII that `from_static` does.
246  ///
247  /// Note: This function is deliberately not `const fn`. Use `from_static`
248  /// in const contexts. This function is not unsafe because using this with
249  /// an ascii string will just not be as optimal for performance.
250  pub fn from_non_ascii_static(s: &'static str) -> Self {
251    Self {
252      inner: FastStringInner::Static(s),
253    }
254  }
255
256  /// Returns a static string from this `FastString`, if available.
257  pub fn as_static_str(&self) -> Option<&'static str> {
258    match self.inner {
259      FastStringInner::Static(s) => Some(s),
260      FastStringInner::StaticAscii(s) => Some(s),
261      FastStringInner::StaticConst(s) => Some(s.as_str()),
262      _ => None,
263    }
264  }
265
266  /// Creates a cheap copy of this [`FastString`], potentially transmuting it
267  /// to a faster form. Note that this is not a clone operation as it consumes
268  /// the old [`FastString`].
269  pub fn into_cheap_copy(self) -> (Self, Self) {
270    match self.inner {
271      FastStringInner::Owned(s) => {
272        let s: Arc<str> = s.into();
273        (
274          Self {
275            inner: FastStringInner::Arc(s.clone()),
276          },
277          Self {
278            inner: FastStringInner::Arc(s),
279          },
280        )
281      }
282      _ => (self.try_clone().unwrap(), self),
283    }
284  }
285
286  /// If this [`FastString`] is cheaply cloneable, returns a clone.
287  pub fn try_clone(&self) -> Option<Self> {
288    match &self.inner {
289      FastStringInner::Static(s) => Some(Self {
290        inner: FastStringInner::Static(s),
291      }),
292      FastStringInner::StaticAscii(s) => Some(Self {
293        inner: FastStringInner::StaticAscii(s),
294      }),
295      FastStringInner::StaticConst(s) => Some(Self {
296        inner: FastStringInner::StaticConst(*s),
297      }),
298      FastStringInner::Arc(s) => Some(Self {
299        inner: FastStringInner::Arc(s.clone()),
300      }),
301      FastStringInner::Owned(_s) => None,
302    }
303  }
304
305  #[inline(always)]
306  pub fn as_bytes(&self) -> &[u8] {
307    self.as_str().as_bytes()
308  }
309
310  #[inline(always)]
311  pub fn as_str(&self) -> &str {
312    match &self.inner {
313      // TODO(mmastrac): When we get a const deref, as_str can be const
314      FastStringInner::Arc(s) => s,
315      FastStringInner::Owned(s) => s,
316      FastStringInner::Static(s) => s,
317      FastStringInner::StaticAscii(s) => s,
318      FastStringInner::StaticConst(s) => s.as_str(),
319    }
320  }
321
322  /// Create a v8 string from this [`FastString`]. If the string is static and contains only ASCII characters,
323  /// an external one-byte static is created.
324  pub fn v8_string<'a, 'i>(
325    &self,
326    scope: &mut v8::PinScope<'a, 'i>,
327  ) -> Result<v8::Local<'a, v8::String>, FastStringV8AllocationError> {
328    match self.inner {
329      FastStringInner::StaticAscii(s) => {
330        v8::String::new_external_onebyte_static(scope, s.as_bytes())
331          .ok_or(FastStringV8AllocationError)
332      }
333      FastStringInner::StaticConst(s) => {
334        v8::String::new_from_onebyte_const(scope, s.s)
335          .ok_or(FastStringV8AllocationError)
336      }
337      _ => {
338        v8::String::new_from_utf8(scope, self.as_bytes(), NewStringType::Normal)
339          .ok_or(FastStringV8AllocationError)
340      }
341    }
342  }
343
344  /// Truncates a [`FastString`] value, possibly re-allocating or memcpy'ing. May be slow.
345  pub fn truncate(&mut self, index: usize) {
346    match &mut self.inner {
347      FastStringInner::Static(b) => {
348        self.inner = FastStringInner::Static(&b[..index])
349      }
350      FastStringInner::StaticAscii(b) => {
351        self.inner = FastStringInner::StaticAscii(&b[..index])
352      }
353      FastStringInner::StaticConst(b) => {
354        self.inner = FastStringInner::StaticAscii(&b.as_str()[..index])
355      }
356      // TODO(mmastrac): this could be more efficient
357      FastStringInner::Owned(b) => {
358        self.inner = FastStringInner::Owned(b[..index].to_owned().into())
359      }
360      // We can't do much if we have an Arc<str>, so we'll just take ownership of the truncated version
361      FastStringInner::Arc(s) => {
362        self.inner = FastStringInner::Arc(s[..index].to_owned().into())
363      }
364    }
365  }
366}
367
368impl Hash for FastString {
369  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
370    self.as_str().hash(state)
371  }
372}
373
374impl AsRef<str> for FastString {
375  fn as_ref(&self) -> &str {
376    self.as_str()
377  }
378}
379
380impl AsRef<[u8]> for FastString {
381  fn as_ref(&self) -> &[u8] {
382    self.as_str().as_ref()
383  }
384}
385
386impl AsRef<OsStr> for FastString {
387  fn as_ref(&self) -> &OsStr {
388    self.as_str().as_ref()
389  }
390}
391
392impl Deref for FastString {
393  type Target = str;
394  fn deref(&self) -> &Self::Target {
395    self.as_str()
396  }
397}
398
399impl Borrow<str> for FastString {
400  fn borrow(&self) -> &str {
401    self.as_str()
402  }
403}
404
405impl Debug for FastString {
406  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
407    Debug::fmt(self.as_str(), f)
408  }
409}
410
411impl Default for FastString {
412  fn default() -> Self {
413    Self {
414      inner: FastStringInner::StaticConst(FastStaticString::default()),
415    }
416  }
417}
418
419impl PartialEq for FastString {
420  fn eq(&self, other: &Self) -> bool {
421    self.as_bytes() == other.as_bytes()
422  }
423}
424
425impl Eq for FastString {}
426
427impl Display for FastString {
428  fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
429    f.write_str(self.as_str())
430  }
431}
432
433/// [`FastString`] can be made cheaply from [`Url`] as we know it's owned and don't need to do an
434/// ASCII check.
435impl From<FastStaticString> for FastString {
436  fn from(value: FastStaticString) -> Self {
437    Self {
438      inner: FastStringInner::StaticConst(value),
439    }
440  }
441}
442
443/// [`FastString`] can be made cheaply from [`Url`] as we know it's owned and don't need to do an
444/// ASCII check.
445impl From<Url> for FastString {
446  fn from(value: Url) -> Self {
447    let s: String = value.into();
448    s.into()
449  }
450}
451
452/// [`FastString`] can be made cheaply from [`String`] as we know it's owned and don't need to do an
453/// ASCII check.
454impl From<String> for FastString {
455  fn from(value: String) -> Self {
456    Self {
457      inner: FastStringInner::Owned(value.into_boxed_str()),
458    }
459  }
460}
461
462/// [`FastString`] can be made cheaply from [`Arc<str>`] as we know it's shared and don't need to do an
463/// ASCII check.
464impl From<Arc<str>> for FastString {
465  fn from(value: Arc<str>) -> Self {
466    Self {
467      inner: FastStringInner::Arc(value),
468    }
469  }
470}
471
472impl From<FastString> for Arc<str> {
473  fn from(value: FastString) -> Self {
474    use FastStringInner::*;
475    match value.inner {
476      Static(text) | StaticAscii(text) => text.into(),
477      StaticConst(text) => text.as_ref().into(),
478      Owned(text) => text.into(),
479      Arc(text) => text,
480    }
481  }
482}
483
484impl<'s> ToV8<'s> for FastString {
485  type Error = FastStringV8AllocationError;
486
487  #[inline]
488  fn to_v8<'i>(
489    self,
490    scope: &mut v8::PinScope<'s, 'i>,
491  ) -> Result<v8::Local<'s, v8::Value>, Self::Error> {
492    Ok(self.v8_string(scope)?.into())
493  }
494}
495
496impl serde::Serialize for FastString {
497  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
498  where
499    S: Serializer,
500  {
501    serializer.serialize_str(self.as_str())
502  }
503}
504
505type DeserializeProxy<'de> = &'de str;
506
507impl<'de> serde::Deserialize<'de> for FastString {
508  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
509  where
510    D: Deserializer<'de>,
511  {
512    DeserializeProxy::<'de>::deserialize(deserializer)
513      .map(|v| v.to_owned().into())
514  }
515}
516
517/// Include a fast string in the binary. This string is asserted at compile-time to be 7-bit ASCII for optimal
518/// v8 performance.
519///
520/// This macro creates a [`FastStaticString`] that may be converted to a [`FastString`] via [`Into::into`].
521#[macro_export]
522macro_rules! ascii_str_include {
523  ($file:expr_2021) => {{
524    const STR: $crate::v8::OneByteConst =
525      $crate::FastStaticString::create_external_onebyte_const(
526        ::std::include_str!($file).as_bytes(),
527      );
528    let s: &'static $crate::v8::OneByteConst = &STR;
529    $crate::FastStaticString::new(s)
530  }};
531}
532
533/// Include a fast string in the binary from a string literal. This string is asserted at compile-time to be
534/// 7-bit ASCII for optimal v8 performance.
535///
536/// This macro creates a [`FastStaticString`] that may be converted to a [`FastString`] via [`Into::into`].
537#[macro_export]
538macro_rules! ascii_str {
539  ($str:expr_2021) => {{
540    const C: $crate::v8::OneByteConst =
541      $crate::FastStaticString::create_external_onebyte_const($str.as_bytes());
542    $crate::FastStaticString::new(&C)
543  }};
544}
545
546/// Used to generate the fast, const versions of op names. Internal only.
547#[macro_export]
548#[doc(hidden)]
549macro_rules! __op_name_fast {
550  ($op:ident) => {{
551    const LITERAL: &'static [u8] = stringify!($op).as_bytes();
552    const STR: $crate::v8::OneByteConst =
553      $crate::FastStaticString::create_external_onebyte_const(LITERAL);
554    let s: &'static $crate::v8::OneByteConst = &STR;
555    (stringify!($op), $crate::FastStaticString::new(s))
556  }};
557}
558
559#[cfg(test)]
560mod tests {
561  use super::*;
562
563  #[test]
564  fn string_eq() {
565    let s: FastString = ascii_str!("Testing").into();
566    assert_eq!("Testing", s.as_str());
567    let s2 = FastString::from_static("Testing");
568    assert_eq!(s, s2);
569    let (s1, s2) = s.into_cheap_copy();
570    assert_eq!("Testing", s1.as_str());
571    assert_eq!("Testing", s2.as_str());
572
573    let s = FastString::from("Testing".to_owned());
574    assert_eq!("Testing", s.as_str());
575    let (s1, s2) = s.into_cheap_copy();
576    assert_eq!("Testing", s1.as_str());
577    assert_eq!("Testing", s2.as_str());
578  }
579
580  #[test]
581  fn truncate() {
582    let mut s = "123456".to_owned();
583    s.truncate(3);
584
585    let mut code: FastString = ascii_str!("123456").into();
586    code.truncate(3);
587    assert_eq!(s, code.as_str());
588
589    let mut code: FastString = "123456".to_owned().into();
590    code.truncate(3);
591    assert_eq!(s, code.as_str());
592
593    let arc_str: Arc<str> = "123456".into();
594    let mut code: FastString = arc_str.into();
595    code.truncate(3);
596    assert_eq!(s, code.as_str());
597  }
598
599  #[test]
600  fn test_large_include() {
601    // This test would require an excessively large file in the repo, so we just run this manually
602    // ascii_str_include!("runtime/tests/large_string.txt");
603    // ascii_str_include!(concat!("runtime", "/tests/", "large_string.txt"));
604  }
605
606  /// Ensure that all of our macros compile properly in a static context.
607  #[test]
608  fn test_const() {
609    const _: (&str, FastStaticString) = __op_name_fast!(op_name);
610    const _: FastStaticString = ascii_str!("hmm");
611    const _: FastStaticString = ascii_str!(concat!("hmm", "hmmmmm"));
612    const _: FastStaticString = ascii_str_include!("Cargo.toml");
613    const _: FastStaticString = ascii_str_include!(concat!("./", "Cargo.toml"));
614  }
615}