quickjs-parse 0.14.0

ECMAScript 2025 lexer, AST and parser for the pure-Rust QuickJS port
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
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
//! The string type JavaScript actually has, in **WTF-8**.
//!
//! This lives *below* the parser rather than with the rest of the value types because the
//! **lexer** has to build one: a string literal may contain a lone surrogate
//! (`"\uD800"`), and Rust's `String` cannot hold that, so the cooked value of a literal is
//! a [`Wtf8`]. The runtime re-exports this type, so `Value::String` holds the same type the
//! parser produced — one representation all the way through, with no conversion step at
//! which a surrogate could be lost.
//!
//! The crate is the bottom of the engine, so this module has no dependencies.

use std::fmt;

/// Where a [`Wtf8`]'s bytes live.
///
/// Two representations, because the two things a string does with its bytes want opposite
/// layouts:
///
/// * An **atom** — a property name from the compiled code — is created on every property
///   access and never grows. `Shared` copies it into one allocation and clones are a
///   refcount bump.
/// * A **result** — `a + b` — is built once from two slices and, for the `s += x` loop the
///   language encourages, then grows in place. `Owned` keeps a `Vec`, so
///   [`Wtf8::append_in_place`] reuses the buffer instead of copying the whole string per
///   append.
///
/// Both are `Rc`, so `Clone` stays a refcount bump either way — that is the property the
/// whole engine leans on (see the field comment below).
#[derive(Clone)]
enum Bytes {
    /// Shared, immutable, exactly as long as its contents.
    Shared(std::rc::Rc<[u8]>),
    /// Owned through a `Vec`, which can grow in place while it is unshared.
    Owned(std::rc::Rc<Vec<u8>>),
}

impl Bytes {
    #[inline(always)]
    fn as_slice(&self) -> &[u8] {
        match self {
            Bytes::Shared(bytes) => bytes,
            Bytes::Owned(bytes) => bytes,
        }
    }

    /// The bytes this string is holding on to, which is the buffer's *capacity* for an
    /// owned one.
    ///
    /// `Vec` doubles, so a string built by 200,000 appends holds up to twice its length;
    /// reporting only the length would let a `--memory-limit` run exceed the limit it asked
    /// for by that factor. `Heap::adjust_payload` and this must agree exactly, because the
    /// two are added and subtracted from the same counter.
    fn allocated(&self) -> usize {
        match self {
            Bytes::Shared(bytes) => bytes.len(),
            Bytes::Owned(bytes) => bytes.capacity(),
        }
    }
}

impl std::ops::Deref for Bytes {
    type Target = [u8];

    fn deref(&self) -> &[u8] {
        self.as_slice()
    }
}

/// A JavaScript string's bytes, in **WTF-8**.
///
/// A JS string is a sequence of UTF-16 *code units*, and that sequence may contain an
/// unpaired surrogate: `String.fromCharCode(0xD800)` produces exactly one, and
/// `"\uD800".length` is 1. Rust's `String` cannot represent that, so the bytes here are
/// WTF-8 — ordinary UTF-8, except that a code unit with no partner is written as the
/// three-byte sequence UTF-8 would use for U+D800..U+DFFF.
///
/// # The encoding is canonical, and that is load-bearing
///
/// A *surrogate pair* is written as the single four-byte sequence of the astral code point
/// it spells, never as two three-byte sequences. Without that rule the bytes of `"\uD800" +
/// "\uDC00"` would differ from the bytes of `"\u{10000}"` while the two strings are
/// observably identical — same length, same `charCodeAt` at every index — and every
/// equality, property key and `switch` arm in the engine would disagree with the language.
///
/// The canonical form makes **byte equality exactly code-unit equality**, which is what lets
/// a property key be compared without decoding it.
#[derive(Clone)]
pub struct Wtf8 {
    /// The WTF-8 bytes, shared.
    ///
    /// `Rc<[u8]>` rather than `Box<[u8]>` because cloning a `Wtf8` is one of the hottest
    /// operations in the engine: every property key comparison, every atom lookup and every
    /// `Value::String` copy did it, and with a `Box` each clone deep-copied the bytes. That
    /// is a heap allocation plus a memcpy per property read, which is why
    /// `property:monomorphic` was 16× slower than the reference before this.
    ///
    /// Being `Rc` makes `Wtf8` `!Send`, which it effectively already was: it lives behind
    /// `Gc`, which uses a non-atomic refcount.
    bytes: Bytes,
    /// Whether `bytes` is valid UTF-8, meaning the string has no unpaired surrogate.
    ///
    /// A `Wtf8` is immutable, so this stays correct for its whole life.
    valid: bool,
}

