quickjs-pure 0.17.4

Embeddable JavaScript engine written in pure Rust (QuickJS-compatible)
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
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
//! `Uint8Array` base64 and hex: the `uint8array-base64` proposal.
//!
//! Six methods — `Uint8Array.{fromBase64,fromHex}` and
//! `Uint8Array.prototype.{toBase64,toHex,setFromBase64,setFromHex}` — absent from this
//! engine until §4.43. Their absence hid 70 test262 cases, because the runner skips by
//! `feature:` flag: a missing *method* under a proposal's feature name looks like a missing
//! *proposal*, and the number never moved.
//!
//! # Why the decoder is a state machine and not `split`+`decode`
//!
//! `setFromBase64` reports `{read, written}` and leaves whatever it decoded before the first
//! error in the target (`writes-up-to-error.js` checks the bytes that were written). So the
//! decoder has to (a) stop at the destination's capacity, mid-quantum, and say how much of
//! the *input* it consumed, and (b) write to the target as it goes rather than to a scratch
//! buffer. Both are properties of the loop, not of a library call — which is also why this
//! is a hand-written port of the reference's `from_base64` rather than a `base64` crate
//! (which would also break NFR-7: the engine crates have no third-party dependencies).
//!
//! # The three `lastChunkHandling` modes, and where they differ
//!
//! * `loose` (the default) — an unpadded final quantum is decoded; a *single* leftover
//!   character is an error, because one base64 character carries only 6 bits and half a byte
//!   is not a byte;
//! * `strict` — additionally rejects non-zero padding bits, so `"ZXhhZh=="` (whose last
//!   quantum has garbage in the low bits) throws while `"ZXhhZg=="` does not;
//! * `stop-before-partial` — a partial final quantum is not an error, it is simply not
//!   decoded, and `read` stops before it.
//!
//! Each mode has a case in `last-chunk-handling.js` and one in
//! `setFromBase64/last-chunk-handling.js`, and the `read` value differs between them — which
//! is the only reason the distinction is visible at all.

use crate::builtins::typedarray::ElementType;
use crate::builtins::{arg, define_method};
use crate::interp::{Interp, JsResult, Signal};
use crate::object::{JsObject, Property};
use js_gc::Gc;

/// The standard alphabet: `+` is 62 and `/` is 63.
const BASE64: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// The URL-safe alphabet: `-` is 62 and `_` is 63, and neither `+` nor `/` is accepted.
const BASE64URL: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";

/// A character the decoder skips: ASCII whitespace, which is TAB, LF, FF, CR and space.
///
/// Vertical tab is **not** in the set, and that is not an oversight — `illegal-characters.js`
/// has a case for `\v`.
const WHITESPACE: u8 = 64;
/// A character the decoder rejects.
const ILLEGAL: u8 = 65;

#[derive(Clone, Copy, PartialEq, Eq)]
enum Alphabet {
    Base64,
    Base64Url,
}

impl Alphabet {
    fn encode_table(self) -> &'static [u8; 64] {
        match self {
            Alphabet::Base64 => BASE64,
            Alphabet::Base64Url => BASE64URL,
        }
    }

    fn decode(self, byte: u8) -> u8 {
        match byte {
            b'\t' | b'\n' | b'\x0c' | b'\r' | b' ' => WHITESPACE,
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'+' if self == Alphabet::Base64 => 62,
            b'/' if self == Alphabet::Base64 => 63,
            b'-' if self == Alphabet::Base64Url => 62,
            b'_' if self == Alphabet::Base64Url => 63,
            _ => ILLEGAL,
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq)]
enum LastChunk {
    Loose,
    Strict,
    StopBeforePartial,
}

/// What a decode produced. `error` means the input was rejected and nothing should be
/// reported as consumed; the destination may still hold bytes decoded before that point,
/// which is exactly what `setFromBase64` is specified to leave behind.
struct Decoded {
    written: usize,
    read: usize,
    error: bool,
}

impl Decoded {
    fn fail() -> Decoded {
        Decoded {
            written: 0,
            read: 0,
            error: true,
        }
    }
}

