-
-
Notifications
You must be signed in to change notification settings - Fork 616
Expand file tree
/
Copy pathlib.rs
More file actions
1070 lines (954 loc) · 34 KB
/
lib.rs
File metadata and controls
1070 lines (954 loc) · 34 KB
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
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! A Latin1 or UTF-16 encoded, reference counted, immutable string.
// Required per unsafe code standards to ensure every unsafe usage is properly documented.
// - `unsafe_op_in_unsafe_fn` will be warn-by-default in edition 2024:
// https://github.com/rust-lang/rust/issues/71668#issuecomment-1189396860
// - `undocumented_unsafe_blocks` and `missing_safety_doc` requires a `Safety:` section in the
// comment or doc of the unsafe block or function, respectively.
#![deny(
unsafe_op_in_unsafe_fn,
clippy::undocumented_unsafe_blocks,
clippy::missing_safety_doc
)]
#![allow(clippy::module_name_repetitions)]
mod builder;
mod code_point;
mod common;
mod display;
mod iter;
mod str;
mod r#type;
mod vtable;
#[cfg(test)]
mod tests;
use self::iter::Windows;
use crate::display::{JsStrDisplayEscaped, JsStrDisplayLossy, JsStringDebugInfo};
use crate::iter::CodePointsIter;
use crate::r#type::{Latin1, Utf16};
pub use crate::vtable::StaticString;
use crate::vtable::{SequenceString, SliceString};
#[doc(inline)]
pub use crate::{
builder::{CommonJsStringBuilder, Latin1JsStringBuilder, Utf16JsStringBuilder},
code_point::CodePoint,
common::StaticJsStrings,
iter::Iter,
str::{JsStr, JsStrVariant},
};
use std::marker::PhantomData;
use std::{borrow::Cow, mem::ManuallyDrop};
use std::{
convert::Infallible,
hash::{Hash, Hasher},
ptr::{self, NonNull},
str::FromStr,
};
use vtable::JsStringVTable;
/// Maximum string length allowed (`u32::MAX`).
/// This prevents OOM crashes from exponential string growth during concatenation.
pub const MAX_STRING_LENGTH: usize = u32::MAX as usize;
fn alloc_overflow() -> ! {
panic!("detected overflow during string allocation")
}
/// Helper function to check if a `char` is trimmable.
pub(crate) const fn is_trimmable_whitespace(c: char) -> bool {
// The rust implementation of `trim` does not regard the same characters whitespace as
// ecma standard does.
//
// Rust uses \p{White_Space} by default, which also includes:
// `\u{0085}' (next line)
// And does not include:
// '\u{FEFF}' (zero width non-breaking space)
// Explicit whitespace: https://tc39.es/ecma262/#sec-white-space
matches!(
c,
'\u{0009}' | '\u{000B}' | '\u{000C}' | '\u{0020}' | '\u{00A0}' | '\u{FEFF}' |
// Unicode Space_Separator category
'\u{1680}' | '\u{2000}'
..='\u{200A}' | '\u{202F}' | '\u{205F}' | '\u{3000}' |
// Line terminators: https://tc39.es/ecma262/#sec-line-terminators
'\u{000A}' | '\u{000D}' | '\u{2028}' | '\u{2029}'
)
}
/// Helper function to check if a `u8` latin1 character is trimmable.
pub(crate) const fn is_trimmable_whitespace_latin1(c: u8) -> bool {
// The rust implementation of `trim` does not regard the same characters whitespace as
// ecma standard does.
//
// Rust uses \p{White_Space} by default, which also includes:
// `\u{0085}' (next line)
// And does not include:
// '\u{FEFF}' (zero width non-breaking space)
// Explicit whitespace: https://tc39.es/ecma262/#sec-white-space
matches!(
c,
0x09 | 0x0B | 0x0C | 0x20 | 0xA0 |
// Line terminators: https://tc39.es/ecma262/#sec-line-terminators
0x0A | 0x0D
)
}
/// Opaque type of a raw string pointer.
#[allow(missing_copy_implementations, missing_debug_implementations)]
pub struct RawJsString {
// Make this non-send, non-sync, invariant and unconstructable.
phantom_data: PhantomData<*mut ()>,
}
/// Strings can be represented internally by multiple kinds. This is used to identify
/// the storage kind of string.
#[derive(Debug, Clone, Copy, Eq, PartialEq)]
#[repr(u8)]
pub(crate) enum JsStringKind {
/// A sequential memory slice of Latin1 bytes. See [`SequenceString`].
Latin1Sequence = 0,
/// A sequential memory slice of UTF-16 code units. See [`SequenceString`].
Utf16Sequence = 1,
/// A slice of an existing string. See [`SliceString`].
Slice = 2,
/// A static string that is valid for `'static` lifetime.
Static = 3,
}
/// A Latin1 or UTF-16–encoded, reference counted, immutable string.
///
/// This is pretty similar to a <code>[Rc][std::rc::Rc]\<[\[u16\]][slice]\></code>, but without the
/// length metadata associated with the `Rc` fat pointer. Instead, the length of every string is
/// stored on the heap, along with its reference counter and its data.
///
/// The string can be latin1 (stored as a byte for space efficiency) or U16 encoding.
///
/// We define some commonly used string constants in an interner. For these strings, we don't allocate
/// memory on the heap to reduce the overhead of memory allocation and reference counting.
///
/// # Internal representation
///
/// The `ptr` field always points to a structure whose first field is a `JsStringVTable`.
/// This enables uniform vtable dispatch for all string operations without branching.
///
/// Because we ensure this invariant at every construction, we can directly point to this
/// type to allow for better optimization (and simpler code).
#[allow(clippy::module_name_repetitions)]
pub struct JsString {
/// Pointer to the string data. Always points to a struct whose first field is
/// `JsStringVTable`.
ptr: NonNull<JsStringVTable>,
}
// `JsString` should always be thin-pointer sized.
static_assertions::assert_eq_size!(JsString, *const ());
impl<'a> From<&'a JsString> for JsStr<'a> {
#[inline]
fn from(value: &'a JsString) -> Self {
value.as_str()
}
}
impl<'a> IntoIterator for &'a JsString {
type Item = u16;
type IntoIter = Iter<'a>;
#[inline]
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
impl JsString {
/// Create an iterator over the [`JsString`].
#[inline]
#[must_use]
pub fn iter(&self) -> Iter<'_> {
self.as_str().iter()
}
/// Create an iterator over overlapping subslices of length size.
#[inline]
#[must_use]
pub fn windows(&self, size: usize) -> Windows<'_> {
self.as_str().windows(size)
}
/// Decodes a [`JsString`] into a [`String`], replacing invalid data with its escaped representation
/// in 4 digit hexadecimal.
#[inline]
#[must_use]
pub fn to_std_string_escaped(&self) -> String {
self.display_escaped().to_string()
}
/// Decodes a [`JsString`] into a [`String`], replacing invalid data with the
/// replacement character U+FFFD.
#[inline]
#[must_use]
pub fn to_std_string_lossy(&self) -> String {
self.display_lossy().to_string()
}
/// Decodes a [`JsString`] into a [`String`], returning an error if the string contains unpaired
/// surrogates.
///
/// # Errors
///
/// [`FromUtf16Error`][std::string::FromUtf16Error] if it contains any invalid data.
#[inline]
pub fn to_std_string(&self) -> Result<String, std::string::FromUtf16Error> {
self.as_str().to_std_string()
}
/// Decodes a [`JsString`] into an iterator of [`Result<String, u16>`], returning surrogates as
/// errors.
#[inline]
#[allow(clippy::missing_panics_doc)]
pub fn to_std_string_with_surrogates(
&self,
) -> impl Iterator<Item = Result<String, u16>> + use<'_> {
let mut iter = self.code_points().peekable();
std::iter::from_fn(move || {
let cp = iter.next()?;
let char = match cp {
CodePoint::Unicode(c) => c,
CodePoint::UnpairedSurrogate(surr) => return Some(Err(surr)),
};
let mut string = String::from(char);
loop {
let Some(cp) = iter.peek().and_then(|cp| match cp {
CodePoint::Unicode(c) => Some(*c),
CodePoint::UnpairedSurrogate(_) => None,
}) else {
break;
};
string.push(cp);
iter.next().expect("should exist by the check above");
}
Some(Ok(string))
})
}
/// Maps the valid segments of an UTF16 string and leaves the unpaired surrogates unchanged.
#[inline]
#[must_use]
pub fn map_valid_segments<F>(&self, mut f: F) -> Self
where
F: FnMut(String) -> String,
{
let mut text = Vec::new();
for part in self.to_std_string_with_surrogates() {
match part {
Ok(string) => text.extend(f(string).encode_utf16()),
Err(surr) => text.push(surr),
}
}
Self::from(&text[..])
}
/// Gets an iterator of all the Unicode codepoints of a [`JsString`].
#[inline]
#[must_use]
pub fn code_points(&self) -> CodePointsIter<'_> {
(self.vtable().code_points)(self.ptr)
}
/// Get the variant of this string.
#[inline]
#[must_use]
pub fn variant(&self) -> JsStrVariant<'_> {
self.as_str().variant()
}
/// Abstract operation `StringIndexOf ( string, searchValue, fromIndex )`
///
/// Note: Instead of returning an isize with `-1` as the "not found" value, we make use of the
/// type system and return <code>[Option]\<usize\></code> with [`None`] as the "not found" value.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-stringindexof
#[inline]
#[must_use]
pub fn index_of(&self, search_value: JsStr<'_>, from_index: usize) -> Option<usize> {
self.as_str().index_of(search_value, from_index)
}
/// Abstract operation `CodePointAt( string, position )`.
///
/// The abstract operation `CodePointAt` takes arguments `string` (a String) and `position` (a
/// non-negative integer) and returns a Record with fields `[[CodePoint]]` (a code point),
/// `[[CodeUnitCount]]` (a positive integer), and `[[IsUnpairedSurrogate]]` (a Boolean). It
/// interprets string as a sequence of UTF-16 encoded code points, as described in 6.1.4, and reads
/// from it a single code point starting with the code unit at index `position`.
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-codepointat
///
/// # Panics
///
/// If `position` is smaller than size of string.
#[inline]
#[must_use]
pub fn code_point_at(&self, position: usize) -> CodePoint {
self.as_str().code_point_at(position)
}
/// Abstract operation `StringToNumber ( str )`
///
/// More information:
/// - [ECMAScript reference][spec]
///
/// [spec]: https://tc39.es/ecma262/#sec-stringtonumber
#[inline]
#[must_use]
pub fn to_number(&self) -> f64 {
self.as_str().to_number()
}
/// Get the length of the [`JsString`].
#[inline]
#[must_use]
pub fn len(&self) -> usize {
self.vtable().len
}
/// Return true if the [`JsString`] is empty.
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
self.len() == 0
}
/// Convert the [`JsString`] into a [`Vec<U16>`].
#[inline]
#[must_use]
pub fn to_vec(&self) -> Vec<u16> {
self.as_str().to_vec()
}
/// Check if the [`JsString`] contains a byte.
#[inline]
#[must_use]
pub fn contains(&self, element: u8) -> bool {
self.as_str().contains(element)
}
/// Trim whitespace from the start and end of the [`JsString`].
#[inline]
#[must_use]
pub fn trim(&self) -> JsString {
// Calculate both bounds directly to avoid intermediate allocations.
let (start, end) = match self.variant() {
JsStrVariant::Latin1(v) => {
let Some(start) = v.iter().position(|c| !is_trimmable_whitespace_latin1(*c)) else {
return StaticJsStrings::EMPTY_STRING;
};
let end = v
.iter()
.rposition(|c| !is_trimmable_whitespace_latin1(*c))
.unwrap_or(start);
(start, end)
}
JsStrVariant::Utf16(v) => {
let Some(start) = v.iter().copied().position(|r| {
!char::from_u32(u32::from(r)).is_some_and(is_trimmable_whitespace)
}) else {
return StaticJsStrings::EMPTY_STRING;
};
let end = v
.iter()
.copied()
.rposition(|r| {
!char::from_u32(u32::from(r)).is_some_and(is_trimmable_whitespace)
})
.unwrap_or(start);
(start, end)
}
};
// SAFETY: `position(...)` and `rposition(...)` cannot exceed the length of the string.
unsafe { Self::slice_unchecked(self, start, end + 1) }
}
/// Trim whitespace from the start of the [`JsString`].
#[inline]
#[must_use]
pub fn trim_start(&self) -> JsString {
let Some(start) = (match self.variant() {
JsStrVariant::Latin1(v) => v.iter().position(|c| !is_trimmable_whitespace_latin1(*c)),
JsStrVariant::Utf16(v) => v
.iter()
.copied()
.position(|r| !char::from_u32(u32::from(r)).is_some_and(is_trimmable_whitespace)),
}) else {
return StaticJsStrings::EMPTY_STRING;
};
// SAFETY: `position(...)` cannot exceed the length of the string.
unsafe { Self::slice_unchecked(self, start, self.len()) }
}
/// Trim whitespace from the end of the [`JsString`].
#[inline]
#[must_use]
pub fn trim_end(&self) -> JsString {
let Some(end) = (match self.variant() {
JsStrVariant::Latin1(v) => v.iter().rposition(|c| !is_trimmable_whitespace_latin1(*c)),
JsStrVariant::Utf16(v) => v
.iter()
.copied()
.rposition(|r| !char::from_u32(u32::from(r)).is_some_and(is_trimmable_whitespace)),
}) else {
return StaticJsStrings::EMPTY_STRING;
};
// SAFETY: `rposition(...)` cannot exceed the length of the string. `end` is the first
// character that is not trimmable, therefore we need to add 1 to it.
unsafe { Self::slice_unchecked(self, 0, end + 1) }
}
/// Returns true if needle is a prefix of the [`JsStr`].
#[inline]
#[must_use]
// We check the size, so this should never panic.
#[allow(clippy::missing_panics_doc)]
pub fn starts_with(&self, needle: JsStr<'_>) -> bool {
self.as_str().starts_with(needle)
}
/// Returns `true` if `needle` is a suffix of the [`JsStr`].
#[inline]
#[must_use]
// We check the size, so this should never panic.
#[allow(clippy::missing_panics_doc)]
pub fn ends_with(&self, needle: JsStr<'_>) -> bool {
self.as_str().starts_with(needle)
}
/// Get the `u16` code unit at index. This does not parse any characters if there
/// are pairs, it is simply the index of the `u16` elements.
#[inline]
#[must_use]
pub fn code_unit_at(&self, index: usize) -> Option<u16> {
self.as_str().get(index)
}
/// Get the element at the given index, or [`None`] if the index is out of range.
#[inline]
#[must_use]
pub fn get<I>(&self, index: I) -> Option<JsString>
where
I: JsStringSliceIndex,
{
index.get(self)
}
/// Get the element at the given index, or panic.
///
/// # Panics
/// If the index returns `None`, this will panic.
#[inline]
#[must_use]
pub fn get_expect<I>(&self, index: I) -> JsString
where
I: JsStringSliceIndex,
{
index.get(self).expect("Unexpected get()")
}
/// Gets a displayable escaped string. This may be faster and has fewer
/// allocations than `format!("{}", str.to_string_escaped())` when
/// displaying.
#[inline]
#[must_use]
pub fn display_escaped(&self) -> JsStrDisplayEscaped<'_> {
JsStrDisplayEscaped::from(self)
}
/// Gets a displayable lossy string. This may be faster and has fewer
/// allocations than `format!("{}", str.to_string_lossy())` when displaying.
#[inline]
#[must_use]
pub fn display_lossy(&self) -> JsStrDisplayLossy<'_> {
self.as_str().display_lossy()
}
/// Get a debug displayable info and metadata for this string.
#[inline]
#[must_use]
pub fn debug_info(&self) -> JsStringDebugInfo<'_> {
self.into()
}
/// Consumes the [`JsString`], returning the internal pointer.
///
/// To avoid a memory leak the pointer must be converted back to a `JsString` using
/// [`JsString::from_raw`].
#[inline]
#[must_use]
pub fn into_raw(self) -> NonNull<RawJsString> {
ManuallyDrop::new(self).ptr.cast()
}
/// Constructs a `JsString` from the internal pointer.
///
/// The raw pointer must have been previously returned by a call to
/// [`JsString::into_raw`].
///
/// # Safety
///
/// This function is unsafe because improper use may lead to memory unsafety,
/// even if the returned `JsString` is never accessed.
#[inline]
#[must_use]
pub const unsafe fn from_raw(ptr: NonNull<RawJsString>) -> Self {
Self { ptr: ptr.cast() }
}
/// Constructs a `JsString` from a reference to a `VTable`.
///
/// # Safety
///
/// This function is unsafe because improper use may lead to memory unsafety,
/// even if the returned `JsString` is never accessed.
#[inline]
#[must_use]
pub(crate) const unsafe fn from_ptr(ptr: NonNull<JsStringVTable>) -> Self {
Self { ptr }
}
}
// `&JsStr<'static>` must always be aligned so it can be tagged.
static_assertions::const_assert!(align_of::<*const JsStr<'static>>() >= 2);
/// Dealing with inner types.
impl JsString {
/// Check if this is a static string.
#[inline]
#[must_use]
pub fn is_static(&self) -> bool {
// Check the vtable kind tag
self.vtable().kind == JsStringKind::Static
}
/// Get the vtable for this string.
#[inline]
#[must_use]
const fn vtable(&self) -> &JsStringVTable {
// SAFETY: All JsString variants have vtable as the first field (embedded directly).
unsafe { self.ptr.as_ref() }
}
/// Create a [`JsString`] from a [`StaticString`] instance. This is assumed that the
/// static string referenced is available for the duration of the `JsString` instance
/// returned.
#[inline]
#[must_use]
pub const fn from_static(str: &'static StaticString) -> Self {
Self {
ptr: NonNull::from_ref(str).cast(),
}
}
/// Create a [`JsString`] from an existing `JsString` and start, end
/// range. `end` is 1 past the last character (or `== data.len()`
/// for the last character).
///
/// # Safety
/// It is the responsibility of the caller to ensure:
/// - `start` <= `end`. If `start` == `end`, the string is empty.
/// - `end` <= `data.len()`.
#[inline]
#[must_use]
pub unsafe fn slice_unchecked(data: &JsString, start: usize, end: usize) -> Self {
// Safety: invariant stated by this whole function.
let slice = Box::new(unsafe { SliceString::new(data, start, end) });
Self {
ptr: NonNull::from(Box::leak(slice)).cast(),
}
}
/// Create a [`JsString`] from an existing `JsString` and start, end
/// range. Returns None if the start/end is invalid.
#[inline]
#[must_use]
pub fn slice(&self, p1: usize, mut p2: usize) -> JsString {
if p2 > self.len() {
p2 = self.len();
}
if p1 >= p2 {
StaticJsStrings::EMPTY_STRING
} else {
// SAFETY: We just checked the conditions.
unsafe { Self::slice_unchecked(self, p1, p2) }
}
}
/// Get the kind of this string (for debugging/introspection).
#[inline]
#[must_use]
pub(crate) fn kind(&self) -> JsStringKind {
self.vtable().kind
}
/// Get the inner pointer as a reference of type T.
///
/// # Safety
/// This should only be used when the inner type has been validated via `kind()`.
/// Using an unvalidated inner type is undefined behaviour.
#[inline]
pub(crate) unsafe fn as_inner<T>(&self) -> &T {
// SAFETY: Caller must ensure the type matches.
unsafe { self.ptr.cast::<T>().as_ref() }
}
}
impl JsString {
/// Obtains the underlying [`&[u16]`][slice] slice of a [`JsString`]
#[inline]
#[must_use]
pub fn as_str(&self) -> JsStr<'_> {
(self.vtable().as_str)(self.ptr)
}
/// Creates a new [`JsString`] from the concatenation of `x` and `y`.
///
/// # Errors
///
/// Returns an error if the resulting string would exceed [`MAX_STRING_LENGTH`].
#[inline]
pub fn concat(x: JsStr<'_>, y: JsStr<'_>) -> Result<Self, &'static str> {
Self::concat_array(&[x, y])
}
/// Creates a new [`JsString`] from the concatenation of every element of
/// `strings`.
///
/// # Errors
///
/// Returns an error if the resulting string would exceed [`MAX_STRING_LENGTH`].
#[inline]
pub fn concat_array(strings: &[JsStr<'_>]) -> Result<Self, &'static str> {
let mut latin1_encoding = true;
let mut full_count = 0usize;
for string in strings {
let Some(sum) = full_count.checked_add(string.len()) else {
return Err("Invalid string length");
};
// Check if the resulting string would exceed the maximum length
if sum > MAX_STRING_LENGTH {
return Err("Invalid string length");
}
if !string.is_latin1() {
latin1_encoding = false;
}
full_count = sum;
}
// For UTF-16 strings, also check that the byte count doesn't overflow usize
// (each character is 2 bytes). This is important for 32-bit systems.
if !latin1_encoding && full_count.checked_mul(2).is_none() {
return Err("Invalid string length");
}
let (ptr, data_offset) = if latin1_encoding {
let p = SequenceString::<Latin1>::allocate(full_count);
(p.cast::<u8>(), size_of::<SequenceString<Latin1>>())
} else {
let p = SequenceString::<Utf16>::allocate(full_count);
(p.cast::<u8>(), size_of::<SequenceString<Utf16>>())
};
let string = {
// SAFETY: `allocate_*_seq` guarantees that `ptr` is a valid pointer to a sequence string.
let mut data = unsafe {
let seq_ptr = ptr.as_ptr();
seq_ptr.add(data_offset)
};
for &string in strings {
// SAFETY:
// The sum of all `count` for each `string` equals `full_count`, and since we're
// iteratively writing each of them to `data`, `copy_non_overlapping` always stays
// in-bounds for `count` reads of each string and `full_count` writes to `data`.
//
// Each `string` must be properly aligned to be a valid slice, and `data` must be
// properly aligned by `allocate_seq`.
//
// `allocate_seq` must return a valid pointer to newly allocated memory, meaning
// `ptr` and all `string`s should never overlap.
unsafe {
// NOTE: The alignment is checked when we allocate the array.
#[allow(clippy::cast_ptr_alignment)]
match (latin1_encoding, string.variant()) {
(true, JsStrVariant::Latin1(s)) => {
let count = s.len();
ptr::copy_nonoverlapping(s.as_ptr(), data.cast::<u8>(), count);
data = data.cast::<u8>().add(count).cast::<u8>();
}
(false, JsStrVariant::Latin1(s)) => {
let count = s.len();
for (i, byte) in s.iter().enumerate() {
*data.cast::<u16>().add(i) = u16::from(*byte);
}
data = data.cast::<u16>().add(count).cast::<u8>();
}
(false, JsStrVariant::Utf16(s)) => {
let count = s.len();
ptr::copy_nonoverlapping(s.as_ptr(), data.cast::<u16>(), count);
data = data.cast::<u16>().add(count).cast::<u8>();
}
(true, JsStrVariant::Utf16(_)) => {
unreachable!("Already checked that it's latin1 encoding")
}
}
}
}
Self { ptr: ptr.cast() }
};
Ok(StaticJsStrings::get_string(&string.as_str()).unwrap_or(string))
}
/// Creates a new [`JsString`] from `data`, without checking if the string is in the interner.
fn from_slice_skip_interning(string: JsStr<'_>) -> Self {
let count = string.len();
// SAFETY:
// - We read `count = data.len()` elements from `data`, which is within the bounds of the slice.
// - `allocate_*_seq` must allocate at least `count` elements, which allows us to safely
// write at least `count` elements.
// - `allocate_*_seq` should already take care of the alignment of `ptr`, and `data` must be
// aligned to be a valid slice.
// - `allocate_*_seq` must return a valid pointer to newly allocated memory, meaning `ptr`
// and `data` should never overlap.
unsafe {
// NOTE: The alignment is checked when we allocate the array.
#[allow(clippy::cast_ptr_alignment)]
match string.variant() {
JsStrVariant::Latin1(s) => {
let ptr = SequenceString::<Latin1>::allocate(count);
let data = (&raw mut (*ptr.as_ptr()).data)
.cast::<<Latin1 as r#type::StringType>::Byte>();
ptr::copy_nonoverlapping(s.as_ptr(), data, count);
Self { ptr: ptr.cast() }
}
JsStrVariant::Utf16(s) => {
let ptr = SequenceString::<Utf16>::allocate(count);
let data = (&raw mut (*ptr.as_ptr()).data)
.cast::<<Utf16 as r#type::StringType>::Byte>();
ptr::copy_nonoverlapping(s.as_ptr(), data, count);
Self { ptr: ptr.cast() }
}
}
}
}
/// Creates a new [`JsString`] from `data`.
fn from_js_str(string: JsStr<'_>) -> Self {
if let Some(s) = StaticJsStrings::get_string(&string) {
return s;
}
Self::from_slice_skip_interning(string)
}
/// Gets the number of `JsString`s which point to this allocation.
#[inline]
#[must_use]
pub fn refcount(&self) -> Option<usize> {
(self.vtable().refcount)(self.ptr)
}
}
impl Clone for JsString {
#[inline]
fn clone(&self) -> Self {
(self.vtable().clone)(self.ptr)
}
}
impl Default for JsString {
#[inline]
fn default() -> Self {
StaticJsStrings::EMPTY_STRING
}
}
impl Drop for JsString {
#[inline]
fn drop(&mut self) {
(self.vtable().drop)(self.ptr);
}
}
impl std::fmt::Debug for JsString {
#[inline]
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_tuple("JsString")
.field(&self.display_escaped().to_string())
.finish()
}
}
impl Eq for JsString {}
macro_rules! impl_from_number_for_js_string {
($($module: ident => $($ty:ty),+)+) => {
$(
$(
impl From<$ty> for JsString {
#[inline]
fn from(value: $ty) -> Self {
JsString::from_slice_skip_interning(JsStr::latin1(
$module::Buffer::new().format(value).as_bytes(),
))
}
}
)+
)+
};
}
impl_from_number_for_js_string!(
itoa => i8, i16, i32, i64, i128, u8, u16, u32, u64, u128, isize, usize
ryu_js => f32, f64
);
impl From<&[u16]> for JsString {
#[inline]
fn from(s: &[u16]) -> Self {
JsString::from_js_str(JsStr::utf16(s))
}
}
impl From<&str> for JsString {
#[inline]
fn from(s: &str) -> Self {
if s.is_ascii() {
let js_str = JsStr::latin1(s.as_bytes());
return StaticJsStrings::get_string(&js_str)
.unwrap_or_else(|| JsString::from_slice_skip_interning(js_str));
}
// Non-ASCII but still Latin1-encodable (U+0080..=U+00FF): chars map 1-to-1 to u8.
if s.chars().all(|c| c as u32 <= 0xFF) {
let bytes: Vec<u8> = s.chars().map(|c| c as u8).collect();
let js_str = JsStr::latin1(&bytes);
return StaticJsStrings::get_string(&js_str)
.unwrap_or_else(|| JsString::from_slice_skip_interning(js_str));
}
let s = s.encode_utf16().collect::<Vec<_>>();
JsString::from_slice_skip_interning(JsStr::utf16(&s[..]))
}
}
impl From<JsStr<'_>> for JsString {
#[inline]
fn from(value: JsStr<'_>) -> Self {
StaticJsStrings::get_string(&value)
.unwrap_or_else(|| JsString::from_slice_skip_interning(value))
}
}
impl From<&[JsString]> for JsString {
#[inline]
fn from(value: &[JsString]) -> Self {
Self::concat_array(&value.iter().map(Self::as_str).collect::<Vec<_>>()[..])
.expect("string concatenation overflow")
}
}
impl<const N: usize> From<&[JsString; N]> for JsString {
#[inline]
fn from(value: &[JsString; N]) -> Self {
Self::concat_array(&value.iter().map(Self::as_str).collect::<Vec<_>>()[..])
.expect("string concatenation overflow")
}
}
impl From<String> for JsString {
#[inline]
fn from(s: String) -> Self {
Self::from(s.as_str())
}
}
impl<'a> From<Cow<'a, str>> for JsString {
#[inline]
fn from(s: Cow<'a, str>) -> Self {
match s {
Cow::Borrowed(s) => s.into(),
Cow::Owned(s) => s.into(),
}
}
}
impl<const N: usize> From<&[u16; N]> for JsString {
#[inline]
fn from(s: &[u16; N]) -> Self {
Self::from(&s[..])
}
}
impl Hash for JsString {
#[inline]
fn hash<H: Hasher>(&self, state: &mut H) {
self.as_str().hash(state);
}
}
impl PartialOrd for JsStr<'_> {
#[inline]
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for JsString {
#[inline]
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.as_str().cmp(&other.as_str())
}
}
impl PartialEq for JsString {
#[inline]
fn eq(&self, other: &Self) -> bool {
self.as_str() == other.as_str()
}
}
impl PartialEq<JsString> for [u16] {
#[inline]
fn eq(&self, other: &JsString) -> bool {
if self.len() != other.len() {
return false;
}
for (x, y) in self.iter().copied().zip(other.iter()) {
if x != y {
return false;
}
}
true
}
}
impl<const N: usize> PartialEq<JsString> for [u16; N] {
#[inline]
fn eq(&self, other: &JsString) -> bool {
self[..] == *other
}
}
impl PartialEq<[u16]> for JsString {
#[inline]
fn eq(&self, other: &[u16]) -> bool {
other == self
}
}
impl<const N: usize> PartialEq<[u16; N]> for JsString {
#[inline]
fn eq(&self, other: &[u16; N]) -> bool {
*self == other[..]
}
}
impl PartialEq<str> for JsString {
#[inline]
fn eq(&self, other: &str) -> bool {
self.as_str() == other
}
}
impl PartialEq<&str> for JsString {
#[inline]
fn eq(&self, other: &&str) -> bool {
self.as_str() == *other
}
}
impl PartialEq<JsString> for str {
#[inline]
fn eq(&self, other: &JsString) -> bool {
other == self
}
}
impl PartialEq<JsStr<'_>> for JsString {
#[inline]
fn eq(&self, other: &JsStr<'_>) -> bool {
self.as_str() == *other