impl Wtf8 {
    /// Wrap a Rust string, which is valid UTF-8 by construction.
    pub fn new(text: impl Into<String>) -> Wtf8 {
        Wtf8 {
            bytes: Bytes::Owned(std::rc::Rc::new(text.into().into_bytes())),
            valid: true,
        }
    }

    /// Build from a `&str` without copying it.
    ///
    /// `Wtf8::new` takes `impl Into<String>`, which copies. A property atom is a `&str` that
    /// already lives in the compiled code and outlives every use of the key, so sharing the
    /// bytes is free — and this is on the path of every property access.
    pub fn from_rc_str(text: &str) -> Wtf8 {
        Wtf8 {
            bytes: Bytes::Shared(std::rc::Rc::from(text.as_bytes())),
            valid: true,
        }
    }

    /// Build from bytes that are already WTF-8, with `valid` saying whether they contain an
    /// unpaired surrogate.
    ///
    /// Used by the rope's flattening path, which has just concatenated children whose
    /// validity it knows.
    pub fn from_parts(bytes: Vec<u8>, valid: bool) -> Wtf8 {
        Wtf8 {
            bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
            valid,
        }
    }

    /// Whether the bytes are valid UTF-8, i.e. the string has no unpaired surrogate.
    /// The bytes this string is holding on to — the buffer's *capacity* when it owns one.
    ///
    /// A `Vec` doubles, so a string built by 200,000 appends holds up to twice its length;
    /// the heap accounting must charge for what is really allocated, not for what is used.
    pub fn allocated_bytes(&self) -> usize {
        self.bytes.allocated()
    }

    /// Whether the text is well-formed — no unpaired surrogate.
    ///
    /// The one thing the bytes alone cannot answer without decoding, so it is computed once
    /// at construction.
    pub fn is_valid(&self) -> bool {
        self.valid
    }

    /// Build from code points, folding astral ones into the pair they spell.
    ///
    /// The inverse of [`Wtf8::code_point_values`]: a value in `0xD800..=0xDFFF` is taken to
    /// be a lone surrogate rather than an error, because that is what a code point list from
    /// this type can legitimately contain.
    pub fn from_code_points(points: &[u32]) -> Wtf8 {
        let mut units = Vec::with_capacity(points.len());
        for &point in points {
            if point > 0xFFFF {
                let value = point - 0x10000;
                units.push(0xD800 + (value >> 10) as u16);
                units.push(0xDC00 + (value & 0x3FF) as u16);
            } else {
                units.push(point as u16);
            }
        }
        Wtf8::from_units(&units)
    }

    /// Build from UTF-16 code units, which is the form a JS string really has.
    ///
    /// An unpaired surrogate survives; a pair is folded into its astral code point.
    /// Decode WTF-8 bytes, canonicalising them.
    ///
    /// The strict counterpart of [`Wtf8::as_bytes`], for text that came from outside the
    /// process: a serialised bytecode blob carries atoms and string constants as raw bytes,
    /// and one of them may be an unpaired surrogate. `String::from_utf8` would reject it,
    /// which is why this exists rather than `from`.
    ///
    /// `None` for bytes that are not WTF-8 at all — a truncated sequence, a stray
    /// continuation byte, or an overlong encoding. The code units are then re-encoded
    /// through [`Wtf8::from_units`], so the result is canonical even if the input wrote a
    /// surrogate pair as two three-byte sequences.
    pub fn from_wtf8_bytes(bytes: &[u8]) -> Option<Wtf8> {
        let mut units: Vec<u16> = Vec::with_capacity(bytes.len());
        let mut at = 0;
        while at < bytes.len() {
            let first = bytes[at];
            // The payload bits each lead byte contributes: 7, then 5, 4 and 3. Derived from
            // the length rather than by shifting `0x7f`, because `0x7f >> 1` is `0x3f` — off
            // by the top bit of the payload, which silently corrupts every ASCII character.
            let (length, payload_mask, min) = match first {
                0x00..=0x7f => (1, 0x7f, 0),
                0xc2..=0xdf => (2, 0x1f, 0x80),
                0xe0..=0xef => (3, 0x0f, 0x800),
                0xf0..=0xf4 => (4, 0x07, 0x10000),
                // 0x80..=0xc1 (continuation bytes and overlong two-byte leads) and
                // 0xf5..=0xff are never valid WTF-8.
                _ => return None,
            };
            let end = at.checked_add(length)?;
            if end > bytes.len() {
                return None;
            }
            let mut code = u32::from(first) & payload_mask;
            for &byte in &bytes[at + 1..end] {
                if byte & 0xc0 != 0x80 {
                    return None;
                }
                code = (code << 6) | u32::from(byte & 0x3f);
            }
            if code < min {
                // Overlong: the same code point has a shorter encoding, so accepting this
                // would make two byte strings for one string.
                return None;
            }
            if code > 0xffff {
                let value = code - 0x10000;
                units.push(0xd800 + (value >> 10) as u16);
                units.push(0xdc00 + (value & 0x3ff) as u16);
            } else {
                units.push(code as u16);
            }
            at = end;
        }
        Some(Wtf8::from_units(&units))
    }