/// `Spec: FromBase64(string, alphabet, lastChunkHandling)`, writing into `dst`.
///
/// A port of the reference's `from_base64`, deliberately step for step: the two
/// half-quantum capacities (`remaining == 1 && seen == 2`, `remaining == 2 && seen == 3`)
/// and the "stop before the padding, but still call it read" cases are all observable
/// through `setFromBase64`'s `read`/`written`, so "cleaner" arithmetic would change answers.
fn from_base64(src: &[u8], dst: &mut [u8], alphabet: Alphabet, last_chunk: LastChunk) -> Decoded {
    let src_len = src.len();
    let max_len = dst.len();
    let mut read = 0usize;
    let mut written = 0usize;
    let mut acc: u32 = 0;
    let mut seen = 0usize;
    let mut index = 0usize;

    if max_len == 0 {
        // Nothing can be written, so nothing is read. A zero-length target is legal and
        // must not consume input (`trailing-garbage-empty.js`).
        return Decoded {
            written: 0,
            read: 0,
            error: false,
        };
    }

    let skip_ws = |mut at: usize| -> usize {
        while at < src_len && alphabet.decode(src[at]) == WHITESPACE {
            at += 1;
        }
        at
    };

    loop {
        if seen == 0 {
            // Fast path: whole quanta of four clean characters. It stops on anything else
            // — whitespace, padding, an illegal byte, or the end of the destination — and
            // the slow path below decides what that means.
            while index + 4 <= src_len && written + 3 <= max_len {
                let v0 = alphabet.decode(src[index]);
                let v1 = alphabet.decode(src[index + 1]);
                let v2 = alphabet.decode(src[index + 2]);
                let v3 = alphabet.decode(src[index + 3]);
                if (v0 | v1 | v2 | v3) >= 64 {
                    break;
                }
                let v = (u32::from(v0) << 18)
                    | (u32::from(v1) << 12)
                    | (u32::from(v2) << 6)
                    | u32::from(v3);
                dst[written] = (v >> 16) as u8;
                dst[written + 1] = (v >> 8) as u8;
                dst[written + 2] = v as u8;
                written += 3;
                index += 4;
            }
            read = index;
            if written >= max_len {
                return Decoded {
                    written,
                    read,
                    error: false,
                };
            }
        }

        index = skip_ws(index);

        if index == src_len {
            if seen > 0 {
                match last_chunk {
                    LastChunk::StopBeforePartial => {
                        return Decoded {
                            written,
                            read,
                            error: false,
                        };
                    }
                    // `strict` refuses an unpadded quantum of any length.
                    LastChunk::Strict => return Decoded::fail(),
                    LastChunk::Loose => {
                        // One character is 6 bits: not a byte, so it is an error even here.
                        if seen == 1 {
                            return Decoded::fail();
                        }
                        break;
                    }
                }
            }
            return Decoded {
                written,
                read: src_len,
                error: false,
            };
        }

        let ch = src[index];
        index += 1;

        if ch == b'=' {
            if seen < 2 {
                return Decoded::fail();
            }
            index = skip_ws(index);
            if seen == 2 {
                if index == src_len {
                    if last_chunk == LastChunk::StopBeforePartial {
                        return Decoded {
                            written,
                            read,
                            error: false,
                        };
                    }
                    // One `=` after two characters pads a two-character quantum to four;
                    // stopping there is an incomplete chunk.
                    return Decoded::fail();
                }
                if src[index] == b'=' {
                    index += 1;
                    index = skip_ws(index);
                } else {
                    return Decoded::fail();
                }
            }
            // Only whitespace may follow the padding.
            if index != src_len {
                return Decoded::fail();
            }
            if last_chunk == LastChunk::Strict {
                let mask = if seen == 2 { 0xf } else { 0x3 };
                if acc & mask != 0 {
                    return Decoded::fail();
                }
            }
            break;
        }

        let v = alphabet.decode(ch);
        if v >= 64 {
            return Decoded::fail();
        }

        // Capacity, checked *before* the character is committed to `acc`: a quantum that
        // would not fit entirely is not started. `remaining == 1 && seen == 2` is the case
        // where two more bytes are needed but only one slot is left.
        let remaining = max_len - written;
        if (remaining == 1 && seen == 2) || (remaining == 2 && seen == 3) {
            return Decoded {
                written,
                read,
                error: false,
            };
        }

        acc = (acc << 6) | u32::from(v);
        seen += 1;

        if seen == 4 {
            dst[written] = (acc >> 16) as u8;
            dst[written + 1] = (acc >> 8) as u8;
            dst[written + 2] = acc as u8;
            written += 3;
            acc = 0;
            seen = 0;
            read = index;
            if written >= max_len {
                return Decoded {
                    written,
                    read,
                    error: false,
                };
            }
        }
    }

    // The leftover quantum, decoded without padding.
    if seen == 2 {
        dst[written] = (acc >> 4) as u8;
        written += 1;
    } else if seen == 3 {
        dst[written] = (acc >> 10) as u8;
        dst[written + 1] = (acc >> 2) as u8;
        written += 2;
    }
    Decoded {
        written,
        read: src_len,
        error: false,
    }
}

