js_parse/wtf8.rs
1//! The string type JavaScript actually has, in **WTF-8**.
2//!
3//! This lives *below* the parser rather than with the rest of the value types because the
4//! **lexer** has to build one: a string literal may contain a lone surrogate
5//! (`"\uD800"`), and Rust's `String` cannot hold that, so the cooked value of a literal is
6//! a [`Wtf8`]. The runtime re-exports this type, so `Value::String` holds the same type the
7//! parser produced — one representation all the way through, with no conversion step at
8//! which a surrogate could be lost.
9//!
10//! The crate is the bottom of the engine, so this module has no dependencies.
11
12use std::fmt;
13
14/// Where a [`Wtf8`]'s bytes live.
15///
16/// Two representations, because the two things a string does with its bytes want opposite
17/// layouts:
18///
19/// * An **atom** — a property name from the compiled code — is created on every property
20/// access and never grows. `Shared` copies it into one allocation and clones are a
21/// refcount bump.
22/// * A **result** — `a + b` — is built once from two slices and, for the `s += x` loop the
23/// language encourages, then grows in place. `Owned` keeps a `Vec`, so
24/// [`Wtf8::append_in_place`] reuses the buffer instead of copying the whole string per
25/// append.
26///
27/// Both are `Rc`, so `Clone` stays a refcount bump either way — that is the property the
28/// whole engine leans on (see the field comment below).
29#[derive(Clone)]
30enum Bytes {
31 /// Shared, immutable, exactly as long as its contents.
32 Shared(std::rc::Rc<[u8]>),
33 /// Owned through a `Vec`, which can grow in place while it is unshared.
34 Owned(std::rc::Rc<Vec<u8>>),
35}
36
37impl Bytes {
38 #[inline(always)]
39 fn as_slice(&self) -> &[u8] {
40 match self {
41 Bytes::Shared(bytes) => bytes,
42 Bytes::Owned(bytes) => bytes,
43 }
44 }
45
46 /// The bytes this string is holding on to, which is the buffer's *capacity* for an
47 /// owned one.
48 ///
49 /// `Vec` doubles, so a string built by 200,000 appends holds up to twice its length;
50 /// reporting only the length would let a `--memory-limit` run exceed the limit it asked
51 /// for by that factor. `Heap::adjust_payload` and this must agree exactly, because the
52 /// two are added and subtracted from the same counter.
53 fn allocated(&self) -> usize {
54 match self {
55 Bytes::Shared(bytes) => bytes.len(),
56 Bytes::Owned(bytes) => bytes.capacity(),
57 }
58 }
59}
60
61impl std::ops::Deref for Bytes {
62 type Target = [u8];
63
64 fn deref(&self) -> &[u8] {
65 self.as_slice()
66 }
67}
68
69/// A JavaScript string's bytes, in **WTF-8**.
70///
71/// A JS string is a sequence of UTF-16 *code units*, and that sequence may contain an
72/// unpaired surrogate: `String.fromCharCode(0xD800)` produces exactly one, and
73/// `"\uD800".length` is 1. Rust's `String` cannot represent that, so the bytes here are
74/// WTF-8 — ordinary UTF-8, except that a code unit with no partner is written as the
75/// three-byte sequence UTF-8 would use for U+D800..U+DFFF.
76///
77/// # The encoding is canonical, and that is load-bearing
78///
79/// A *surrogate pair* is written as the single four-byte sequence of the astral code point
80/// it spells, never as two three-byte sequences. Without that rule the bytes of `"\uD800" +
81/// "\uDC00"` would differ from the bytes of `"\u{10000}"` while the two strings are
82/// observably identical — same length, same `charCodeAt` at every index — and every
83/// equality, property key and `switch` arm in the engine would disagree with the language.
84///
85/// The canonical form makes **byte equality exactly code-unit equality**, which is what lets
86/// a property key be compared without decoding it.
87#[derive(Clone)]
88pub struct Wtf8 {
89 /// The WTF-8 bytes, shared.
90 ///
91 /// `Rc<[u8]>` rather than `Box<[u8]>` because cloning a `Wtf8` is one of the hottest
92 /// operations in the engine: every property key comparison, every atom lookup and every
93 /// `Value::String` copy did it, and with a `Box` each clone deep-copied the bytes. That
94 /// is a heap allocation plus a memcpy per property read, which is why
95 /// `property:monomorphic` was 16× slower than the reference before this.
96 ///
97 /// Being `Rc` makes `Wtf8` `!Send`, which it effectively already was: it lives behind
98 /// `Gc`, which uses a non-atomic refcount.
99 bytes: Bytes,
100 /// Whether `bytes` is valid UTF-8, meaning the string has no unpaired surrogate.
101 ///
102 /// A `Wtf8` is immutable, so this stays correct for its whole life.
103 valid: bool,
104}
105
106impl Wtf8 {
107 /// Wrap a Rust string, which is valid UTF-8 by construction.
108 pub fn new(text: impl Into<String>) -> Wtf8 {
109 Wtf8 {
110 bytes: Bytes::Owned(std::rc::Rc::new(text.into().into_bytes())),
111 valid: true,
112 }
113 }
114
115 /// Build from a `&str` without copying it.
116 ///
117 /// `Wtf8::new` takes `impl Into<String>`, which copies. A property atom is a `&str` that
118 /// already lives in the compiled code and outlives every use of the key, so sharing the
119 /// bytes is free — and this is on the path of every property access.
120 pub fn from_rc_str(text: &str) -> Wtf8 {
121 Wtf8 {
122 bytes: Bytes::Shared(std::rc::Rc::from(text.as_bytes())),
123 valid: true,
124 }
125 }
126
127 /// Build from bytes that are already WTF-8, with `valid` saying whether they contain an
128 /// unpaired surrogate.
129 ///
130 /// Used by the rope's flattening path, which has just concatenated children whose
131 /// validity it knows.
132 pub fn from_parts(bytes: Vec<u8>, valid: bool) -> Wtf8 {
133 Wtf8 {
134 bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
135 valid,
136 }
137 }
138
139 /// Whether the bytes are valid UTF-8, i.e. the string has no unpaired surrogate.
140 /// The bytes this string is holding on to — the buffer's *capacity* when it owns one.
141 ///
142 /// A `Vec` doubles, so a string built by 200,000 appends holds up to twice its length;
143 /// the heap accounting must charge for what is really allocated, not for what is used.
144 pub fn allocated_bytes(&self) -> usize {
145 self.bytes.allocated()
146 }
147
148 /// Whether the text is well-formed — no unpaired surrogate.
149 ///
150 /// The one thing the bytes alone cannot answer without decoding, so it is computed once
151 /// at construction.
152 pub fn is_valid(&self) -> bool {
153 self.valid
154 }
155
156 /// Build from code points, folding astral ones into the pair they spell.
157 ///
158 /// The inverse of [`Wtf8::code_point_values`]: a value in `0xD800..=0xDFFF` is taken to
159 /// be a lone surrogate rather than an error, because that is what a code point list from
160 /// this type can legitimately contain.
161 pub fn from_code_points(points: &[u32]) -> Wtf8 {
162 let mut units = Vec::with_capacity(points.len());
163 for &point in points {
164 if point > 0xFFFF {
165 let value = point - 0x10000;
166 units.push(0xD800 + (value >> 10) as u16);
167 units.push(0xDC00 + (value & 0x3FF) as u16);
168 } else {
169 units.push(point as u16);
170 }
171 }
172 Wtf8::from_units(&units)
173 }
174
175 /// Build from UTF-16 code units, which is the form a JS string really has.
176 ///
177 /// An unpaired surrogate survives; a pair is folded into its astral code point.
178 /// Decode WTF-8 bytes, canonicalising them.
179 ///
180 /// The strict counterpart of [`Wtf8::as_bytes`], for text that came from outside the
181 /// process: a serialised bytecode blob carries atoms and string constants as raw bytes,
182 /// and one of them may be an unpaired surrogate. `String::from_utf8` would reject it,
183 /// which is why this exists rather than `from`.
184 ///
185 /// `None` for bytes that are not WTF-8 at all — a truncated sequence, a stray
186 /// continuation byte, or an overlong encoding. The code units are then re-encoded
187 /// through [`Wtf8::from_units`], so the result is canonical even if the input wrote a
188 /// surrogate pair as two three-byte sequences.
189 pub fn from_wtf8_bytes(bytes: &[u8]) -> Option<Wtf8> {
190 let mut units: Vec<u16> = Vec::with_capacity(bytes.len());
191 let mut at = 0;
192 while at < bytes.len() {
193 let first = bytes[at];
194 // The payload bits each lead byte contributes: 7, then 5, 4 and 3. Derived from
195 // the length rather than by shifting `0x7f`, because `0x7f >> 1` is `0x3f` — off
196 // by the top bit of the payload, which silently corrupts every ASCII character.
197 let (length, payload_mask, min) = match first {
198 0x00..=0x7f => (1, 0x7f, 0),
199 0xc2..=0xdf => (2, 0x1f, 0x80),
200 0xe0..=0xef => (3, 0x0f, 0x800),
201 0xf0..=0xf4 => (4, 0x07, 0x10000),
202 // 0x80..=0xc1 (continuation bytes and overlong two-byte leads) and
203 // 0xf5..=0xff are never valid WTF-8.
204 _ => return None,
205 };
206 let end = at.checked_add(length)?;
207 if end > bytes.len() {
208 return None;
209 }
210 let mut code = u32::from(first) & payload_mask;
211 for &byte in &bytes[at + 1..end] {
212 if byte & 0xc0 != 0x80 {
213 return None;
214 }
215 code = (code << 6) | u32::from(byte & 0x3f);
216 }
217 if code < min {
218 // Overlong: the same code point has a shorter encoding, so accepting this
219 // would make two byte strings for one string.
220 return None;
221 }
222 if code > 0xffff {
223 let value = code - 0x10000;
224 units.push(0xd800 + (value >> 10) as u16);
225 units.push(0xdc00 + (value & 0x3ff) as u16);
226 } else {
227 units.push(code as u16);
228 }
229 at = end;
230 }
231 Some(Wtf8::from_units(&units))
232 }
233
234 /// Build from UTF-16 code units, which is the form a JS string really has.
235 ///
236 /// A surrogate pair is folded into the astral code point it spells, so the result is
237 /// canonical: this is where the encoding's invariant is enforced, and therefore the only
238 /// place that has to know about it.
239 pub fn from_units(units: &[u16]) -> Wtf8 {
240 let mut bytes = Vec::with_capacity(units.len());
241 let mut valid = true;
242 let mut index = 0;
243 while index < units.len() {
244 let unit = units[index];
245 match units.get(index + 1) {
246 Some(&low) if is_high(unit) && is_low(low) => {
247 push_code_point(&mut bytes, combine(unit, low));
248 index += 2;
249 }
250 _ if is_surrogate(unit) => {
251 // A lone surrogate keeps its own three-byte form, so it round-trips and
252 // still counts as one code unit.
253 valid = false;
254 push_surrogate(&mut bytes, unit);
255 index += 1;
256 }
257 _ => {
258 push_code_point(&mut bytes, unit as u32);
259 index += 1;
260 }
261 }
262 }
263 Wtf8 {
264 bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
265 valid,
266 }
267 }
268
269 /// The text, when it is valid UTF-8.
270 ///
271 /// `None` only for a string containing an unpaired surrogate — there is no `&str` for
272 /// one. Callers that only need to display or compare use [`Wtf8::to_string_lossy`].
273 pub fn as_str(&self) -> Option<&str> {
274 if self.valid {
275 // SAFETY: `valid` is only set by the encoder above, which produces valid UTF-8
276 // exactly when no surrogate was written on its own, and the bytes never change.
277 Some(unsafe { std::str::from_utf8_unchecked(self.bytes.as_slice()) })
278 } else {
279 None
280 }
281 }
282
283 /// The text with unpaired surrogates replaced by U+FFFD.
284 ///
285 /// Borrowed, and therefore free, for the ordinary string that has no surrogate.
286 pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
287 match self.as_str() {
288 Some(text) => std::borrow::Cow::Borrowed(text),
289 None => String::from_utf8_lossy(self.bytes.as_slice()),
290 }
291 }
292
293 /// The WTF-8 bytes. Two `Wtf8`s are equal exactly when these are.
294 pub fn as_bytes(&self) -> &[u8] {
295 self.bytes.as_slice()
296 }
297
298 /// The UTF-16 code units, which is what indexing and `charCodeAt` count.
299 pub fn to_units(&self) -> Vec<u16> {
300 let mut units = Vec::with_capacity(self.utf16_len());
301 self.push_units(&mut units);
302 units
303 }
304
305 /// Length in UTF-16 code units, which is what `String.prototype.length` reports.
306 ///
307 /// Counted from the encoding rather than by decoding, so it does not allocate: a
308 /// four-byte sequence is a surrogate pair and therefore two units, everything else is
309 /// one.
310 pub fn utf16_len(&self) -> usize {
311 self.bytes
312 .iter()
313 .filter(|byte| (**byte & 0xC0) != 0x80)
314 .map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
315 .sum()
316 }
317
318 /// The code unit at `index`, or `None` past the end.
319 pub fn code_unit_at(&self, index: usize) -> Option<u16> {
320 // Walking instead of decoding keeps `charCodeAt` in a loop linear rather than
321 // quadratic, which matters because that is exactly how a script inspects a string.
322 let mut position = 0;
323 let mut at = 0;
324 while at < self.bytes.len() {
325 let (units, count, width) = self.sequence_at(at);
326 if position + count > index {
327 return Some(units[index - position]);
328 }
329 position += count;
330 at += width;
331 }
332 None
333 }
334
335 /// Whether the string is empty.
336 pub fn is_empty(&self) -> bool {
337 self.bytes.is_empty()
338 }
339
340 /// One code unit as a string, which is what `s[i]` yields.
341 ///
342 /// A single unit, not a code point: `"\u{1F600}"[0]` is the lone high surrogate, because
343 /// indexing a string in JS works on code units.
344 pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
345 self.code_unit_at(index)
346 .map(|unit| Wtf8::from_units(&[unit]))
347 }
348
349 /// The code units `start..end`, re-encoded canonically.
350 pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
351 let units = self.to_units();
352 let start = start.min(units.len());
353 let end = end.clamp(start, units.len());
354 Wtf8::from_units(&units[start..end])
355 }
356
357 /// One element per code *point*, which is how a string is iterated.
358 ///
359 /// Iteration and indexing disagree on purpose: `[...str]` splits an astral character
360 /// into one element while `str[0]` splits it into half a surrogate pair.
361 pub fn code_points(&self) -> Vec<Wtf8> {
362 let mut out = Vec::new();
363 let mut at = 0;
364 while at < self.bytes.as_slice().len() {
365 let (_, _, width) = self.sequence_at(at);
366 let mut bytes = Vec::with_capacity(width);
367 bytes.extend_from_slice(&self.bytes.as_slice()[at..at + width]);
368 // A single sequence is always canonical on its own: a four-byte one is already
369 // an astral code point and a three-byte one is a BMP code point or a lone
370 // surrogate.
371 let valid = std::str::from_utf8(&bytes).is_ok();
372 out.push(Wtf8 {
373 valid,
374 bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
375 });
376 at += width;
377 }
378 out
379 }
380
381 /// Concatenate, keeping the encoding canonical.
382 ///
383 /// Byte concatenation is already canonical *except* where a high surrogate at the end of
384 /// `self` meets a low surrogate at the start of `other`: those two must fold into one
385 /// astral sequence, or the result would be a different string from the one the language
386 /// says `+` produces.
387 pub fn concat(&self, other: &Wtf8) -> Wtf8 {
388 let bridges = ends_with_high_surrogate(self.bytes.as_slice())
389 && starts_with_low_surrogate(other.bytes.as_slice());
390 if !bridges {
391 let mut bytes =
392 Vec::with_capacity(self.bytes.as_slice().len() + other.bytes.as_slice().len());
393 bytes.extend_from_slice(self.bytes.as_slice());
394 bytes.extend_from_slice(other.bytes.as_slice());
395 return Wtf8 {
396 bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
397 valid: self.valid && other.valid,
398 };
399 }
400 let mut units = self.to_units();
401 units.extend(other.to_units());
402 Wtf8::from_units(&units)
403 }
404
405 /// Append `other` to this string **in place**, when the buffer is unshared.
406 ///
407 /// Returns the number of bytes added, or `None` when the append could not be done in
408 /// place. That is the whole point of [`Bytes::Owned`]: `s += t` in a loop is a copy of
409 /// the entire string per iteration unless the buffer can grow, which is why the
410 /// reference has `JS_ConcatStringInPlace` — and why `string:concat` was the slowest
411 /// case in the suite (0.06×) before this.
412 ///
413 /// Three conditions, each one a correctness requirement rather than a heuristic:
414 ///
415 /// * **The bytes must be owned and unshared.** `Rc::get_mut` answers that; a shared
416 /// buffer belongs to another visible string and appending to it would change that
417 /// string too.
418 /// * **The two must not meet at a surrogate boundary.** Byte concatenation is already
419 /// canonical except where a high surrogate at the end meets a low surrogate at the
420 /// start, and there the result would be a different string from the one `+` builds.
421 /// Falling back is cheap and always correct.
422 /// * **`valid` must stay right**, which the caller-facing wrapper re-derives from the
423 /// two inputs.
424 pub fn append_in_place(&mut self, other: &Wtf8) -> Option<usize> {
425 let Bytes::Owned(owned) = &mut self.bytes else {
426 return None;
427 };
428 if ends_with_high_surrogate(owned.as_slice())
429 && starts_with_low_surrogate(other.bytes.as_slice())
430 {
431 return None;
432 }
433 let buffer = std::rc::Rc::get_mut(owned)?;
434 // The capacity, not the length: that is what the string now holds, and what
435 // `Heap::adjust_payload` has to be told so the running total stays equal to what
436 // `external_bytes` reports. Returning the length would drift by the spare
437 // capacity `Vec` keeps.
438 let before = buffer.capacity();
439 buffer.extend_from_slice(other.bytes.as_slice());
440 self.valid = self.valid && other.valid;
441 Some(buffer.capacity() - before)
442 }
443
444 /// Append the code units to `out`.
445 fn push_units(&self, out: &mut Vec<u16>) {
446 let mut at = 0;
447 while at < self.bytes.len() {
448 let (units, count, width) = self.sequence_at(at);
449 out.extend_from_slice(&units[..count]);
450 at += width;
451 }
452 }
453
454 /// The text as **source code**, for a parser that reads `&str`.
455 ///
456 /// Every string here is valid UTF-8 except one that contains an unpaired surrogate, and
457 /// a `&str` cannot spell those — yet `eval("\ud800")` really does hand the parser a
458 /// source text containing one, as a `.source` must give it back
459 /// (`literals/regexp/S7.8.5_A1.1_T2`). Where such a code unit can legally appear in
460 /// source — inside a string literal, a template literal, a regexp literal or a comment —
461 /// its `\uXXXX` escape means the same thing, so spelling it is not a change of meaning
462 /// but the only way to write it down at all. (The one place the two are distinguishable
463 /// is `String.raw` of a template that holds a surrogate *literally*.)
464 pub fn to_source_text(&self) -> std::borrow::Cow<'_, str> {
465 if let Some(text) = self.as_str() {
466 return std::borrow::Cow::Borrowed(text);
467 }
468 let units = self.to_units();
469 let mut out = String::with_capacity(units.len() + 8);
470 let mut index = 0;
471 while index < units.len() {
472 let unit = units[index];
473 let pair = units.get(index + 1).copied();
474 match (unit, pair) {
475 (high @ 0xD800..=0xDBFF, Some(low @ 0xDC00..=0xDFFF)) => {
476 let scalar =
477 0x10000 + ((u32::from(high) - 0xD800) << 10) + (u32::from(low) - 0xDC00);
478 out.push(char::from_u32(scalar).expect("a pair is a scalar"));
479 index += 2;
480 }
481 (lone @ 0xD800..=0xDFFF, _) => {
482 out.push_str(&format!("\\u{lone:04X}"));
483 index += 1;
484 }
485 (unit, _) => {
486 out.push(char::from_u32(u32::from(unit)).expect("a BMP unit is a scalar"));
487 index += 1;
488 }
489 }
490 }
491 std::borrow::Cow::Owned(out)
492 }
493
494 /// The code points the regular expression engine matches against.
495 ///
496 /// This is [`Wtf8::code_points`] flattened to `u32`, with a lone surrogate kept as its
497 /// own value rather than becoming U+FFFD: `\p{Cs}` has to match it, and no `char` can
498 /// hold it. A valid pair is one code point, so an offset into this list is still a code
499 /// point boundary.
500 pub fn code_point_values(&self) -> Vec<u32> {
501 self.code_points()
502 .into_iter()
503 .map(|point| match point.as_str() {
504 Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
505 // A lone surrogate: three bytes, one code unit, which *is* the value.
506 None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
507 })
508 .collect()
509 }
510
511 /// The code units the sequence starting at `at` stands for, how many of them there are,
512 /// and its byte width.
513 fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
514 let byte = self.bytes.as_slice()[at];
515 let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
516 if byte < 0x80 {
517 ([byte as u16, 0], 1, 1)
518 } else if byte >> 5 == 0b110 {
519 (
520 [
521 (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
522 0,
523 ],
524 1,
525 2,
526 )
527 } else if byte >> 4 == 0b1110 {
528 // A three-byte sequence is either a BMP code point or a lone surrogate; either
529 // way it is exactly one code unit.
530 (
531 [
532 ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
533 as u16,
534 0,
535 ],
536 1,
537 3,
538 )
539 } else {
540 let code = (byte as u32 & 0x07) << 18
541 | ((byte_at(1) & 0x3F) << 12)
542 | ((byte_at(2) & 0x3F) << 6)
543 | (byte_at(3) & 0x3F);
544 let code = code.wrapping_sub(0x10000);
545 (
546 [
547 0xD800u16.wrapping_add((code >> 10) as u16),
548 0xDC00u16.wrapping_add((code & 0x3FF) as u16),
549 ],
550 2,
551 4,
552 )
553 }
554 }
555}
556
557fn is_surrogate(unit: u16) -> bool {
558 (0xD800..0xE000).contains(&unit)
559}
560
561fn is_high(unit: u16) -> bool {
562 (0xD800..0xDC00).contains(&unit)
563}
564
565fn is_low(unit: u16) -> bool {
566 (0xDC00..0xE000).contains(&unit)
567}
568
569/// The astral code point a surrogate pair spells.
570fn combine(high: u16, low: u16) -> u32 {
571 0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
572}
573
574/// Write a code point as UTF-8.
575fn push_code_point(out: &mut Vec<u8>, code: u32) {
576 if code < 0x80 {
577 out.push(code as u8);
578 } else if code < 0x800 {
579 out.push(0xC0 | (code >> 6) as u8);
580 out.push(0x80 | (code & 0x3F) as u8);
581 } else if code < 0x10000 {
582 out.push(0xE0 | (code >> 12) as u8);
583 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
584 out.push(0x80 | (code & 0x3F) as u8);
585 } else {
586 out.push(0xF0 | (code >> 18) as u8);
587 out.push(0x80 | ((code >> 12) & 0x3F) as u8);
588 out.push(0x80 | ((code >> 6) & 0x3F) as u8);
589 out.push(0x80 | (code & 0x3F) as u8);
590 }
591}
592
593/// Write an unpaired surrogate as the three-byte sequence WTF-8 gives it.
594fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
595 out.push(0xE0 | (unit >> 12) as u8);
596 out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
597 out.push(0x80 | (unit & 0x3F) as u8);
598}
599
600/// Whether the bytes end with an unpaired high surrogate.
601///
602/// High surrogates are `ED A0..AF 80..BF` and low ones `ED B0..BF 80..BF`, so the test is on
603/// the second byte of the trailing three-byte sequence.
604fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
605 let len = bytes.len();
606 len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
607}
608
609/// Whether the bytes start with an unpaired low surrogate.
610fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
611 bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
612}
613
614impl PartialEq for Wtf8 {
615 /// Byte equality, which the canonical encoding makes equal to code-unit equality.
616 fn eq(&self, other: &Self) -> bool {
617 // The bytes, through whichever representation each side has. Comparing pointers
618 // first would be one branch cheaper for two atoms — but it is two *more* branches
619 // for the atom-against-atom comparison this actually sees, which is every property
620 // key lookup: measured, it cost 7% of `property:monomorphic`.
621 self.bytes.as_slice() == other.bytes.as_slice()
622 }
623}
624
625impl Eq for Wtf8 {}
626
627impl fmt::Debug for Wtf8 {
628 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
629 write!(f, "{:?}", self.to_string_lossy())
630 }
631}
632/// Comparing against a `&str` literal, which is exact rather than approximate.
633///
634/// A `Wtf8` holding an unpaired surrogate has no `&str` form at all, so it can never equal
635/// one; the comparison is `as_str() == Some(other)` and cannot conflate two different
636/// strings. Without this, every `key == "prototype"` in the parser would have to spell out
637/// the `Option` and the reason for it at each site.
638impl PartialEq<str> for Wtf8 {
639 fn eq(&self, other: &str) -> bool {
640 self.as_str() == Some(other)
641 }
642}
643
644impl PartialEq<&str> for Wtf8 {
645 fn eq(&self, other: &&str) -> bool {
646 self.as_str() == Some(*other)
647 }
648}
649
650impl Default for Wtf8 {
651 /// The empty string, which is also what a missing atom's text is.
652 fn default() -> Wtf8 {
653 Wtf8::new("")
654 }
655}
656
657impl std::hash::Hash for Wtf8 {
658 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
659 // The bytes, which the type's own documentation makes equivalent to the code
660 // units: the encoding is canonical, so two strings are equal exactly when their
661 // bytes are. Atom interning and property-key lookup both depend on that.
662 self.bytes.as_slice().hash(state);
663 }
664}
665
666#[cfg(test)]
667mod tests {
668 use super::*;
669
670 /// The bytes and the string must round-trip, which is what the serialised bytecode blob
671 /// relies on: atoms and string constants are written as WTF-8 and read back.
672 #[test]
673 fn wtf8_bytes_round_trip() {
674 for text in ["", "plain ascii", "\u{1F600} astral", "Привет"] {
675 let string = Wtf8::new(text);
676 let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("valid WTF-8");
677 assert_eq!(decoded, string);
678 }
679 }
680
681 /// A lone surrogate survives the round trip too — this is the case the whole type exists
682 /// for, and the case `String::from_utf8` would reject.
683 #[test]
684 fn wtf8_bytes_keep_a_lone_surrogate() {
685 let string = Wtf8::from_units(&[0xD800]);
686 assert_eq!(string.to_units(), vec![0xD800]);
687 let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("WTF-8 accepts it");
688 assert_eq!(decoded, string);
689 assert!(!decoded.is_valid());
690 }
691
692 /// A pair written as two three-byte sequences decodes to the canonical four-byte form,
693 /// so the decoded string equals the one `from_units` builds directly.
694 #[test]
695 fn wtf8_bytes_canonicalise_a_pair() {
696 let mut split = Vec::new();
697 split.extend_from_slice(&[0xED, 0xA0, 0xBD]); // U+D83D
698 split.extend_from_slice(&[0xED, 0xB8, 0x80]); // U+DE00
699 let decoded = Wtf8::from_wtf8_bytes(&split).expect("valid WTF-8");
700 assert_eq!(decoded.to_units(), vec![0xD83D, 0xDE00]);
701 assert_eq!(decoded, Wtf8::new("\u{1F600}"));
702 }
703
704 /// Bytes that are not WTF-8 at all are refused rather than decoded into something.
705 #[test]
706 fn invalid_utf8_is_refused() {
707 // Truncated, stray continuation, overlong, and a five-byte lead.
708 assert!(Wtf8::from_wtf8_bytes(&[0xC3]).is_none());
709 assert!(Wtf8::from_wtf8_bytes(&[0x80]).is_none());
710 assert!(Wtf8::from_wtf8_bytes(&[0xC1, 0x81]).is_none());
711 assert!(Wtf8::from_wtf8_bytes(&[0xF8, 0x80, 0x80, 0x80, 0x80]).is_none());
712 }
713}