    /// Build from UTF-16 code units, which is the form a JS string really has.
    ///
    /// A surrogate pair is folded into the astral code point it spells, so the result is
    /// canonical: this is where the encoding's invariant is enforced, and therefore the only
    /// place that has to know about it.
    pub fn from_units(units: &[u16]) -> Wtf8 {
        let mut bytes = Vec::with_capacity(units.len());
        let mut valid = true;
        let mut index = 0;
        while index < units.len() {
            let unit = units[index];
            match units.get(index + 1) {
                Some(&low) if is_high(unit) && is_low(low) => {
                    push_code_point(&mut bytes, combine(unit, low));
                    index += 2;
                }
                _ if is_surrogate(unit) => {
                    // A lone surrogate keeps its own three-byte form, so it round-trips and
                    // still counts as one code unit.
                    valid = false;
                    push_surrogate(&mut bytes, unit);
                    index += 1;
                }
                _ => {
                    push_code_point(&mut bytes, unit as u32);
                    index += 1;
                }
            }
        }
        Wtf8 {
            bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
            valid,
        }
    }

    /// The text, when it is valid UTF-8.
    ///
    /// `None` only for a string containing an unpaired surrogate — there is no `&str` for
    /// one. Callers that only need to display or compare use [`Wtf8::to_string_lossy`].
    pub fn as_str(&self) -> Option<&str> {
        if self.valid {
            // SAFETY: `valid` is only set by the encoder above, which produces valid UTF-8
            // exactly when no surrogate was written on its own, and the bytes never change.
            Some(unsafe { std::str::from_utf8_unchecked(self.bytes.as_slice()) })
        } else {
            None
        }
    }