fn encode(src: &[u8], alphabet: Alphabet) -> String {
    let table = alphabet.encode_table();
    let mut out = String::with_capacity(src.len().div_ceil(3) * 4);
    let mut chunk = src.chunks_exact(3);
    for triple in &mut chunk {
        let v = (u32::from(triple[0]) << 16) | (u32::from(triple[1]) << 8) | u32::from(triple[2]);
        out.push(table[(v >> 18) as usize & 63] as char);
        out.push(table[(v >> 12) as usize & 63] as char);
        out.push(table[(v >> 6) as usize & 63] as char);
        out.push(table[v as usize & 63] as char);
    }
    match chunk.remainder() {
        [a] => {
            let v = u32::from(*a) << 16;
            out.push(table[(v >> 18) as usize & 63] as char);
            out.push(table[(v >> 12) as usize & 63] as char);
            out.push_str("==");
        }
        [a, b] => {
            let v = (u32::from(*a) << 16) | (u32::from(*b) << 8);
            out.push(table[(v >> 18) as usize & 63] as char);
            out.push(table[(v >> 12) as usize & 63] as char);
            out.push(table[(v >> 6) as usize & 63] as char);
            out.push('=');
        }
        _ => {}
    }
    out
}

fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

/// Hex, with the same three-part outcome as [`Decoded`] and for the same reason.
///
/// One difference from base64: an **odd total length** is an error up front, before any
/// byte is written — `throws-when-string-length-is-odd.js` checks that the target is left
/// alone, unlike an illegal character halfway through.
fn from_hex(src: &[u8], dst: &mut [u8]) -> Decoded {
    if src.len() % 2 != 0 {
        return Decoded::fail();
    }
    let mut written = 0usize;
    let mut index = 0usize;
    while index < src.len() && written < dst.len() {
        let (Some(hi), Some(lo)) = (hex_value(src[index]), hex_value(src[index + 1])) else {
            return Decoded::fail();
        };
        dst[written] = (hi << 4) | lo;
        written += 1;
        index += 2;
    }
    Decoded {
        written,
        read: index,
        error: false,
    }
}

fn to_hex(src: &[u8]) -> String {
    const DIGITS: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(src.len() * 2);
    for byte in src {
        out.push(DIGITS[(byte >> 4) as usize] as char);
        out.push(DIGITS[(byte & 0xf) as usize] as char);
    }
    out
}

/// `GetOptionsObject(options)`: `undefined` is fine, anything else must be an object.
fn options_object(interp: &mut Interp<'_>, value: &Value) -> JsResult<Option<Gc<JsObject>>> {
    match value {
        Value::Undefined => Ok(None),
        Value::Object(object) => Ok(Some(object.clone())),
        _ => Err(interp.type_error("options must be an object")),
    }
}

/// Read one string-valued option by `name`, defaulting to `fallback` when absent.
///
/// The value must be a primitive string: `Object("base64")` is a `TypeError`, and a
/// `toString` on it is never called (`option-coercion.js` counts the calls and expects
/// zero). That is why this is `IsString` and not `ToString`.
fn string_option(
    interp: &mut Interp<'_>,
    options: Option<&Gc<JsObject>>,
    name: &str,
) -> JsResult<Option<String>> {
    let Some(options) = options else {
        return Ok(None);
    };
    let Some(value) = interp.get_property(options, name)? else {
        return Ok(None);
    };
    match value {
        Value::Undefined => Ok(None),
        Value::String(text) => Ok(Some(text.to_string_lossy().into_owned())),
        _ => Err(interp.type_error(format!("expected string for {name}"))),
    }
}

