1use 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#[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 #[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 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
162pub struct FastString {
178 inner: FastStringInner,
179}
180
181enum FastStringInner {
182 Static(&'static str),
184
185 StaticAscii(&'static str),
187
188 StaticConst(FastStaticString),
190
191 Owned(Box<str>),
194
195 Arc(Arc<str>),
197}
198
199impl FastString {
200 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 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 pub fn from_non_ascii_static(s: &'static str) -> Self {
251 Self {
252 inner: FastStringInner::Static(s),
253 }
254 }
255
256 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 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 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 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 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 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 FastStringInner::Owned(b) => {
358 self.inner = FastStringInner::Owned(b[..index].to_owned().into())
359 }
360 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
433impl From<FastStaticString> for FastString {
436 fn from(value: FastStaticString) -> Self {
437 Self {
438 inner: FastStringInner::StaticConst(value),
439 }
440 }
441}
442
443impl From<Url> for FastString {
446 fn from(value: Url) -> Self {
447 let s: String = value.into();
448 s.into()
449 }
450}
451
452impl From<String> for FastString {
455 fn from(value: String) -> Self {
456 Self {
457 inner: FastStringInner::Owned(value.into_boxed_str()),
458 }
459 }
460}
461
462impl 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#[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#[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#[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 }
605
606 #[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}