    /// The text with unpaired surrogates replaced by U+FFFD.
    ///
    /// Borrowed, and therefore free, for the ordinary string that has no surrogate.
    pub fn to_string_lossy(&self) -> std::borrow::Cow<'_, str> {
        match self.as_str() {
            Some(text) => std::borrow::Cow::Borrowed(text),
            None => String::from_utf8_lossy(self.bytes.as_slice()),
        }
    }

    /// The WTF-8 bytes. Two `Wtf8`s are equal exactly when these are.
    pub fn as_bytes(&self) -> &[u8] {
        self.bytes.as_slice()
    }

    /// The UTF-16 code units, which is what indexing and `charCodeAt` count.
    pub fn to_units(&self) -> Vec<u16> {
        let mut units = Vec::with_capacity(self.utf16_len());
        self.push_units(&mut units);
        units
    }

    /// Length in UTF-16 code units, which is what `String.prototype.length` reports.
    ///
    /// Counted from the encoding rather than by decoding, so it does not allocate: a
    /// four-byte sequence is a surrogate pair and therefore two units, everything else is
    /// one.
    pub fn utf16_len(&self) -> usize {
        self.bytes
            .iter()
            .filter(|byte| (**byte & 0xC0) != 0x80)
            .map(|byte| if *byte >= 0xF0 { 2 } else { 1 })
            .sum()
    }

    /// The code unit at `index`, or `None` past the end.
    pub fn code_unit_at(&self, index: usize) -> Option<u16> {
        // Walking instead of decoding keeps `charCodeAt` in a loop linear rather than
        // quadratic, which matters because that is exactly how a script inspects a string.
        let mut position = 0;
        let mut at = 0;
        while at < self.bytes.len() {
            let (units, count, width) = self.sequence_at(at);
            if position + count > index {
                return Some(units[index - position]);
            }
            position += count;
            at += width;
        }
        None
    }

    /// Whether the string is empty.
    pub fn is_empty(&self) -> bool {
        self.bytes.is_empty()
    }

    /// One code unit as a string, which is what `s[i]` yields.
    ///
    /// A single unit, not a code point: `"\u{1F600}"[0]` is the lone high surrogate, because
    /// indexing a string in JS works on code units.
    pub fn unit_at(&self, index: usize) -> Option<Wtf8> {
        self.code_unit_at(index)
            .map(|unit| Wtf8::from_units(&[unit]))
    }

    /// The code units `start..end`, re-encoded canonically.
    pub fn slice_units(&self, start: usize, end: usize) -> Wtf8 {
        let units = self.to_units();
        let start = start.min(units.len());
        let end = end.clamp(start, units.len());
        Wtf8::from_units(&units[start..end])
    }

    /// One element per code *point*, which is how a string is iterated.
    ///
    /// Iteration and indexing disagree on purpose: `[...str]` splits an astral character
    /// into one element while `str[0]` splits it into half a surrogate pair.
    pub fn code_points(&self) -> Vec<Wtf8> {
        let mut out = Vec::new();
        let mut at = 0;
        while at < self.bytes.as_slice().len() {
            let (_, _, width) = self.sequence_at(at);
            let mut bytes = Vec::with_capacity(width);
            bytes.extend_from_slice(&self.bytes.as_slice()[at..at + width]);
            // A single sequence is always canonical on its own: a four-byte one is already
            // an astral code point and a three-byte one is a BMP code point or a lone
            // surrogate.
            let valid = std::str::from_utf8(&bytes).is_ok();
            out.push(Wtf8 {
                valid,
                bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
            });
            at += width;
        }
        out
    }

    /// Concatenate, keeping the encoding canonical.
    ///
    /// Byte concatenation is already canonical *except* where a high surrogate at the end of
    /// `self` meets a low surrogate at the start of `other`: those two must fold into one
    /// astral sequence, or the result would be a different string from the one the language
    /// says `+` produces.
    pub fn concat(&self, other: &Wtf8) -> Wtf8 {
        let bridges = ends_with_high_surrogate(self.bytes.as_slice())
            && starts_with_low_surrogate(other.bytes.as_slice());
        if !bridges {
            let mut bytes =
                Vec::with_capacity(self.bytes.as_slice().len() + other.bytes.as_slice().len());
            bytes.extend_from_slice(self.bytes.as_slice());
            bytes.extend_from_slice(other.bytes.as_slice());
            return Wtf8 {
                bytes: Bytes::Owned(std::rc::Rc::new(bytes)),
                valid: self.valid && other.valid,
            };
        }
        let mut units = self.to_units();
        units.extend(other.to_units());
        Wtf8::from_units(&units)
    }

    /// Append `other` to this string **in place**, when the buffer is unshared.
    ///
    /// Returns the number of bytes added, or `None` when the append could not be done in
    /// place. That is the whole point of [`Bytes::Owned`]: `s += t` in a loop is a copy of
    /// the entire string per iteration unless the buffer can grow, which is why the
    /// reference has `JS_ConcatStringInPlace` — and why `string:concat` was the slowest
    /// case in the suite (0.06×) before this.
    ///
    /// Three conditions, each one a correctness requirement rather than a heuristic:
    ///
    /// * **The bytes must be owned and unshared.** `Rc::get_mut` answers that; a shared
    ///   buffer belongs to another visible string and appending to it would change that
    ///   string too.
    /// * **The two must not meet at a surrogate boundary.** Byte concatenation is already
    ///   canonical except where a high surrogate at the end meets a low surrogate at the
    ///   start, and there the result would be a different string from the one `+` builds.
    ///   Falling back is cheap and always correct.
    /// * **`valid` must stay right**, which the caller-facing wrapper re-derives from the
    ///   two inputs.
    pub fn append_in_place(&mut self, other: &Wtf8) -> Option<usize> {
        let Bytes::Owned(owned) = &mut self.bytes else {
            return None;
        };
        if ends_with_high_surrogate(owned.as_slice())
            && starts_with_low_surrogate(other.bytes.as_slice())
        {
            return None;
        }
        let buffer = std::rc::Rc::get_mut(owned)?;
        // The capacity, not the length: that is what the string now holds, and what
        // `Heap::adjust_payload` has to be told so the running total stays equal to what
        // `external_bytes` reports. Returning the length would drift by the spare
        // capacity `Vec` keeps.
        let before = buffer.capacity();
        buffer.extend_from_slice(other.bytes.as_slice());
        self.valid = self.valid && other.valid;
        Some(buffer.capacity() - before)
    }

    /// Append the code units to `out`.
    fn push_units(&self, out: &mut Vec<u16>) {
        let mut at = 0;
        while at < self.bytes.len() {
            let (units, count, width) = self.sequence_at(at);
            out.extend_from_slice(&units[..count]);
            at += width;
        }
    }

    /// The code points the regular expression engine matches against.
    ///
    /// This is [`Wtf8::code_points`] flattened to `u32`, with a lone surrogate kept as its
    /// own value rather than becoming U+FFFD: `\p{Cs}` has to match it, and no `char` can
    /// hold it. A valid pair is one code point, so an offset into this list is still a code
    /// point boundary.
    pub fn code_point_values(&self) -> Vec<u32> {
        self.code_points()
            .into_iter()
            .map(|point| match point.as_str() {
                Some(text) => text.chars().next().map_or(0xFFFD, |c| c as u32),
                // A lone surrogate: three bytes, one code unit, which *is* the value.
                None => point.to_units().first().copied().map_or(0xFFFD, u32::from),
            })
            .collect()
    }

    /// The code units the sequence starting at `at` stands for, how many of them there are,
    /// and its byte width.
    fn sequence_at(&self, at: usize) -> ([u16; 2], usize, usize) {
        let byte = self.bytes.as_slice()[at];
        let byte_at = |offset: usize| self.bytes.get(at + offset).copied().unwrap_or(0) as u32;
        if byte < 0x80 {
            ([byte as u16, 0], 1, 1)
        } else if byte >> 5 == 0b110 {
            (
                [
                    (((byte as u32 & 0x1F) << 6) | (byte_at(1) & 0x3F)) as u16,
                    0,
                ],
                1,
                2,
            )
        } else if byte >> 4 == 0b1110 {
            // A three-byte sequence is either a BMP code point or a lone surrogate; either
            // way it is exactly one code unit.
            (
                [
                    ((byte as u32 & 0x0F) << 12 | ((byte_at(1) & 0x3F) << 6) | (byte_at(2) & 0x3F))
                        as u16,
                    0,
                ],
                1,
                3,
            )
        } else {
            let code = (byte as u32 & 0x07) << 18
                | ((byte_at(1) & 0x3F) << 12)
                | ((byte_at(2) & 0x3F) << 6)
                | (byte_at(3) & 0x3F);
            let code = code.wrapping_sub(0x10000);
            (
                [
                    0xD800u16.wrapping_add((code >> 10) as u16),
                    0xDC00u16.wrapping_add((code & 0x3FF) as u16),
                ],
                2,
                4,
            )
        }
    }
}