fn alphabet_option(interp: &mut Interp<'_>, options: Option<&Gc<JsObject>>) -> JsResult<Alphabet> {
    match string_option(interp, options, "alphabet")?.as_deref() {
        None | Some("base64") => Ok(Alphabet::Base64),
        Some("base64url") => Ok(Alphabet::Base64Url),
        Some(_) => Err(interp.type_error("invalid alphabet")),
    }
}

fn last_chunk_option(
    interp: &mut Interp<'_>,
    options: Option<&Gc<JsObject>>,
) -> JsResult<LastChunk> {
    match string_option(interp, options, "lastChunkHandling")?.as_deref() {
        None | Some("loose") => Ok(LastChunk::Loose),
        Some("strict") => Ok(LastChunk::Strict),
        Some("stop-before-partial") => Ok(LastChunk::StopBeforePartial),
        Some(_) => Err(interp.type_error("invalid lastChunkHandling option")),
    }
}

/// The argument as a byte string, which is what the decoders walk.
///
/// A non-ASCII character becomes its UTF-8 bytes, all of which the decoders reject — the
/// same answer the reference gets by treating the input as `char *`. Two adjacent lone
/// surrogates are *not* folded into one astral character, because the bytes come from the
/// WTF-8 form rather than from a lossy `String`.
fn argument_bytes(interp: &mut Interp<'_>, value: &Value) -> JsResult<Vec<u8>> {
    let text = interp.to_js_string(value)?;
    let value = interp.string(text);
    Ok(match &value {
        Value::String(text) => text.wtf8().as_bytes().to_vec(),
        _ => unreachable!("interp.string always answers a string"),
    })
}

/// `RequireInternalSlot(this, [[TypedArrayName]] = "Uint8Array")`, then the bytes.
///
/// The receiver check is a `TypeError` for every other typed array — `Int8Array` included —
/// which is what `receiver-not-uint8array.js` pins; it is *not* a length check.
fn uint8_view(interp: &Interp<'_>, this: &Value) -> JsResult<Gc<JsObject>> {
    let Some(object) = this.as_object() else {
        return Err(interp.type_error("not a Uint8Array"));
    };
    let Some((_, element, _, _)) = object.typed_array_parts() else {
        return Err(interp.type_error("not a Uint8Array"));
    };
    if element != ElementType::Uint8 {
        return Err(interp.type_error("not a Uint8Array"));
    }
    Ok(object.clone())
}

/// The view's `(byteOffset, byteLength)` **after** the detached check.
///
/// Deliberately a separate call from [`uint8_view`]: the reference's
/// `get_uint8array_bytes` runs *after* every option has been read, and a getter there can
/// detach the buffer. `toBase64/detached-buffer.js` does exactly that and counts the getter
/// calls, so merging the two checks would answer `"Zm9v"` where the spec demands a
/// `TypeError`.
fn uint8_bytes(interp: &Interp<'_>, object: &Gc<JsObject>) -> JsResult<(usize, usize)> {
    let Some((_, _, offset, length)) = object.typed_array_parts() else {
        return Err(interp.type_error("not a Uint8Array"));
    };
    let out_of_bounds = object
        .typed_array_geometry()
        .is_some_and(|(_, _, _, _, out_of_bounds)| out_of_bounds);
    if out_of_bounds {
        return Err(interp.type_error("the buffer was detached or resized out of bounds"));
    }
    Ok((offset, length))
}

/// Copy a range of the buffer's bytes out.
fn read_bytes(object: &Gc<JsObject>, offset: usize, length: usize) -> Vec<u8> {
    let Some(storage) = object
        .typed_array_parts()
        .and_then(|(buffer, _, _, _)| buffer.array_buffer_storage())
    else {
        return Vec::new();
    };
    let storage = storage.borrow();
    storage
        .bytes
        .get(offset..offset + length)
        .map(<[u8]>::to_vec)
        .unwrap_or_default()
}