fn is_surrogate(unit: u16) -> bool {
    (0xD800..0xE000).contains(&unit)
}

fn is_high(unit: u16) -> bool {
    (0xD800..0xDC00).contains(&unit)
}

fn is_low(unit: u16) -> bool {
    (0xDC00..0xE000).contains(&unit)
}

/// The astral code point a surrogate pair spells.
fn combine(high: u16, low: u16) -> u32 {
    0x10000 + ((high as u32 - 0xD800) << 10) + (low as u32 - 0xDC00)
}

/// Write a code point as UTF-8.
fn push_code_point(out: &mut Vec<u8>, code: u32) {
    if code < 0x80 {
        out.push(code as u8);
    } else if code < 0x800 {
        out.push(0xC0 | (code >> 6) as u8);
        out.push(0x80 | (code & 0x3F) as u8);
    } else if code < 0x10000 {
        out.push(0xE0 | (code >> 12) as u8);
        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
        out.push(0x80 | (code & 0x3F) as u8);
    } else {
        out.push(0xF0 | (code >> 18) as u8);
        out.push(0x80 | ((code >> 12) & 0x3F) as u8);
        out.push(0x80 | ((code >> 6) & 0x3F) as u8);
        out.push(0x80 | (code & 0x3F) as u8);
    }
}

/// Write an unpaired surrogate as the three-byte sequence WTF-8 gives it.
fn push_surrogate(out: &mut Vec<u8>, unit: u16) {
    out.push(0xE0 | (unit >> 12) as u8);
    out.push(0x80 | ((unit >> 6) & 0x3F) as u8);
    out.push(0x80 | (unit & 0x3F) as u8);
}

/// Whether the bytes end with an unpaired high surrogate.
///
/// High surrogates are `ED A0..AF 80..BF` and low ones `ED B0..BF 80..BF`, so the test is on
/// the second byte of the trailing three-byte sequence.
fn ends_with_high_surrogate(bytes: &[u8]) -> bool {
    let len = bytes.len();
    len >= 3 && bytes[len - 3] == 0xED && (0xA0..0xB0).contains(&bytes[len - 2])
}

/// Whether the bytes start with an unpaired low surrogate.
fn starts_with_low_surrogate(bytes: &[u8]) -> bool {
    bytes.len() >= 3 && bytes[0] == 0xED && (0xB0..0xC0).contains(&bytes[1])
}

impl PartialEq for Wtf8 {
    /// Byte equality, which the canonical encoding makes equal to code-unit equality.
    fn eq(&self, other: &Self) -> bool {
        // The bytes, through whichever representation each side has. Comparing pointers
        // first would be one branch cheaper for two atoms — but it is two *more* branches
        // for the atom-against-atom comparison this actually sees, which is every property
        // key lookup: measured, it cost 7% of `property:monomorphic`.
        self.bytes.as_slice() == other.bytes.as_slice()
    }
}

impl Eq for Wtf8 {}

impl fmt::Debug for Wtf8 {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{:?}", self.to_string_lossy())
    }
}
/// Comparing against a `&str` literal, which is exact rather than approximate.
///
/// A `Wtf8` holding an unpaired surrogate has no `&str` form at all, so it can never equal
/// one; the comparison is `as_str() == Some(other)` and cannot conflate two different
/// strings. Without this, every `key == "prototype"` in the parser would have to spell out
/// the `Option` and the reason for it at each site.
impl PartialEq<str> for Wtf8 {
    fn eq(&self, other: &str) -> bool {
        self.as_str() == Some(other)
    }
}

impl PartialEq<&str> for Wtf8 {
    fn eq(&self, other: &&str) -> bool {
        self.as_str() == Some(*other)
    }
}

impl Default for Wtf8 {
    /// The empty string, which is also what a missing atom's text is.
    fn default() -> Wtf8 {
        Wtf8::new("")
    }
}

impl std::hash::Hash for Wtf8 {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        // The bytes, which the type's own documentation makes equivalent to the code
        // units: the encoding is canonical, so two strings are equal exactly when their
        // bytes are. Atom interning and property-key lookup both depend on that.
        self.bytes.as_slice().hash(state);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The bytes and the string must round-trip, which is what the serialised bytecode blob
    /// relies on: atoms and string constants are written as WTF-8 and read back.
    #[test]
    fn wtf8_bytes_round_trip() {
        for text in ["", "plain ascii", "\u{1F600} astral", "Привет"] {
            let string = Wtf8::new(text);
            let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("valid WTF-8");
            assert_eq!(decoded, string);
        }
    }

    /// A lone surrogate survives the round trip too — this is the case the whole type exists
    /// for, and the case `String::from_utf8` would reject.
    #[test]
    fn wtf8_bytes_keep_a_lone_surrogate() {
        let string = Wtf8::from_units(&[0xD800]);
        assert_eq!(string.to_units(), vec![0xD800]);
        let decoded = Wtf8::from_wtf8_bytes(string.as_bytes()).expect("WTF-8 accepts it");
        assert_eq!(decoded, string);
        assert!(!decoded.is_valid());
    }

    /// A pair written as two three-byte sequences decodes to the canonical four-byte form,
    /// so the decoded string equals the one `from_units` builds directly.
    #[test]
    fn wtf8_bytes_canonicalise_a_pair() {
        let mut split = Vec::new();
        split.extend_from_slice(&[0xED, 0xA0, 0xBD]); // U+D83D
        split.extend_from_slice(&[0xED, 0xB8, 0x80]); // U+DE00
        let decoded = Wtf8::from_wtf8_bytes(&split).expect("valid WTF-8");
        assert_eq!(decoded.to_units(), vec![0xD83D, 0xDE00]);
        assert_eq!(decoded, Wtf8::new("\u{1F600}"));
    }

    /// Bytes that are not WTF-8 at all are refused rather than decoded into something.
    #[test]
    fn invalid_utf8_is_refused() {
        // Truncated, stray continuation, overlong, and a five-byte lead.
        assert!(Wtf8::from_wtf8_bytes(&[0xC3]).is_none());
        assert!(Wtf8::from_wtf8_bytes(&[0x80]).is_none());
        assert!(Wtf8::from_wtf8_bytes(&[0xC1, 0x81]).is_none());
        assert!(Wtf8::from_wtf8_bytes(&[0xF8, 0x80, 0x80, 0x80, 0x80]).is_none());
    }
}