/// Run `f` over a mutable window of the buffer's bytes.
///
/// The window is copied out, edited, and copied back rather than borrowed in place: the
/// decoder is plain Rust with no script callbacks inside it, but holding a `RefMut` on the
/// buffer across an `interp` call would be a panic waiting for the next edit, and this is
/// three `memcpy`s over a typed array.
fn with_bytes<R>(
    object: &Gc<JsObject>,
    offset: usize,
    length: usize,
    f: impl FnOnce(&mut [u8]) -> R,
) -> R {
    let mut scratch = read_bytes(object, offset, length);
    let answer = f(&mut scratch);
    if let Some(storage) = object
        .typed_array_parts()
        .and_then(|(buffer, _, _, _)| buffer.array_buffer_storage())
        && let Some(target) = storage.borrow_mut().bytes.get_mut(offset..offset + length)
    {
        target.copy_from_slice(&scratch);
    }
    answer
}

/// `Uint8Array.fromBase64(string[, options])`.
fn from_base64_method(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    // The string check comes *before* the options: `fromBase64(1, "not an object")` is a
    // `TypeError` either way, but the ordering decides which message.
    if !matches!(arg(args, 0), Value::String(_)) {
        return Err(interp.type_error("expected string"));
    }
    let options = options_object(interp, &arg(args, 1))?;
    let alphabet = alphabet_option(interp, options.as_ref())?;
    let last_chunk = last_chunk_option(interp, options.as_ref())?;
    let src = argument_bytes(interp, &arg(args, 0))?;
    // Capacity: a four-character quantum yields at most three bytes, and a partial quantum
    // can add two more. Deliberately generous — the decoder stops at what it needs.
    let mut dst = vec![0u8; (src.len() / 4) * 3 + 3];
    let decoded = from_base64(&src, &mut dst, alphabet, last_chunk);
    if decoded.error {
        return Err(Signal::Throw(
            interp.make_error("SyntaxError", "invalid base64 string"),
        ));
    }
    dst.truncate(decoded.written);
    let view = new_uint8(interp, &dst)?;
    Ok(Value::Object(view))
}

/// `Uint8Array.fromHex(string)`.
fn from_hex_method(interp: &mut Interp<'_>, _this: Value, args: &[Value]) -> JsResult<Value> {
    if !matches!(arg(args, 0), Value::String(_)) {
        return Err(interp.type_error("expected string"));
    }
    let src = argument_bytes(interp, &arg(args, 0))?;
    let mut dst = vec![0u8; src.len() / 2 + 1];
    let decoded = from_hex(&src, &mut dst);
    if decoded.error {
        return Err(Signal::Throw(
            interp.make_error("SyntaxError", "invalid hex string"),
        ));
    }
    dst.truncate(decoded.written);
    let view = new_uint8(interp, &dst)?;
    Ok(Value::Object(view))
}

/// A fresh `Uint8Array` holding a copy of `bytes`, with the intrinsic as its prototype.
///
/// `fromBase64`/`fromHex` are specified to answer a plain `Uint8Array` — not a species
/// result, and not a subclass — so this builds the buffer directly rather than going through
/// the constructor.
fn new_uint8(interp: &mut Interp<'_>, bytes: &[u8]) -> JsResult<Gc<JsObject>> {
    let buffer_proto = interp
        .realm
        .array_buffer_proto
        .clone()
        .unwrap_or_else(|| interp.realm.object_proto.clone());
    let buffer = interp.new_object(Some(buffer_proto));
    buffer.set_array_buffer(std::rc::Rc::new(std::cell::RefCell::new(
        crate::object::BufferStorage::fixed(bytes.to_vec()),
    )));
    let proto = interp
        .realm
        .typed_array_protos
        .get(ElementType::Uint8 as usize)
        .cloned()
        .unwrap_or_else(|| interp.realm.object_proto.clone());
    let view = interp.new_object(Some(proto));
    view.set_typed_array(
        buffer,
        ElementType::Uint8,
        0,
        crate::object::ViewLength::Fixed(bytes.len()),
    );
    Ok(view)
}

/// `u8.toBase64([options])`.
fn to_base64(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = uint8_view(interp, &this)?;
    let options = options_object(interp, &arg(args, 0))?;
    let alphabet = alphabet_option(interp, options.as_ref())?;
    let omit_padding = match &options {
        Some(options) => interp
            .get_property(options, "omitPadding")?
            .is_some_and(|value| value.to_boolean()),
        None => false,
    };
    let (offset, length) = uint8_bytes(interp, &object)?;
    let bytes = read_bytes(&object, offset, length);
    let mut text = encode(&bytes, alphabet);
    if omit_padding {
        while text.ends_with('=') {
            text.pop();
        }
    }
    Ok(interp.string(text))
}

/// `u8.toHex()`.
fn to_hex_method(interp: &mut Interp<'_>, this: Value, _args: &[Value]) -> JsResult<Value> {
    let object = uint8_view(interp, &this)?;
    let (offset, length) = uint8_bytes(interp, &object)?;
    let bytes = read_bytes(&object, offset, length);
    Ok(interp.string(to_hex(&bytes)))
}

/// `u8.setFromBase64(string[, options])` → `{read, written}`.
fn set_from_base64(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = uint8_view(interp, &this)?;
    if !matches!(arg(args, 0), Value::String(_)) {
        return Err(interp.type_error("expected string"));
    }
    let options = options_object(interp, &arg(args, 1))?;
    let alphabet = alphabet_option(interp, options.as_ref())?;
    let last_chunk = last_chunk_option(interp, options.as_ref())?;
    let src = argument_bytes(interp, &arg(args, 0))?;
    let (offset, length) = uint8_bytes(interp, &object)?;
    let decoded = with_bytes(&object, offset, length, |dst| {
        from_base64(&src, dst, alphabet, last_chunk)
    });
    // The bytes decoded before the failure stay in the target — that is specified, and
    // `writes-up-to-error.js` reads them back.
    if decoded.error {
        return Err(Signal::Throw(
            interp.make_error("SyntaxError", "invalid base64 string"),
        ));
    }
    Ok(read_written(interp, decoded.read, decoded.written))
}

/// `u8.setFromHex(string)` → `{read, written}`.
fn set_from_hex(interp: &mut Interp<'_>, this: Value, args: &[Value]) -> JsResult<Value> {
    let object = uint8_view(interp, &this)?;
    if !matches!(arg(args, 0), Value::String(_)) {
        return Err(interp.type_error("expected string"));
    }
    let src = argument_bytes(interp, &arg(args, 0))?;
    let (offset, length) = uint8_bytes(interp, &object)?;
    let decoded = with_bytes(&object, offset, length, |dst| from_hex(&src, dst));
    if decoded.error {
        return Err(Signal::Throw(
            interp.make_error("SyntaxError", "invalid hex string"),
        ));
    }
    Ok(read_written(interp, decoded.read, decoded.written))
}

fn read_written(interp: &mut Interp<'_>, read: usize, written: usize) -> Value {
    let result = interp.new_object(Some(interp.realm.object_proto.clone()));
    result.define_data("read", Value::Int(read as i32));
    result.define_data("written", Value::Int(written as i32));
    Value::Object(result)
}

/// Install the six methods on `Uint8Array` and its prototype.
///
/// Called from `typedarray::install` after the per-type loop, because the statics live on
/// one constructor out of nine and the prototype methods on one prototype out of nine —
/// putting them in the shared `%TypedArray%` would make `Uint16Array.fromHex` exist.
pub fn install(interp: &mut Interp<'_>, constructor: &Gc<JsObject>, proto: &Gc<JsObject>) {
    for (name, length, func) in [
        (
            "fromBase64",
            1,
            from_base64_method as crate::object::NativeFn,
        ),
        ("fromHex", 1, from_hex_method),
    ] {
        define_method(constructor, name, length, func, interp);
    }
    for (name, length, func) in [
        ("toBase64", 0, to_base64 as crate::object::NativeFn),
        ("toHex", 0, to_hex_method),
        ("setFromBase64", 1, set_from_base64),
        ("setFromHex", 1, set_from_hex),
    ] {
        define_method(proto, name, length, func, interp);
    }
    let _ = Property::default();
}

use crate::value::Value;