Skip to main content

nodejs/stdlib/
buffer.rs

1//! Node `Buffer` (global + `require('buffer').Buffer`). A Buffer is a plain
2//! object tagged `@@native = "Buffer"` whose bytes live in a hidden `@@bytes`
3//! array SHARED with its `ArrayBuffer` (`@@buffer`, read as `buf.buffer`); the
4//! Buffer is a window (`byteOffset`/`length`) onto it, so every reader goes
5//! through `window_bytes_h`.
6
7use super::{arg_str, from_base64, from_hex, to_base64, to_hex};
8use crate::host::{with_host, JsObj};
9use fusevm::Value;
10use indexmap::IndexMap;
11
12/// The statics on `Buffer`. node v26.7.0's
13/// `Object.getOwnPropertyNames(Buffer).filter(n => typeof Buffer[n] === 'function')`
14/// reports eleven; this is ten of them.
15///
16/// Three used to be missing, and the gap was not cosmetic: `safe-buffer`
17/// feature-detects `Buffer.from && Buffer.alloc && Buffer.allocUnsafe &&
18/// Buffer.allocUnsafeSlow` and, on a miss, exports its own legacy `SafeBuffer`
19/// wrapper instead of the real `buffer` module. express's `res.send` takes
20/// `Buffer` from `safe-buffer`, so every `res.json()` went through that wrapper
21/// and died on its `Buffer(arg, …)` call.
22///
23/// The eleventh, `copyBytesFrom`, is deliberately absent rather than faked. It
24/// copies a typed array's raw BYTES with `offset`/`length` counted in ELEMENTS,
25/// which needs a per-kind little-endian serializer for all nine element kinds
26/// (typed arrays are stored here as a `@@elems` array of NUMBERS, not bytes).
27/// Listing it without that would advertise a method the dispatcher cannot
28/// implement — the exact drift this list exists to prevent.
29pub const STATIC_METHODS: &[&str] = &[
30    "from",
31    "copyBytesFrom",
32    "alloc",
33    "allocUnsafe",
34    "allocUnsafeSlow",
35    "concat",
36    "isBuffer",
37    "isEncoding",
38    "byteLength",
39    "compare",
40    "of",
41];
42
43/// The methods a `Buffer` instance answers — the surface `instance_call`
44/// dispatches, and the set installed as `@proto:Buffer:<m>` thunks on the real
45/// `Buffer.prototype` object.
46pub const INSTANCE_METHODS: &[&str] = &[
47    "toString",
48    "set",
49    "toJSON",
50    "equals",
51    "slice",
52    "subarray",
53    "readUInt8",
54    "includes",
55    "indexOf",
56    "lastIndexOf",
57    "write",
58    "copy",
59    "fill",
60    "compare",
61    "readUInt16BE",
62    "readUInt16LE",
63    "writeUInt8",
64    "writeInt8",
65    "writeInt16BE",
66    "writeInt16LE",
67    "readFloatBE",
68    "readFloatLE",
69    "writeFloatBE",
70    "writeFloatLE",
71    "readDoubleBE",
72    "readDoubleLE",
73    "writeDoubleBE",
74    "writeDoubleLE",
75    "readBigInt64BE",
76    "readBigInt64LE",
77    "readBigUInt64BE",
78    "readBigUInt64LE",
79    "writeBigInt64BE",
80    "writeBigInt64LE",
81    "writeBigUInt64BE",
82    "writeBigUInt64LE",
83    "readIntBE",
84    "readIntLE",
85    "readUIntBE",
86    "readUIntLE",
87    "writeIntBE",
88    "writeIntLE",
89    "writeUIntBE",
90    "writeUIntLE",
91    "writeUInt16BE",
92    "writeUInt16LE",
93    "readUInt32BE",
94    "readUInt32LE",
95    "readInt8",
96    "readInt16BE",
97    "readInt16LE",
98    "readInt32BE",
99    "readInt32LE",
100    "writeUInt32BE",
101    "writeUInt32LE",
102    "writeInt32BE",
103    "writeInt32LE",
104    "at",
105    "values",
106    "keys",
107    "entries",
108    "swap16",
109    "swap32",
110    "swap64",
111];
112
113/// Free functions of the `buffer` module itself (`require('buffer').atob`, …), as
114/// opposed to the `Buffer` constructor's static methods above. Needs the parent
115/// `"buffer"` routing arm (see final report).
116pub const MODULE_METHODS: &[&str] = &["atob", "btoa", "isAscii", "isLatin1", "isUtf8", "transcode"];
117
118/// The data members of the `buffer` module, next to its functions.
119/// `MAX_STRING_LENGTH` is V8's `String::kMaxLength` on a 64-bit build, the
120/// figure node reports; node-js does not itself cap a string at it.
121pub fn module_constant(name: &str) -> Option<Value> {
122    const MAX_STRING_LENGTH: f64 = 536_870_888.0;
123    match name {
124        "kMaxLength" => Some(Value::Float(K_MAX_LENGTH)),
125        "kStringMaxLength" => Some(Value::Float(MAX_STRING_LENGTH)),
126        "INSPECT_MAX_BYTES" => Some(Value::Float(50.0)),
127        "constants" => Some(with_host(|h| {
128            let mut m = IndexMap::new();
129            m.insert("MAX_LENGTH".into(), Value::Float(K_MAX_LENGTH));
130            m.insert("MAX_STRING_LENGTH".into(), Value::Float(MAX_STRING_LENGTH));
131            h.new_object(m)
132        })),
133        _ => None,
134    }
135}
136
137/// `atob`/`btoa`'s one argument: absent is `ERR_MISSING_ARGS`, anything else
138/// goes through `ToString` (so `btoa(undefined)` encodes `"undefined"`, a
139/// `toString` method runs, and a symbol throws).
140fn string_input(args: &[Value]) -> Result<String, String> {
141    let v = args.first().ok_or_else(|| {
142        crate::host::coded_error(
143            "TypeError",
144            "ERR_MISSING_ARGS",
145            "The \"input\" argument must be specified",
146        )
147    })?;
148    let s = crate::host::to_string_value(v)?;
149    Ok(with_host(|h| h.str_of(&s)))
150}
151
152/// The bytes `isAscii`/`isUtf8` inspect: an `ArrayBuffer` or a typed array
153/// (a Buffer is one), read as the bytes it views. A string, a number or a
154/// `DataView` is `ERR_INVALID_ARG_TYPE` — they were answered as if they were
155/// byte sequences.
156fn validated_bytes(args: &[Value]) -> Result<Vec<u8>, String> {
157    let v = args.first().cloned().unwrap_or(Value::Undef);
158    match super::native_tag(&v).as_deref() {
159        Some("Buffer" | "TypedArray" | "ArrayBuffer") => Ok(view_bytes(&v).unwrap_or_default()),
160        _ => Err(crate::host::coded_error(
161            "TypeError",
162            "ERR_INVALID_ARG_TYPE",
163            &format!(
164                "The \"input\" argument must be an instance of ArrayBuffer, Buffer, or TypedArray. Received {}",
165                super::received_desc(&v)
166            ),
167        )),
168    }
169}
170
171/// WHATWG forgiving-base64 decode, with the two failures node's `atob`
172/// distinguishes: a character outside the alphabet (or misplaced padding) is
173/// "Invalid character", and a data length of `4n + 1` is "not correctly
174/// encoded". ASCII whitespace is skipped, up to two trailing `=` are allowed
175/// when they complete a quantum, and non-zero trailing bits are accepted.
176fn forgiving_base64(s: &str) -> Result<Vec<u8>, String> {
177    let invalid = || crate::host::dom_error("InvalidCharacterError", "Invalid character");
178    let chars: Vec<char> = s
179        .chars()
180        .filter(|c| !matches!(c, '\t' | '\n' | '\u{c}' | '\r' | ' '))
181        .collect();
182    let pad = chars.iter().rev().take_while(|c| **c == '=').count();
183    let data = &chars[..chars.len() - pad];
184    let mut vals = Vec::with_capacity(data.len());
185    for c in data {
186        match B64_ALPHABET.find(*c) {
187            Some(i) => vals.push(i as u32),
188            None => return Err(invalid()),
189        }
190    }
191    if pad > 2 {
192        return Err(invalid());
193    }
194    if vals.len() % 4 == 1 {
195        return Err(crate::host::dom_error(
196            "InvalidCharacterError",
197            "The string to be decoded is not correctly encoded.",
198        ));
199    }
200    if pad > 0 && chars.len() % 4 != 0 {
201        return Err(invalid());
202    }
203    let mut out = Vec::with_capacity(vals.len() * 3 / 4);
204    for q in vals.chunks(4) {
205        let n = q
206            .iter()
207            .enumerate()
208            .fold(0u32, |n, (i, v)| n | v << (18 - 6 * i));
209        out.extend_from_slice(&n.to_be_bytes()[1..q.len()]);
210    }
211    Ok(out)
212}
213
214const B64_ALPHABET: &str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
215
216/// Dispatch a `require('buffer').<method>` free function.
217pub fn module_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
218    Some(match method {
219        // atob: forgiving base64 → a binary (latin1) string.
220        "atob" => (|| {
221            let bytes = forgiving_base64(&string_input(args)?)?;
222            let bin: String = bytes.iter().map(|b| *b as char).collect();
223            Ok(with_host(|h| h.new_str(bin)))
224        })(),
225        // btoa: a binary string → base64. A code point above U+00FF has no
226        // octet, so it is an `InvalidCharacterError` — it used to encode the
227        // character's low byte.
228        "btoa" => (|| {
229            let s = string_input(args)?;
230            let bytes = s
231                .chars()
232                .map(|c| u8::try_from(c as u32))
233                .collect::<Result<Vec<u8>, _>>()
234                .map_err(|_| {
235                    crate::host::dom_error("InvalidCharacterError", "Invalid character")
236                })?;
237            Ok(with_host(|h| h.new_str(to_base64(&bytes))))
238        })(),
239        "isAscii" => validated_bytes(args).map(|b| Value::Bool(b.is_ascii())),
240        "isUtf8" => validated_bytes(args).map(|b| Value::Bool(std::str::from_utf8(&b).is_ok())),
241        // isLatin1 takes a STRING in node v26: whether every code unit fits a
242        // byte.
243        "isLatin1" => {
244            let v = args.first().cloned().unwrap_or(Value::Undef);
245            match with_host(|h| h.as_str(&v)) {
246                Some(s) => Ok(Value::Bool(s.chars().all(|c| (c as u32) < 0x100))),
247                None => Err(crate::host::invalid_arg_type(
248                    "input", "argument", "string", &v,
249                )),
250            }
251        }
252        // transcode(source, fromEnc, toEnc): re-encode bytes between utf8/latin1/
253        // ascii/utf16le (best-effort; hex/base64 are not transcode encodings).
254        "transcode" => {
255            let src = input_bytes(args.first());
256            let from = arg_str(args, 1);
257            let to = arg_str(args, 2);
258            let s = bytes_to_string(&src, &from);
259            let out = string_to_bytes(&s, &to);
260            Ok(from_bytes(&out))
261        }
262        _ => return None,
263    })
264}
265
266/// Raw bytes of a Buffer/Blob arg, or the UTF-8 bytes of a string arg.
267fn input_bytes(v: Option<&Value>) -> Vec<u8> {
268    match v {
269        None => Vec::new(),
270        Some(v) => {
271            if let Some(s) = with_host(|h| h.as_str(v)) {
272                s.into_bytes()
273            } else {
274                bytes_of(v)
275            }
276        }
277    }
278}
279
280/// Interpret bytes under `enc` as a Rust string (for `transcode`).
281fn bytes_to_string(bytes: &[u8], enc: &str) -> String {
282    match enc.to_ascii_lowercase().as_str() {
283        "ascii" | "latin1" | "binary" => bytes.iter().map(|b| *b as char).collect(),
284        "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
285            let units: Vec<u16> = bytes
286                .chunks_exact(2)
287                .map(|c| u16::from_le_bytes([c[0], c[1]]))
288                .collect();
289            String::from_utf16_lossy(&units)
290        }
291        _ => String::from_utf8_lossy(bytes).into_owned(),
292    }
293}
294
295/// Encode a Rust string into `enc` bytes (for `transcode`).
296///
297/// `transcode` is ICU, not `Buffer.from`, so its `ascii` arm SUBSTITUTES rather
298/// than truncates: node renders `transcode(Buffer.from('aÿ'),'utf8','ascii')` as
299/// `61 3f` — an unrepresentable character becomes `?`.
300fn string_to_bytes(s: &str, enc: &str) -> Vec<u8> {
301    match enc.to_ascii_lowercase().as_str() {
302        "ascii" => s
303            .chars()
304            .map(|c| if c.is_ascii() { c as u8 } else { b'?' })
305            .collect(),
306        "latin1" | "binary" => s.chars().map(|c| c as u32 as u8).collect(),
307        "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
308            s.encode_utf16().flat_map(|u| u.to_le_bytes()).collect()
309        }
310        _ => s.as_bytes().to_vec(),
311    }
312}
313
314// ── Blob / File ──────────────────────────────────────────────────────────────
315//
316// A `Blob` is a native object tagged `@@native = "Blob"` (a `File` is `"File"`)
317// whose bytes live in `@@bytes`, with `size`/`type` (and `File`'s `name`/
318// `lastModified`) as readable data properties. Needs parent construct/instance
319// wiring (see final report).
320
321/// Concatenate one Blob-part's bytes: a string contributes its UTF-8 bytes, a
322/// Buffer/Blob its raw bytes.
323fn part_bytes(v: &Value) -> Vec<u8> {
324    match with_host(|h| h.as_str(v)) {
325        Some(s) => s.into_bytes(),
326        None => bytes_of(v),
327    }
328}
329
330/// Gather the byte payload from a `BlobPart[]` (the first constructor argument).
331fn gather_parts(parts: &Value) -> Vec<u8> {
332    let items = with_host(|h| match h.get(parts) {
333        Some(JsObj::Array(it)) => it.clone(),
334        _ => Vec::new(),
335    });
336    let mut out = Vec::new();
337    for it in &items {
338        out.extend(part_bytes(it));
339    }
340    out
341}
342
343/// The `type` string from an options bag (`{ type }`), or "".
344fn opt_type(opts: Option<&Value>) -> String {
345    match opts {
346        Some(v) => with_host(|h| match h.get(v) {
347            Some(JsObj::Object(p)) => p.get("type").map(|x| h.str_of(x)).unwrap_or_default(),
348            _ => String::new(),
349        }),
350        None => String::new(),
351    }
352}
353
354/// Build a `Blob`/`File` native object with the shared `@@bytes`/`size`/`type`
355/// fields; `File` adds `name`/`lastModified`.
356fn build_blob(tag: &str, bytes: &[u8], typ: &str, extra: IndexMap<String, Value>) -> Value {
357    with_host(|h| {
358        let arr = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
359        let mut m = IndexMap::new();
360        m.insert("@@native".into(), h.new_str(tag.to_string()));
361        m.insert("@@bytes".into(), arr);
362        m.insert("size".into(), Value::Float(bytes.len() as f64));
363        m.insert("type".into(), h.new_str(typ.to_string()));
364        for (k, v) in extra {
365            m.insert(k, v);
366        }
367        h.new_object(m)
368    })
369}
370
371/// `new Blob(parts[, options])`.
372pub fn construct_blob(args: &[Value]) -> Result<Value, String> {
373    let bytes = gather_parts(&args.first().cloned().unwrap_or(Value::Undef));
374    let typ = opt_type(args.get(1));
375    Ok(build_blob("Blob", &bytes, &typ, IndexMap::new()))
376}
377
378/// `new File(parts, name[, options])`.
379pub fn construct_file(args: &[Value]) -> Result<Value, String> {
380    let bytes = gather_parts(&args.first().cloned().unwrap_or(Value::Undef));
381    let name = arg_str(args, 1);
382    let typ = opt_type(args.get(2));
383    // lastModified: options.lastModified or 0.
384    let last_modified = args
385        .get(2)
386        .map(|v| {
387            with_host(|h| match h.get(v) {
388                Some(JsObj::Object(p)) => {
389                    p.get("lastModified").map(|x| h.to_number(x)).unwrap_or(0.0)
390                }
391                _ => 0.0,
392            })
393        })
394        .unwrap_or(0.0);
395    let extra = with_host(|h| {
396        let mut m = IndexMap::new();
397        m.insert("name".to_string(), h.new_str(name));
398        m.insert("lastModified".to_string(), Value::Float(last_modified));
399        m
400    });
401    Ok(build_blob("File", &bytes, &typ, extra))
402}
403
404/// Method names for `Blob`/`File` instances (parent `instance_has_method`).
405pub const BLOB_METHODS: &[&str] = &["text", "arrayBuffer", "bytes", "slice"];
406
407/// `Blob`/`File` instance methods. `text`/`arrayBuffer`/`bytes` return already-
408/// resolved Promises (Node's async accessors); `slice` returns a new `Blob`.
409/// `arrayBuffer`/`bytes` resolve with a `Buffer` (this runtime's byte container)
410/// rather than a bare `ArrayBuffer`/`Uint8Array`.
411pub fn blob_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
412    let bytes = bytes_of(recv);
413    match method {
414        "text" => {
415            let s = String::from_utf8_lossy(&bytes).into_owned();
416            let sv = with_host(|h| h.new_str(s));
417            Ok(crate::host::promise_of(&sv))
418        }
419        "arrayBuffer" | "bytes" => {
420            let buf = from_bytes(&bytes);
421            Ok(crate::host::promise_of(&buf))
422        }
423        "slice" => {
424            let (s, e) = slice_bounds(args, bytes.len());
425            let typ = if args.len() > 2 {
426                arg_str(args, 2)
427            } else {
428                String::new()
429            };
430            Ok(build_blob("Blob", &bytes[s..e], &typ, IndexMap::new()))
431        }
432        _ => Err(crate::host::type_error(&format!(
433            "blob.{method} is not a function"
434        ))),
435    }
436}
437
438/// A Buffer that is a WINDOW onto an existing `ArrayBuffer`'s store, sharing
439/// its bytes rather than copying them.
440pub fn share_array_buffer(ab: &Value, off: usize, len: usize) -> Value {
441    let store = crate::stdlib::typedarray::buffer_store(ab);
442    with_host(|h| {
443        let mut m = IndexMap::new();
444        m.insert("@@native".into(), h.new_str("Buffer"));
445        m.insert(
446            "@@bytes".into(),
447            store.unwrap_or_else(|| h.new_array(Vec::new())),
448        );
449        m.insert("@@buffer".into(), ab.clone());
450        m.insert("buffer".into(), ab.clone());
451        m.insert("length".into(), Value::Float(len as f64));
452        m.insert("byteLength".into(), Value::Float(len as f64));
453        m.insert("byteOffset".into(), Value::Float(off as f64));
454        m.insert("BYTES_PER_ELEMENT".into(), Value::Float(1.0));
455        let obj = h.new_object(m);
456        h.ensure_native_protos();
457        if let Some(p) = h.native_proto("Buffer") {
458            h.set_proto(&obj, p);
459        }
460        for k in [
461            "buffer",
462            "length",
463            "byteLength",
464            "byteOffset",
465            "BYTES_PER_ELEMENT",
466        ] {
467            h.hide_prop(&obj, k);
468        }
469        obj
470    })
471}
472
473/// Build a Buffer value from raw bytes.
474///
475/// Every Buffer is a VIEW: the bytes live in an `ArrayBuffer` (its `.buffer`)
476/// and the Buffer shares that store. It used to own a private array with no
477/// buffer behind it, so `buf.buffer` threw on every Buffer node-js made.
478pub fn from_bytes(bytes: &[u8]) -> Value {
479    let arr = with_host(|h| h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect()));
480    let ab = crate::stdlib::typedarray::array_buffer_over(arr);
481    share_array_buffer(&ab, 0, bytes.len())
482}
483
484// ── the allocation pool (`lib/buffer.js`) ────────────────────────────────────
485//
486// Node carves small Buffers out of one shared ArrayBuffer: `Buffer.from` of a
487// string or an array-like, `Buffer.allocUnsafe` and `Buffer.concat` take a
488// slice of `allocPool` and advance `poolOffset` past it, 8-byte aligned; a new
489// pool is made when the slice does not fit. So `buf.byteOffset` is the slice's
490// place in the pool, `buf.buffer.byteLength` is the pool's (64 KiB plus the
491// 64 bytes `createUnsafeAlignedBuffer` over-allocates), and `buf.buffer
492// .transfer()` throws, the pool being marked untransferable. `Buffer.alloc`,
493// `allocUnsafeSlow` and `Buffer.of` never use the pool. `poolBase` — where the
494// aligned pool starts inside its ArrayBuffer — depends on a real address in
495// node and is 0 here, which is what node reports whenever the backing store
496// is already 64-byte aligned.
497
498/// `kPoolAlignment`, and so the padding `createUnsafeAlignedBuffer` adds.
499const POOL_PADDING: usize = 64;
500
501/// `Buffer.poolSize` as a script currently sees it (it is writable).
502fn pool_size_value() -> f64 {
503    let set = with_host(|h| h.builtin_static("Buffer", "poolSize"));
504    match set {
505        Some(v) => with_host(|h| h.to_number(&v)),
506        None => 65536.0,
507    }
508}
509
510/// `Buffer.poolSize >>> 1`, the size below which a Buffer is pooled.
511fn pool_half() -> usize {
512    let n = pool_size_value();
513    let u = if n.is_finite() {
514        n.trunc().rem_euclid(4294967296.0) as u32
515    } else {
516        0
517    };
518    (u >> 1) as usize
519}
520
521/// `createPool()`: a fresh untransferable pool of `Buffer.poolSize` bytes.
522fn create_pool() {
523    let size = pool_size_value().max(0.0) as usize;
524    let arr = with_host(|h| h.new_array(vec![Value::Float(0.0); size + POOL_PADDING]));
525    let ab = crate::stdlib::typedarray::array_buffer_over(arr);
526    crate::stdlib::typedarray::mark_untransferable(&ab);
527    with_host(|h| h.buffer_pool = Some((ab, size, 0)));
528}
529
530/// A Buffer of `bytes` sliced out of the pool, after checking that `reserve`
531/// bytes fit (`fromStringFast` checks its upper estimate, not the length it
532/// ends up writing).
533fn pool_slice(reserve: usize, bytes: &[u8]) -> Value {
534    let fits = with_host(
535        |h| matches!(h.buffer_pool, Some((_, size, off)) if reserve <= size - off.min(size)),
536    );
537    if !fits {
538        create_pool();
539    }
540    let Some((ab, size, off)) = with_host(|h| h.buffer_pool.clone()) else {
541        return from_bytes(bytes);
542    };
543    if let Some(store) = crate::stdlib::typedarray::buffer_store(&ab) {
544        with_host(|h| {
545            if let Some(JsObj::Array(items)) = h.get_mut(&store) {
546                for (i, b) in bytes.iter().enumerate() {
547                    items[off + i] = Value::Float(*b as f64);
548                }
549            }
550        });
551    }
552    let buf = share_array_buffer(&ab, off, bytes.len());
553    // `alignPool()`: the next slice starts on an 8-byte boundary.
554    let next = (off + bytes.len() + 7) & !7;
555    with_host(|h| h.buffer_pool = Some((ab, size, next)));
556    buf
557}
558
559/// `allocate(size)` / `fromArrayLike`: a pooled Buffer holding `bytes` when it
560/// is non-empty and under half the pool size, an own allocation otherwise.
561pub fn pooled(bytes: &[u8]) -> Value {
562    if bytes.is_empty() || bytes.len() >= pool_half() {
563        return from_bytes(bytes);
564    }
565    pool_slice(bytes.len(), bytes)
566}
567
568/// `fromString` / `fromStringFast`: `s` encoded under `enc`, pooled when its
569/// length estimate (four bytes per UTF-16 unit, or the real byte length once
570/// that estimate reaches half the pool) is under half the pool size.
571fn pooled_string(s: &str, enc: &str) -> Value {
572    let bytes = decode_str(s, enc);
573    if s.is_empty() {
574        return from_bytes(&bytes);
575    }
576    let max = pool_half();
577    let units = s.encode_utf16().count();
578    if units >= max {
579        return from_bytes(&bytes);
580    }
581    let mut estimate = units * 4;
582    if estimate >= max {
583        estimate = bytes.len();
584    }
585    if estimate >= max {
586        return from_bytes(&bytes);
587    }
588    pool_slice(estimate, &bytes)
589}
590
591/// A Buffer's window onto its byte store as `(byteOffset, length)`.
592///
593/// A Buffer built from its own bytes spans the whole store, so this is
594/// `(0, len)` and every accessor behaves as it did. One built over an
595/// `ArrayBuffer` SHARES that buffer's array and may start partway into it, which
596/// is what makes `Buffer.from(ab, 2, 2)` alias rather than copy.
597fn window(recv: &Value) -> (usize, usize) {
598    with_host(|h| match h.get(recv) {
599        Some(JsObj::Object(p)) => window_h(h, p),
600        _ => (0, 0),
601    })
602}
603
604/// `window` over a Buffer's own properties, with the host borrow held.
605pub fn window_h(h: &crate::host::JsHost, p: &IndexMap<String, Value>) -> (usize, usize) {
606    let off = p.get("byteOffset").map(|o| h.to_number(o)).unwrap_or(0.0) as usize;
607    let store = match p.get("@@bytes").and_then(|v| h.get(v)) {
608        Some(JsObj::Array(items)) => items.len(),
609        _ => 0,
610    };
611    let len = p
612        .get("length")
613        .map(|l| h.to_number(l) as usize)
614        .unwrap_or(store);
615    (off.min(store), len.min(store.saturating_sub(off)))
616}
617
618/// The bytes a Buffer's window covers, with the host borrow held. Every reader
619/// of a Buffer's bytes goes through here: the store is SHARED with its
620/// `ArrayBuffer` and with every other view over it, so reading the whole store
621/// returns bytes that are not the Buffer's.
622pub fn window_bytes_h(h: &crate::host::JsHost, p: &IndexMap<String, Value>) -> Vec<u8> {
623    let (off, len) = window_h(h, p);
624    match p.get("@@bytes").and_then(|v| h.get(v)) {
625        Some(JsObj::Array(items)) => items[off..off + len]
626            .iter()
627            .map(|v| h.to_number(v) as u8)
628            .collect(),
629        _ => Vec::new(),
630    }
631}
632
633fn bytes_of(recv: &Value) -> Vec<u8> {
634    with_host(|h| match h.get(recv) {
635        Some(JsObj::Object(p)) => window_bytes_h(h, p),
636        _ => Vec::new(),
637    })
638}
639
640/// The handle of `recv`'s hidden `@@bytes` array, without copying it.
641fn bytes_handle(recv: &Value) -> Option<Value> {
642    with_host(|h| match h.get(recv) {
643        Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
644        _ => None,
645    })
646}
647
648/// `buf[i]` — the byte at an integer index, or `undefined` past the end.
649///
650/// Reads through to the single element. Materialising the whole buffer here
651/// (the old `bytes_of` call) made one indexed read O(len), so any loop over a
652/// Buffer — including a request body arriving through `express.json()` — cost
653/// O(len^2).
654pub fn byte_get(recv: &Value, index: &str) -> Value {
655    let i: usize = match index.parse() {
656        Ok(i) => i,
657        Err(_) => return Value::Undef,
658    };
659    let arr = match bytes_handle(recv) {
660        Some(a) => a,
661        None => return Value::Undef,
662    };
663    let (off, len) = window(recv);
664    if i >= len {
665        return Value::Undef;
666    }
667    with_host(|h| match h.get(&arr) {
668        Some(JsObj::Array(items)) => match items.get(off + i) {
669            Some(v) => Value::Float(h.to_number(v)),
670            None => Value::Undef,
671        },
672        _ => Value::Undef,
673    })
674}
675
676/// `buf[i] = n` — write one byte (truncated to 8 bits, as a Uint8Array does).
677/// Returns whether `recv` was a Buffer and the write landed.
678///
679/// Writes the single element in place; the old path copied the buffer out,
680/// changed one byte, and wrote every byte back.
681pub fn byte_set(recv: &Value, index: &str, val: &Value) -> bool {
682    if super::native_tag(recv).as_deref() != Some("Buffer") {
683        return false;
684    }
685    let i: usize = match index.parse() {
686        Ok(i) => i,
687        Err(_) => return false,
688    };
689    let arr = match bytes_handle(recv) {
690        Some(a) => a,
691        None => return false,
692    };
693    let b = with_host(|h| h.to_number(val)) as i64 as u8;
694    // Indexed through the Buffer's WINDOW, so one sharing an ArrayBuffer writes
695    // where its own view starts rather than at the store's origin.
696    let (off, len) = window(recv);
697    if i >= len {
698        return true;
699    }
700    with_host(|h| {
701        if let Some(JsObj::Array(items)) = h.get_mut(&arr) {
702            // Out of range writes are dropped, not appended.
703            if let Some(slot) = items.get_mut(off + i) {
704                *slot = Value::Float(b as f64);
705            }
706        }
707    });
708    true
709}
710
711/// `buffer.kMaxLength` — node v26's ceiling on a Buffer's size, 2^53 - 1.
712const K_MAX_LENGTH: f64 = 9_007_199_254_740_991.0;
713
714/// Node's `validateNumber(size, 'size', 0, kMaxLength)`, the check
715/// `Buffer.alloc` / `allocUnsafe` / `allocUnsafeSlow` run before allocating: a
716/// non-number is `ERR_INVALID_ARG_TYPE`, and a negative, too-large or NaN size is
717/// `ERR_OUT_OF_RANGE`. Without it `Buffer.alloc(-1)` and `Buffer.alloc('x')`
718/// quietly returned an empty buffer, and `Buffer.alloc(2 ** 53)` aborted the
719/// process on a failed allocation instead of throwing.
720fn validate_size(args: &[Value]) -> Result<usize, String> {
721    let v = args.first().cloned().unwrap_or(Value::Undef);
722    if with_host(|h| h.type_of(&v)) != "number" {
723        return Err(crate::host::invalid_arg_type(
724            "size", "argument", "number", &v,
725        ));
726    }
727    let n = with_host(|h| h.to_number(&v));
728    if n.is_nan() || !(0.0..=K_MAX_LENGTH).contains(&n) {
729        return Err(crate::host::coded_error(
730            "RangeError",
731            "ERR_OUT_OF_RANGE",
732            &format!(
733                "The value of \"size\" is out of range. It must be >= 0 && <= {}. Received {}",
734                crate::host::fmt_number(K_MAX_LENGTH),
735                out_of_range_received(n)
736            ),
737        ));
738    }
739    Ok(n as usize)
740}
741
742/// How node's `ERR_OUT_OF_RANGE` shows a numeric input: an integer beyond 2^32
743/// through `addNumericalSeparator` (`_` every three characters from the right,
744/// applied to the printed text, so `1e21` becomes `1e_+21` exactly as in node),
745/// anything else as `inspect` would.
746pub(crate) fn out_of_range_received(n: f64) -> String {
747    let shown = crate::host::fmt_number(n);
748    if n.fract() != 0.0 || n.abs() <= 4_294_967_296.0 {
749        return shown;
750    }
751    let start = usize::from(shown.starts_with('-'));
752    let mut i = shown.len();
753    let mut groups = String::new();
754    while i >= start + 4 {
755        groups = format!("_{}{groups}", &shown[i - 3..i]);
756        i -= 3;
757    }
758    format!("{}{groups}", &shown[..i])
759}
760
761pub fn static_call(method: &str, args: &[Value]) -> Option<Result<Value, String>> {
762    Some(match method {
763        "from" => from(args),
764        "copyBytesFrom" => copy_bytes_from(args),
765        "alloc" => {
766            let n = match validate_size(args) {
767                Ok(n) => n,
768                Err(e) => return Some(Err(e)),
769            };
770            // A string fill repeats to length n; a numeric fill is a single byte.
771            // alloc(size[, fill[, encoding]]).
772            let pat = if args.len() > 1 {
773                let enc = if args.len() > 2 {
774                    arg_str(args, 2)
775                } else {
776                    "utf8".into()
777                };
778                fill_pattern(args, 1, &enc)
779            } else {
780                vec![0]
781            };
782            let bytes: Vec<u8> = if pat.is_empty() {
783                vec![0u8; n]
784            } else {
785                (0..n).map(|i| pat[i % pat.len()]).collect()
786            };
787            Ok(from_bytes(&bytes))
788        }
789        // `allocUnsafe` slices the shared pool (`allocate`); `allocUnsafeSlow`
790        // never does.
791        "allocUnsafe" => validate_size(args).map(|n| pooled(&vec![0u8; n])),
792        "allocUnsafeSlow" => validate_size(args).map(|n| from_bytes(&vec![0u8; n])),
793        "concat" => concat(args),
794        // `Buffer.of(...bytes)` — the `%TypedArray%.of` form: each argument is one
795        // byte. Measured: `Buffer.of(1,2,3).toString('hex') === '010203'`,
796        // `Buffer.of().length === 0`.
797        "of" => Ok(from_bytes(
798            &args
799                .iter()
800                .map(|v| crate::host::with_host(|h| h.to_number(v)) as u8)
801                .collect::<Vec<u8>>(),
802        )),
803        // `Buffer.isEncoding(enc)` — case-insensitive over the encodings Node
804        // accepts. Measured: `UTF8`, `UTF-8`, `ASCII` and `Hex` are all true;
805        // `utf7`, `utf-16be`, `none` and `''` are all false.
806        "isEncoding" => Ok(Value::Bool(matches!(
807            super::arg_str(args, 0).to_ascii_lowercase().as_str(),
808            "utf8"
809                | "utf-8"
810                | "ucs2"
811                | "ucs-2"
812                | "utf16le"
813                | "utf-16le"
814                | "latin1"
815                | "binary"
816                | "base64"
817                | "base64url"
818                | "hex"
819                | "ascii"
820        ))),
821        // Static `Buffer.compare(a, b)` — the sort comparator form.
822        "compare" => {
823            let a = match uint8_arg(args.first(), "buf1") {
824                Ok(b) => b,
825                Err(e) => return Some(Err(e)),
826            };
827            let b = match uint8_arg(args.get(1), "buf2") {
828                Ok(b) => b,
829                Err(e) => return Some(Err(e)),
830            };
831            Ok(ordering_value(a.cmp(&b)))
832        }
833        "isBuffer" => Ok(Value::Bool(
834            super::native_tag(&args.first().cloned().unwrap_or(Value::Undef)).as_deref()
835                == Some("Buffer"),
836        )),
837        "byteLength" => {
838            // A Buffer/typed array/ArrayBuffer argument reports its VIEW size,
839            // not its element count and not the length of a stringification.
840            if let Some(n) = view_byte_length(&args.first().cloned().unwrap_or(Value::Undef)) {
841                return Some(Ok(Value::Float(n)));
842            }
843            let enc = args
844                .get(1)
845                .map(|_| arg_str(args, 1))
846                .unwrap_or_else(|| "utf8".into());
847            Ok(Value::Float(
848                decode_str(&arg_str(args, 0), &enc).len() as f64
849            ))
850        }
851        _ => return None,
852    })
853}
854
855/// The bytes of any byte-like source: a JS array of byte values, another
856/// `Buffer`, ANY typed array, or an `ArrayBuffer`. `None` for anything else
857/// (a string, which every caller handles with its own encoding rules).
858///
859/// A `Buffer` is a `Uint8Array` subclass, so every place that accepts a Buffer
860/// accepts a typed array too. Each of `Buffer.from`, `Buffer.concat`,
861/// `buf.equals` and `buf.indexOf` had its own notion of "byte source" and all
862/// four understood `@@bytes` only: passing a `Uint8Array` made `from` fall
863/// through to the STRING path and produce the bytes of `"[object Object]"`,
864/// made `concat` contribute nothing, and made `equals`/`indexOf` silently miss.
865/// Routing them all through one helper is what keeps them from drifting again.
866///
867/// Element values are truncated to a byte each, which is what Node does:
868/// `Buffer.from(new Int32Array([1, 2, 300]))` is `<Buffer 01 02 2c>`.
869/// The bytes of a byte VIEW — a `Buffer`, any typed array, a `DataView` or an
870/// `ArrayBuffer` — and nothing else.
871///
872/// Narrower than `bytes_like`, which also accepts a plain JS array of byte
873/// values. The APIs that take "a Buffer, TypedArray, DataView or string" want
874/// exactly this set: an array argument is a TypeError in node, so widening to
875/// it would trade one divergence for another.
876pub fn view_bytes(v: &Value) -> Option<Vec<u8>> {
877    match super::native_tag(v).as_deref() {
878        // A `DataView` exposes no elements, so its bytes come straight from the
879        // window it holds onto its buffer. It is deliberately absent from
880        // `bytes_like`: `Buffer.from(dataView)` is EMPTY in node, because
881        // `Buffer.from` wants something array-like and a DataView has no
882        // `length`.
883        Some("DataView") => {
884            let n = with_host(|h| match h.get(v) {
885                Some(JsObj::Object(p)) => p.get("byteLength").map(|l| h.to_number(l) as usize),
886                _ => None,
887            })
888            .unwrap_or(0);
889            crate::stdlib::typedarray::view_bytes(v, 0, n)
890        }
891        // A typed array contributes the bytes it views, not its truncated
892        // elements: `hash.update(new Uint16Array([0x4142]))` hashes `42 41`.
893        Some("TypedArray") => crate::stdlib::typedarray::raw_view_bytes(v),
894        Some("Buffer") | Some("ArrayBuffer") => bytes_like(v),
895        _ => None,
896    }
897}
898
899pub fn bytes_like(v: &Value) -> Option<Vec<u8>> {
900    // A Buffer or a typed array of any kind: its ELEMENTS, truncated.
901    if let Some(elems) = crate::stdlib::typedarray::elems_of(v) {
902        return Some(elems.iter().map(|x| *x as i64 as u8).collect());
903    }
904    // An `ArrayBuffer` is handled by `from`, which SHARES its store rather than
905    // copying — reaching here would produce a detached copy.
906    if super::native_tag(v).as_deref() == Some("ArrayBuffer") {
907        return Some(crate::stdlib::typedarray::buffer_bytes_snapshot(v).unwrap_or_default());
908    }
909    // A plain JS array of byte values.
910    with_host(|h| match h.get(v) {
911        Some(JsObj::Array(items)) => {
912            Some(items.iter().map(|x| h.to_number(x) as i64 as u8).collect())
913        }
914        _ => None,
915    })
916}
917
918/// The `byteLength` a `Buffer`/typed array/`ArrayBuffer` reports, which is the
919/// VIEW's size in bytes rather than its element count — `Buffer.byteLength(new
920/// Int32Array([1,2,3]))` is 12, not 3. Verified against node v26.7.0.
921fn view_byte_length(v: &Value) -> Option<f64> {
922    match super::native_tag(v).as_deref() {
923        Some("Buffer") | Some("TypedArray") | Some("ArrayBuffer") => {
924            with_host(|h| match h.get(v) {
925                Some(JsObj::Object(p)) => p.get("byteLength").map(|b| h.to_number(b)),
926                _ => None,
927            })
928        }
929        _ => None,
930    }
931}
932
933fn from(args: &[Value]) -> Result<Value, String> {
934    let v = args.first().cloned().unwrap_or(Value::Undef);
935    // `Buffer.from(arrayBuffer[, byteOffset[, length]])` SHARES the buffer's
936    // memory — a write through the Buffer is visible through every other view.
937    // It used to copy zero bytes, because an ArrayBuffer had no store at all.
938    if super::native_tag(&v).as_deref() == Some("ArrayBuffer") {
939        let total = crate::stdlib::typedarray::buffer_byte_length(&v);
940        let off = (super::arg_num(args, 1).max(0.0) as usize).min(total);
941        let len = match args.get(2) {
942            Some(Value::Undef) | None => total - off,
943            Some(_) => (super::arg_num(args, 2).max(0.0) as usize).min(total - off),
944        };
945        return Ok(share_array_buffer(&v, off, len));
946    }
947    // Any byte-like source (array of bytes, Buffer, typed array).
948    if let Some(bytes) = bytes_like(&v) {
949        return Ok(pooled(&bytes));
950    }
951    // A string, with an optional encoding.
952    if with_host(|h| h.as_str(&v)).is_some() || matches!(v, Value::Str(_)) {
953        let enc = if args.len() > 1 {
954            arg_str(args, 1)
955        } else {
956            "utf8".into()
957        };
958        return Ok(pooled_string(&arg_str(args, 0), &enc));
959    }
960    // A `DataView` yields an EMPTY buffer: `Buffer.from` wants something
961    // array-like, and a DataView carries `byteLength` but no `length`.
962    if super::native_tag(&v).as_deref() == Some("DataView") {
963        return Ok(from_bytes(&[]));
964    }
965    // An ARRAY-LIKE object — anything with a numeric `length` — contributes its
966    // index properties, each coerced to a byte. `Buffer.from({length: 2})` is
967    // two zero bytes in node.
968    if matches!(v, Value::Obj(_)) {
969        let len = crate::builtins::get_property(&v, "length").unwrap_or(Value::Undef);
970        if !matches!(len, Value::Undef) {
971            let n = with_host(|h| h.to_number(&len));
972            if n.is_finite() && n >= 0.0 {
973                let n = n as usize;
974                let mut out = Vec::with_capacity(n);
975                for i in 0..n {
976                    let e =
977                        crate::builtins::get_property(&v, &i.to_string()).unwrap_or(Value::Undef);
978                    let b = with_host(|h| h.to_number(&e));
979                    out.push(if b.is_finite() { b as i64 as u8 } else { 0 });
980                }
981                return Ok(pooled(&out));
982            }
983        }
984        // `fromObject`'s second form: what `buf.toJSON()` produced,
985        // `{ type: 'Buffer', data: [...] }`, rebuilds the bytes of `data`.
986        let ty = crate::builtins::get_property(&v, "type").unwrap_or(Value::Undef);
987        let data = crate::builtins::get_property(&v, "data").unwrap_or(Value::Undef);
988        if with_host(|h| h.as_str(&ty).is_some_and(|t| t == "Buffer"))
989            && with_host(|h| matches!(h.get(&data), Some(JsObj::Array(_))))
990        {
991            return Ok(pooled(&bytes_like(&data).unwrap_or_default()));
992        }
993    }
994    // Anything else is a TypeError, not a stringification: `Buffer.from(5)`
995    // used to produce the single byte `0x35` (the digit "5") and
996    // `Buffer.from(null)` the four bytes of `"null"`.
997    // It is `lib/buffer.js` throwing `new ERR_INVALID_ARG_TYPE(...)`, a JS-layer
998    // NodeError, so `String(err)` brackets the code.
999    Err(crate::host::coded_error(
1000        "TypeError",
1001        "ERR_INVALID_ARG_TYPE",
1002        &format!(
1003            "The first argument must be of type string or an instance of \
1004Buffer, ArrayBuffer, or Array or an Array-like Object. Received {}",
1005            received_label(&v)
1006        ),
1007    ))
1008}
1009
1010/// How node names a rejected `Buffer.from` argument: `null`, `type number (5)`,
1011/// or `an instance of Object`.
1012fn received_label(v: &Value) -> String {
1013    if matches!(v, Value::Undef) {
1014        return "undefined".into();
1015    }
1016    if with_host(|h| h.is_null(v)) {
1017        return "null".into();
1018    }
1019    let ty = with_host(|h| h.type_of(v));
1020    if ty == "object" || ty == "function" {
1021        let ctor = with_host(|h| h.ctor_name(v));
1022        let ctor = if ctor.is_empty() {
1023            "Object".into()
1024        } else {
1025            ctor
1026        };
1027        return format!("an instance of {ctor}");
1028    }
1029    let shown = with_host(|h| h.inspect(v));
1030    format!("type {ty} ({shown})")
1031}
1032
1033fn concat(args: &[Value]) -> Result<Value, String> {
1034    // `lib/buffer.js` `Buffer.concat(list, length)`: `validateArray(list)`; an
1035    // empty list is an empty Buffer before `length` is looked at; `length` is
1036    // `validateOffset`ed; each part must be a Uint8Array; the result is exactly
1037    // `length` bytes, truncated or zero-filled.
1038    let list_v = args.first().cloned().unwrap_or(Value::Undef);
1039    let list = match with_host(|h| h.get(&list_v).cloned()) {
1040        Some(JsObj::Array(items)) => items,
1041        _ => {
1042            return Err(crate::host::coded_error(
1043                "TypeError",
1044                "ERR_INVALID_ARG_TYPE",
1045                &format!(
1046                    "The \"list\" argument must be an instance of Array. Received {}",
1047                    super::received_desc(&list_v)
1048                ),
1049            ))
1050        }
1051    };
1052    if list.is_empty() {
1053        return Ok(from_bytes(&[]));
1054    }
1055    let length = match args.get(1) {
1056        None | Some(Value::Undef) => None,
1057        Some(v) => Some(validate_offset(v, "length")?),
1058    };
1059    let mut out = Vec::new();
1060    for (i, b) in list.iter().enumerate() {
1061        if super::util_types::ta_kind(b).as_deref() != Some("Uint8Array") {
1062            return Err(crate::host::coded_error(
1063                "TypeError",
1064                "ERR_INVALID_ARG_TYPE",
1065                &format!(
1066                    "The \"list[{i}]\" argument must be an instance of Buffer or Uint8Array. Received {}",
1067                    super::received_desc(b)
1068                ),
1069            ));
1070        }
1071        out.extend(bytes_like(b).unwrap_or_default());
1072    }
1073    if let Some(n) = length {
1074        out.resize(n, 0);
1075    }
1076    Ok(pooled(&out))
1077}
1078
1079/// `validateOffset(value, name)` from `lib/buffer.js`: a Number, an integer,
1080/// and within `[0, kMaxLength]`.
1081fn validate_offset(v: &Value, name: &str) -> Result<usize, String> {
1082    validate_offset_in(v, name, K_MAX_LENGTH)
1083}
1084
1085/// `validateOffset(value, name, 0, max)`: [`validate_offset`] with an explicit
1086/// upper bound.
1087fn validate_offset_in(v: &Value, name: &str, max: f64) -> Result<usize, String> {
1088    if with_host(|h| h.type_of(v)) != "number" {
1089        return Err(crate::host::invalid_arg_type(name, "argument", "number", v));
1090    }
1091    let n = with_host(|h| h.to_number(v));
1092    let out_of_range = |must: String| {
1093        crate::host::coded_error(
1094            "RangeError",
1095            "ERR_OUT_OF_RANGE",
1096            &format!(
1097                "The value of \"{name}\" is out of range. It must be {must}. Received {}",
1098                out_of_range_received(n)
1099            ),
1100        )
1101    };
1102    if n.is_nan() || n.fract() != 0.0 {
1103        return Err(out_of_range("an integer".to_string()));
1104    }
1105    if !(0.0..=max).contains(&n) {
1106        return Err(out_of_range(format!(
1107            ">= 0 && <= {}",
1108            crate::host::fmt_number(max)
1109        )));
1110    }
1111    Ok(n as usize)
1112}
1113
1114/// The bytes of a `compare` operand, which `lib/buffer.js` requires to be a
1115/// Uint8Array (a Buffer is one): anything else is `ERR_INVALID_ARG_TYPE` naming
1116/// the parameter, never a comparison against the bytes of its stringification.
1117fn uint8_arg(v: Option<&Value>, name: &str) -> Result<Vec<u8>, String> {
1118    let v = v.cloned().unwrap_or(Value::Undef);
1119    if super::util_types::ta_kind(&v).as_deref() != Some("Uint8Array") {
1120        return Err(crate::host::coded_error(
1121            "TypeError",
1122            "ERR_INVALID_ARG_TYPE",
1123            &format!(
1124                "The \"{name}\" argument must be an instance of Buffer or Uint8Array. Received {}",
1125                super::received_desc(&v)
1126            ),
1127        ));
1128    }
1129    Ok(view_bytes(&v).unwrap_or_default())
1130}
1131
1132/// A byte-order comparison as the `-1` / `0` / `1` that `compare` returns.
1133fn ordering_value(o: std::cmp::Ordering) -> Value {
1134    Value::Float(match o {
1135        std::cmp::Ordering::Less => -1.0,
1136        std::cmp::Ordering::Equal => 0.0,
1137        std::cmp::Ordering::Greater => 1.0,
1138    })
1139}
1140
1141/// Buffer instance methods.
1142pub fn instance_call(recv: &Value, method: &str, args: &[Value]) -> Result<Value, String> {
1143    let bytes = bytes_of(recv);
1144    match method {
1145        // toString([encoding[, start[, end]]]) — the range was ignored, so every
1146        // partial read (`buf.toString('utf8', 1, 3)`) returned the WHOLE buffer.
1147        "toString" => {
1148            let enc = match args.first() {
1149                None | Some(Value::Undef) => "utf8".into(),
1150                _ => arg_str(args, 0),
1151            };
1152            let len = bytes.len();
1153            let clamp = |i: usize| -> usize {
1154                let n = super::arg_num(args, i);
1155                if n.is_nan() {
1156                    0
1157                } else {
1158                    n.clamp(0.0, len as f64) as usize
1159                }
1160            };
1161            let start = if args.len() > 1 { clamp(1) } else { 0 };
1162            let end = if args.len() > 2 { clamp(2) } else { len };
1163            // An inverted range is empty, not reversed.
1164            let slice = if start < end {
1165                &bytes[start..end]
1166            } else {
1167                &[][..]
1168            };
1169            Ok(with_host(|h| h.new_str(encode_bytes(slice, &enc))))
1170        }
1171        "toJSON" => Ok(with_host(|h| {
1172            let data = h.new_array(bytes.iter().map(|b| Value::Float(*b as f64)).collect());
1173            let mut m = IndexMap::new();
1174            m.insert("type".into(), h.new_str("Buffer"));
1175            m.insert("data".into(), data);
1176            h.new_object(m)
1177        })),
1178        "equals" => {
1179            // `otherBuffer` must be a Uint8Array (a Buffer is one); any other
1180            // view or value is `ERR_INVALID_ARG_TYPE`, never a plain `false`.
1181            let other = uint8_arg(args.first(), "otherBuffer")?;
1182            Ok(Value::Bool(bytes == other))
1183        }
1184        // Both are a window onto the SAME memory in node (`slice` is the
1185        // deprecated alias): a write through the result shows in the parent.
1186        "slice" | "subarray" => {
1187            let (s, e) = slice_bounds(args, bytes.len());
1188            let (off, _) = window(recv);
1189            let ab = with_host(|h| match h.get(recv) {
1190                Some(JsObj::Object(p)) => p.get("@@buffer").cloned(),
1191                _ => None,
1192            });
1193            Ok(match ab {
1194                Some(ab) => share_array_buffer(&ab, off + s, e - s),
1195                None => from_bytes(&bytes[s..e]),
1196            })
1197        }
1198        "readUInt8" => {
1199            let i = read_offset(args, 1, bytes.len())?;
1200            Ok(Value::Float(bytes[i] as f64))
1201        }
1202        // indexOf/lastIndexOf/includes(value[, byteOffset][, encoding]) — both
1203        // trailing arguments used to be ignored, so a search always started at 0
1204        // and always read the needle as UTF-8.
1205        "includes" | "indexOf" | "lastIndexOf" => {
1206            let len = bytes.len();
1207            let last = method == "lastIndexOf";
1208            // `byteOffset` is a string when it is really the encoding.
1209            let (from, enc) = match args.get(1) {
1210                None | Some(Value::Undef) => (None, arg_str(args, 2)),
1211                Some(v) if with_host(|h| h.as_str(v)).is_some() => (None, arg_str(args, 1)),
1212                _ => (Some(super::arg_num(args, 1)), arg_str(args, 2)),
1213            };
1214            let enc = if enc.is_empty() { "utf8".into() } else { enc };
1215            // The needle is a number (its `>>> 0` low byte, so 353 finds 97),
1216            // a string in `enc`, or a Uint8Array's bytes; anything else — an
1217            // array, a boolean, `null`, a `Uint16Array` — is the TypeError
1218            // `bidirectionalIndexOf` throws.
1219            let target = args.first().cloned().unwrap_or(Value::Undef);
1220            let needle = match with_host(|h| h.type_of(&target)) {
1221                "number" => {
1222                    let n = super::arg_num(args, 0);
1223                    vec![crate::host::to_int32(n) as u32 as u8]
1224                }
1225                "string" => decode_str(&arg_str(args, 0), &enc),
1226                _ if super::util_types::ta_kind(&target).as_deref() == Some("Uint8Array") => {
1227                    view_bytes(&target).unwrap_or_default()
1228                }
1229                _ => {
1230                    return Err(crate::host::coded_error(
1231                        "TypeError",
1232                        "ERR_INVALID_ARG_TYPE",
1233                        &format!(
1234                            "The \"value\" argument must be one of type number or string or an instance of Buffer or Uint8Array. Received {}",
1235                            super::received_desc(&target)
1236                        ),
1237                    ))
1238                }
1239            };
1240            // A negative offset counts back from the end; NaN is 0. Out of range
1241            // means "no room to match" forwards, and "whole buffer" backwards.
1242            let from = from.map(|n| {
1243                if n.is_nan() {
1244                    0
1245                } else if n < 0.0 {
1246                    (len as f64 + n).max(0.0) as usize
1247                } else {
1248                    (n as usize).min(len)
1249                }
1250            });
1251            // An empty needle matches at the offset itself, clamped to the length.
1252            let pos = if needle.is_empty() {
1253                Some(from.unwrap_or(if last { len } else { 0 }).min(len))
1254            } else if last {
1255                // lastIndexOf searches at or before the offset, so the match may
1256                // start at `from` itself and run past it.
1257                let hi = (from.unwrap_or(len) + needle.len()).min(len);
1258                bytes[..hi]
1259                    .windows(needle.len())
1260                    .rposition(|w| w == needle.as_slice())
1261            } else {
1262                let lo = from.unwrap_or(0);
1263                bytes[lo..]
1264                    .windows(needle.len())
1265                    .position(|w| w == needle.as_slice())
1266                    .map(|p| p + lo)
1267            };
1268            if method == "includes" {
1269                Ok(Value::Bool(pos.is_some()))
1270            } else {
1271                Ok(Value::Float(pos.map(|p| p as f64).unwrap_or(-1.0)))
1272            }
1273        }
1274        // compare(target[, targetStart[, targetEnd[, sourceStart[, sourceEnd]]]])
1275        // — `lib/buffer.js`: each bound is `validateOffset`ed (an end against its
1276        // own buffer's length), an empty source range is `0`/`-1` and an empty
1277        // target range `1` before any byte is read, and the two ranges are then
1278        // compared lexicographically. The bounds used to be ignored entirely.
1279        "compare" => {
1280            let target = uint8_arg(args.first(), "target")?;
1281            let bound = |i: usize, name: &str, default: usize, max: f64| match args.get(i) {
1282                None | Some(Value::Undef) => Ok(default),
1283                Some(v) => validate_offset_in(v, name, max),
1284            };
1285            let t_start = bound(1, "targetStart", 0, K_MAX_LENGTH)?;
1286            let t_end = bound(2, "targetEnd", target.len(), target.len() as f64)?;
1287            let s_start = bound(3, "sourceStart", 0, K_MAX_LENGTH)?;
1288            let s_end = bound(4, "sourceEnd", bytes.len(), bytes.len() as f64)?;
1289            if s_start >= s_end {
1290                return Ok(Value::Float(if t_start >= t_end { 0.0 } else { -1.0 }));
1291            }
1292            if t_start >= t_end {
1293                return Ok(Value::Float(1.0));
1294            }
1295            Ok(ordering_value(
1296                bytes[s_start..s_end].cmp(&target[t_start..t_end]),
1297            ))
1298        }
1299        // Big-endian / little-endian integer reads.
1300        "readUInt16BE" => {
1301            let i = read_offset(args, 2, bytes.len())?;
1302            let v = ((bytes[i] as u16) << 8) | bytes[i + 1] as u16;
1303            Ok(Value::Float(v as f64))
1304        }
1305        "readUInt16LE" => {
1306            let i = read_offset(args, 2, bytes.len())?;
1307            let v = (bytes[i] as u16) | ((bytes[i + 1] as u16) << 8);
1308            Ok(Value::Float(v as f64))
1309        }
1310        // 32-bit and signed reads. `readIntXX` reinterprets the same bytes as
1311        // two's complement.
1312        "readUInt32BE" | "readUInt32LE" | "readInt32BE" | "readInt32LE" => {
1313            let i = read_offset(args, 4, bytes.len())?;
1314            let at = |k: usize| bytes[i + k] as u32;
1315            let v = if method.ends_with("BE") {
1316                (at(0) << 24) | (at(1) << 16) | (at(2) << 8) | at(3)
1317            } else {
1318                at(0) | (at(1) << 8) | (at(2) << 16) | (at(3) << 24)
1319            };
1320            Ok(Value::Float(if method.starts_with("readInt") {
1321                v as i32 as f64
1322            } else {
1323                v as f64
1324            }))
1325        }
1326        "readInt8" => {
1327            let i = read_offset(args, 1, bytes.len())?;
1328            Ok(Value::Float(bytes[i] as i8 as f64))
1329        }
1330        "readInt16BE" | "readInt16LE" => {
1331            let i = read_offset(args, 2, bytes.len())?;
1332            let at = |k: usize| bytes[i + k] as u16;
1333            let v = if method.ends_with("BE") {
1334                (at(0) << 8) | at(1)
1335            } else {
1336                at(0) | (at(1) << 8)
1337            };
1338            Ok(Value::Float(v as i16 as f64))
1339        }
1340        // `buf[i]` by method: `at` accepts a negative index like Array.prototype.at.
1341        "at" => {
1342            let i = super::arg_num(args, 0);
1343            let idx = if i < 0.0 { i + bytes.len() as f64 } else { i };
1344            Ok(match bytes.get(idx.max(-1.0) as usize) {
1345                Some(b) if idx >= 0.0 => Value::Float(*b as f64),
1346                _ => Value::Undef,
1347            })
1348        }
1349        // Iteration helpers: a Buffer is an index/byte collection.
1350        // A Buffer's `Symbol.iterator` IS `values`, inherited from
1351        // `%TypedArray%.prototype`, so it dispatches here rather than reporting
1352        // itself missing.
1353        "values" | "keys" | "entries" | "@@iterator" => {
1354            // They are `%TypedArray%.prototype`'s, so over a DETACHED buffer
1355            // they throw where Buffer's own methods read zero bytes.
1356            if crate::stdlib::typedarray::view_detached(recv) {
1357                let name = if method == "@@iterator" {
1358                    "values"
1359                } else {
1360                    method
1361                };
1362                return Err(crate::stdlib::typedarray::detached_error(
1363                    "%TypedArray%.prototype",
1364                    name,
1365                    false,
1366                ));
1367            }
1368            let items: Vec<Value> = with_host(|h| match method {
1369                "keys" => (0..bytes.len()).map(|i| Value::Float(i as f64)).collect(),
1370                "values" | "@@iterator" => bytes.iter().map(|b| Value::Float(*b as f64)).collect(),
1371                _ => bytes
1372                    .iter()
1373                    .enumerate()
1374                    .map(|(i, b)| {
1375                        h.new_array(vec![Value::Float(i as f64), Value::Float(*b as f64)])
1376                    })
1377                    .collect(),
1378            });
1379            Ok(with_host(|h| {
1380                h.alloc_iter(JsObj::Iter {
1381                    items,
1382                    idx: 0,
1383                    array: None,
1384                    brand: Some("Array Iterator"),
1385                })
1386            }))
1387        }
1388        // IEEE-754 reads/writes. `f32`/`f64` go through their raw bit patterns,
1389        // so the endianness handling is the same byte reversal as the integers.
1390        "readFloatBE" | "readFloatLE" => {
1391            let i = read_offset(args, 4, bytes.len())?;
1392            let mut raw = [0u8; 4];
1393            raw.copy_from_slice(&bytes[i..i + 4]);
1394            if method.ends_with("LE") {
1395                raw.reverse();
1396            }
1397            Ok(Value::Float(f32::from_be_bytes(raw) as f64))
1398        }
1399        "readDoubleBE" | "readDoubleLE" => {
1400            let i = read_offset(args, 8, bytes.len())?;
1401            let mut raw = [0u8; 8];
1402            raw.copy_from_slice(&bytes[i..i + 8]);
1403            if method.ends_with("LE") {
1404                raw.reverse();
1405            }
1406            Ok(Value::Float(f64::from_be_bytes(raw)))
1407        }
1408        "writeFloatBE" | "writeFloatLE" => {
1409            let mut raw = (super::arg_num(args, 0) as f32).to_be_bytes();
1410            if method.ends_with("LE") {
1411                raw.reverse();
1412            }
1413            let off = write_offset(args, 4, bytes.len())?;
1414            store_bytes(recv, &bytes, off, &raw)?;
1415            Ok(Value::Float((off + 4) as f64))
1416        }
1417        "writeDoubleBE" | "writeDoubleLE" => {
1418            let mut raw = super::arg_num(args, 0).to_be_bytes();
1419            if method.ends_with("LE") {
1420                raw.reverse();
1421            }
1422            let off = write_offset(args, 8, bytes.len())?;
1423            store_bytes(recv, &bytes, off, &raw)?;
1424            Ok(Value::Float((off + 8) as f64))
1425        }
1426        // 64-bit integers, which exceed `f64`'s exact range and so are BigInts
1427        // on both sides.
1428        "readBigInt64BE" | "readBigInt64LE" | "readBigUInt64BE" | "readBigUInt64LE" => {
1429            let i = read_offset(args, 8, bytes.len())?;
1430            let mut raw = [0u8; 8];
1431            raw.copy_from_slice(&bytes[i..i + 8]);
1432            if method.ends_with("LE") {
1433                raw.reverse();
1434            }
1435            let n = if method.starts_with("readBigInt") {
1436                num_bigint::BigInt::from(i64::from_be_bytes(raw))
1437            } else {
1438                num_bigint::BigInt::from(u64::from_be_bytes(raw))
1439            };
1440            Ok(with_host(|h| h.alloc(JsObj::BigInt(n))))
1441        }
1442        "writeBigInt64BE" | "writeBigInt64LE" | "writeBigUInt64BE" | "writeBigUInt64LE" => {
1443            let v = args.first().cloned().unwrap_or(Value::Undef);
1444            let n = big_write_value(&v, method.starts_with("writeBigInt"))?;
1445            // Both signed and unsigned store the same 64 bits; the sign is only
1446            // a question of how they are read back.
1447            let bits = num_traits::ToPrimitive::to_i64(&n)
1448                .map(|x| x as u64)
1449                .or_else(|| num_traits::ToPrimitive::to_u64(&n))
1450                .unwrap_or(0);
1451            let mut raw = bits.to_be_bytes();
1452            if method.ends_with("LE") {
1453                raw.reverse();
1454            }
1455            let off = write_offset(args, 8, bytes.len())?;
1456            store_bytes(recv, &bytes, off, &raw)?;
1457            Ok(Value::Float((off + 8) as f64))
1458        }
1459        // The variable-width family: `byteLength` is an argument (1..=6), which
1460        // is why these cannot share the fixed-width arms above.
1461        "readIntBE" | "readIntLE" | "readUIntBE" | "readUIntLE" => {
1462            let width = variable_byte_length(args.get(1))?;
1463            let off = read_offset(args, width, bytes.len())?;
1464            let mut acc: u64 = 0;
1465            for k in 0..width {
1466                let b = if method.ends_with("BE") {
1467                    bytes[off + k]
1468                } else {
1469                    bytes[off + width - 1 - k]
1470                };
1471                acc = (acc << 8) | b as u64;
1472            }
1473            let signed = method.starts_with("readInt");
1474            let out = if signed {
1475                // Sign-extend from the top bit of the width-th byte.
1476                let shift = 64 - (width * 8);
1477                ((acc << shift) as i64 >> shift) as f64
1478            } else {
1479                acc as f64
1480            };
1481            Ok(Value::Float(out))
1482        }
1483        // `lib/internal/buffer.js`'s writers: `value = +value`, `checkInt` against
1484        // the width's range, then the offset's `checkBounds`. A value outside the
1485        // range used to wrap silently (`writeUInt8(300)` stored 0x2c) and an
1486        // out-of-range offset could be negative or fractional.
1487        "writeIntBE" | "writeIntLE" | "writeUIntBE" | "writeUIntLE" | "writeInt8"
1488        | "writeUInt8" | "writeInt16BE" | "writeInt16LE" | "writeUInt16BE" | "writeUInt16LE"
1489        | "writeInt32BE" | "writeInt32LE" | "writeUInt32BE" | "writeUInt32LE" => {
1490            let width = match method {
1491                "writeIntBE" | "writeIntLE" | "writeUIntBE" | "writeUIntLE" => {
1492                    variable_byte_length(args.get(2))?
1493                }
1494                "writeInt8" | "writeUInt8" => 1,
1495                m if m.contains("16") => 2,
1496                _ => 4,
1497            };
1498            let value = super::arg_num(args, 0);
1499            let bits = (width * 8) as i32;
1500            let (min, max) = if method.starts_with("writeInt") {
1501                (-(2f64.powi(bits - 1)), 2f64.powi(bits - 1) - 1.0)
1502            } else {
1503                (0.0, 2f64.powi(bits) - 1.0)
1504            };
1505            check_int_value(value, min, max, width - 1)?;
1506            let off = write_offset(args, width, bytes.len())?;
1507            // NaN stores 0, as `value as i64` gives.
1508            let val = value as i64 as u64;
1509            let mut raw: Vec<u8> = (0..width)
1510                .map(|k| (val >> (8 * (width - 1 - k))) as u8)
1511                .collect();
1512            if method.ends_with("LE") {
1513                raw.reverse();
1514            }
1515            store_bytes(recv, &bytes, off, &raw)?;
1516            Ok(Value::Float((off + width) as f64))
1517        }
1518        // write(string[, offset[, length]][, encoding]) — returns bytes written.
1519        // `length` and `encoding` used to be ignored entirely: every write was
1520        // UTF-8 and ran to the end of the buffer.
1521        "write" => {
1522            let mut b = bytes.clone();
1523            let Some((off, max, enc)) = write_args(args, b.len()) else {
1524                return Err(crate::host::range_error(&format!(
1525                    "The value of \"offset\" is out of range. It must be >= 0 && <= {}. Received {}",
1526                    b.len(),
1527                    super::arg_num(args, 1)
1528                )));
1529            };
1530            let src = truncate_chars(&arg_str(args, 0), &enc, max);
1531            let n = src.len().min(b.len().saturating_sub(off));
1532            b[off..off + n].copy_from_slice(&src[..n]);
1533            set_bytes(recv, &b);
1534            Ok(Value::Float(n as f64))
1535        }
1536        // swap16/32/64 reverse each 2/4/8-byte group IN PLACE and return the
1537        // same Buffer, so `b.swap16()` mutates `b`. A length that is not a whole
1538        // number of groups is a RangeError rather than a partial swap.
1539        "swap16" | "swap32" | "swap64" => {
1540            let group = match method {
1541                "swap16" => 2,
1542                "swap32" => 4,
1543                _ => 8,
1544            };
1545            if bytes.len() % group != 0 {
1546                return Err(crate::host::coded_error(
1547                    "RangeError",
1548                    "ERR_INVALID_BUFFER_SIZE",
1549                    &format!("Buffer size must be a multiple of {}-bits", group * 8),
1550                ));
1551            }
1552            let mut b = bytes.clone();
1553            for c in b.chunks_mut(group) {
1554                c.reverse();
1555            }
1556            set_bytes(recv, &b);
1557            Ok(recv.clone())
1558        }
1559        // fill(value[, start[, end]]) — value is a byte or a repeated string.
1560        // fill(value[, offset[, end]][, encoding]). A STRING in the `offset` or
1561        // `end` slot is the encoding, and node then resets the range to the
1562        // whole buffer rather than shifting the remaining arguments left — so
1563        // `fill('41','hex',1,3)` fills all of it, not `1..3`.
1564        "fill" => {
1565            let mut b = bytes.clone();
1566            let len = b.len();
1567            let (start, end, enc) = if arg_is_str(args, 1) {
1568                (0, len, arg_str(args, 1))
1569            } else if arg_is_str(args, 2) {
1570                let s = (super::arg_num(args, 1).max(0.0) as usize).min(len);
1571                (s, len, arg_str(args, 2))
1572            } else {
1573                let s = if args.len() > 1 {
1574                    (super::arg_num(args, 1).max(0.0) as usize).min(len)
1575                } else {
1576                    0
1577                };
1578                let e = if args.len() > 2 {
1579                    (super::arg_num(args, 2).max(0.0) as usize).min(len)
1580                } else {
1581                    len
1582                };
1583                let enc = if args.len() > 3 {
1584                    arg_str(args, 3)
1585                } else {
1586                    "utf8".into()
1587                };
1588                (s, e, enc)
1589            };
1590            let pat = fill_pattern(args, 0, &enc);
1591            if !pat.is_empty() {
1592                for (k, slot) in b[start..end.max(start)].iter_mut().enumerate() {
1593                    *slot = pat[k % pat.len()];
1594                }
1595            }
1596            set_bytes(recv, &b);
1597            Ok(recv.clone())
1598        }
1599        // copy(target[, targetStart[, sourceStart[, sourceEnd]]]) — returns count.
1600        "copy" => {
1601            let target = args.first().cloned().unwrap_or(Value::Undef);
1602            let mut tb = bytes_of(&target);
1603            let tstart = if args.len() > 1 {
1604                super::arg_num(args, 1).max(0.0) as usize
1605            } else {
1606                0
1607            };
1608            let sstart = if args.len() > 2 {
1609                super::arg_num(args, 2).max(0.0) as usize
1610            } else {
1611                0
1612            };
1613            let send = if args.len() > 3 {
1614                (super::arg_num(args, 3) as usize).min(bytes.len())
1615            } else {
1616                bytes.len()
1617            };
1618            let mut n = 0;
1619            for (k, &byte) in bytes[sstart..send.max(sstart)].iter().enumerate() {
1620                if tstart + k < tb.len() {
1621                    tb[tstart + k] = byte;
1622                    n += 1;
1623                }
1624            }
1625            set_bytes(&target, &tb);
1626            Ok(Value::Float(n as f64))
1627        }
1628        // `TypedArray.prototype.set(source[, offset])` — copy `source`'s bytes in
1629        // at `offset`, throwing when they would not fit (as Node does).
1630        "set" => {
1631            let src = crate::stdlib::typedarray::set_source_bytes(args.first())?;
1632            let off = super::arg_num(args, 1);
1633            let off = if off.is_nan() { 0.0 } else { off.trunc() };
1634            if off < 0.0 || off + src.len() as f64 > bytes.len() as f64 {
1635                return Err(crate::host::range_error("offset is out of bounds"));
1636            }
1637            let offset = off as usize;
1638            let mut out = bytes.clone();
1639            out[offset..offset + src.len()].copy_from_slice(&src);
1640            set_bytes(recv, &out);
1641            Ok(Value::Undef)
1642        }
1643        // A Buffer IS a `Uint8Array`, so anything it does not implement itself
1644        // falls through to the shared typed-array behaviour it inherits —
1645        // `every`, `map`, `filter`, `forEach`, `reduce`, `sort` and the rest.
1646        // These used to READ as functions (the thunks resolve through
1647        // `Uint8Array.prototype` on the chain) but throw on call, because
1648        // dispatch landed here and stopped. A method the typed arrays do not
1649        // have either still reports the Buffer-shaped error below.
1650        _ if crate::stdlib::typedarray::PROTOTYPE_METHODS.contains(&method) => {
1651            crate::stdlib::typedarray::instance_call(recv, method, args)
1652        }
1653        _ => Err(crate::host::type_error(&format!(
1654            "buffer.{method} is not a function"
1655        ))),
1656    }
1657}
1658
1659/// The fill pattern at `args[idx]`: a string's utf-8 bytes, else a single byte.
1660fn fill_pattern(args: &[Value], idx: usize, enc: &str) -> Vec<u8> {
1661    match args.get(idx) {
1662        None => vec![0],
1663        Some(v) => {
1664            let is_str = matches!(v, Value::Str(_))
1665                || with_host(|h| matches!(h.get(v), Some(JsObj::Str(_))));
1666            if is_str {
1667                decode_str(&arg_str(args, idx), enc)
1668            } else {
1669                vec![super::arg_num(args, idx) as u8]
1670            }
1671        }
1672    }
1673}
1674
1675/// Whether `args[i]` is a string — the test that separates a positional
1676/// `offset`/`end` from a trailing `encoding` in `fill`/`write`/`indexOf`.
1677fn arg_is_str(args: &[Value], i: usize) -> bool {
1678    args.get(i)
1679        .is_some_and(|v| with_host(|h| h.as_str(v)).is_some())
1680}
1681
1682/// Overwrite `recv`'s backing `@@bytes` array (for in-place buffer writes).
1683/// Write `out` into the buffer's backing bytes at `off`.
1684///
1685/// A write that would run past the end is a `RangeError`, as in node. The
1686/// fixed-width writers used to skip it silently and still return the advanced
1687/// offset, so a caller writing past the end was told it had succeeded and the
1688/// bytes were simply lost.
1689fn store_bytes(recv: &Value, bytes: &[u8], off: usize, out: &[u8]) -> Result<(), String> {
1690    if off + out.len() > bytes.len() {
1691        return Err(range_error_out_of_bounds());
1692    }
1693    let mut b = bytes.to_vec();
1694    b[off..off + out.len()].copy_from_slice(out);
1695    set_bytes(recv, &b);
1696    Ok(())
1697}
1698
1699fn range_error_out_of_bounds() -> String {
1700    crate::host::plain_coded_error(
1701        "RangeError",
1702        "ERR_OUT_OF_RANGE",
1703        "Attempt to access memory outside buffer bounds",
1704    )
1705}
1706
1707/// Overwrite the bytes a byte VIEW (or an `ArrayBuffer`) exposes, from its
1708/// first byte — the write-side twin of [`view_bytes`], so an API that fills a
1709/// caller's view (`randomFillSync`, `readSync`) reaches every view kind and
1710/// the memory it aliases.
1711pub fn write_view(v: &Value, bytes: &[u8]) {
1712    match super::native_tag(v).as_deref() {
1713        Some("Buffer" | "ArrayBuffer") => set_bytes(v, bytes),
1714        Some("TypedArray" | "DataView") => {
1715            crate::stdlib::typedarray::write_view_bytes(v, 0, bytes);
1716        }
1717        _ => {}
1718    }
1719}
1720
1721fn set_bytes(recv: &Value, new: &[u8]) {
1722    let (off, _) = window(recv);
1723    with_host(|h| {
1724        let arr = match h.get(recv) {
1725            Some(JsObj::Object(p)) => p.get("@@bytes").cloned(),
1726            _ => None,
1727        };
1728        if let Some(a) = arr {
1729            if let Some(JsObj::Array(items)) = h.get_mut(&a) {
1730                // Only the window is rewritten, so a Buffer sharing an
1731                // ArrayBuffer never clobbers bytes outside its own view.
1732                for (i, b) in new.iter().enumerate() {
1733                    if off + i < items.len() {
1734                        items[off + i] = Value::Float(*b as f64);
1735                    }
1736                }
1737            }
1738        }
1739    });
1740}
1741
1742fn slice_bounds(args: &[Value], len: usize) -> (usize, usize) {
1743    let norm = |n: f64| -> usize {
1744        if n < 0.0 {
1745            (len as f64 + n).max(0.0) as usize
1746        } else {
1747            (n as usize).min(len)
1748        }
1749    };
1750    let s = if args.is_empty() {
1751        0
1752    } else {
1753        norm(super::arg_num(args, 0))
1754    };
1755    let e = if args.len() < 2 {
1756        len
1757    } else {
1758        norm(super::arg_num(args, 1))
1759    };
1760    (s.min(e), e.max(s))
1761}
1762
1763/// String → bytes under a Node buffer encoding.
1764///
1765/// The `utf16le` family and `base64url` used to fall through to the UTF-8 arm,
1766/// which is silent corruption rather than a missing feature: `Buffer.from('abc',
1767/// 'utf16le')` produced the 3 bytes `616263` instead of node's 6 bytes
1768/// `610062006300`, and every `byteLength`/`write`/`fill` that funnels through
1769/// here inherited the wrong count.
1770pub(crate) fn decode_str(s: &str, enc: &str) -> Vec<u8> {
1771    match enc.to_ascii_lowercase().as_str() {
1772        "hex" => from_hex(s),
1773        "base64" | "base64url" => from_base64(s),
1774        // One byte per UTF-16 CODE UNIT, not per code point: node writes
1775        // `Buffer.from("\u{1D4B3}","latin1")` as the low bytes of the surrogate
1776        // pair (`35 b3`), two bytes, not the one low byte of U+1D4B3. Encoding
1777        // does NOT mask to 7 bits even for `ascii` — only decoding does.
1778        "ascii" | "latin1" | "binary" => s.encode_utf16().map(|u| u as u8).collect(),
1779        // A JS string IS UTF-16, so this encoding is the identity on its code
1780        // units, written little-endian — not a transcode of the UTF-8 bytes.
1781        "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
1782            s.encode_utf16().flat_map(|u| u.to_le_bytes()).collect()
1783        }
1784        _ => s.as_bytes().to_vec(),
1785    }
1786}
1787
1788pub(crate) fn encode_bytes(bytes: &[u8], enc: &str) -> String {
1789    match enc.to_ascii_lowercase().as_str() {
1790        "hex" => to_hex(bytes),
1791        "base64" => to_base64(bytes),
1792        "base64url" => super::to_base64url(bytes),
1793        // Decoding `ascii` masks off the high bit (node: `Buffer.from([0xff])
1794        // .toString('ascii')` is `U+007F`); `latin1` keeps the whole byte.
1795        "ascii" => bytes.iter().map(|b| (*b & 0x7f) as char).collect(),
1796        "latin1" | "binary" => bytes.iter().map(|b| *b as char).collect(),
1797        // A trailing odd byte has no code unit and is dropped, as node does.
1798        "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => {
1799            let units: Vec<u16> = bytes
1800                .chunks_exact(2)
1801                .map(|c| u16::from_le_bytes([c[0], c[1]]))
1802                .collect();
1803            crate::utf16::to_string_lossy(&units)
1804        }
1805        _ => String::from_utf8_lossy(bytes).into_owned(),
1806    }
1807}
1808
1809/// Resolve the `(offset, length, encoding)` triple of `buf.write(string[,
1810/// offset[, length]][, encoding])`, whose trailing arguments are positional-
1811/// or-encoding depending on their runtime type (node's own `Buffer.prototype
1812/// .write` does exactly this dispatch).
1813///
1814/// `args[0]` is the string; this reads from `args[1]` on. Returns `None` when
1815/// the offset is out of range, which is a `RangeError` at the call site.
1816fn write_args(args: &[Value], len: usize) -> Option<(usize, usize, String)> {
1817    let num = |i: usize| super::arg_num(args, i);
1818    // write(string) / write(string, encoding)
1819    if args.len() < 2 {
1820        return Some((0, len, "utf8".into()));
1821    }
1822    if arg_is_str(args, 1) {
1823        return Some((0, len, arg_str(args, 1)));
1824    }
1825    let off = num(1);
1826    if !(0.0..=len as f64).contains(&off) {
1827        return None;
1828    }
1829    let off = off as usize;
1830    // write(string, offset) / write(string, offset, encoding)
1831    if args.len() < 3 {
1832        return Some((off, len - off, "utf8".into()));
1833    }
1834    if arg_is_str(args, 2) {
1835        return Some((off, len - off, arg_str(args, 2)));
1836    }
1837    let max = len - off;
1838    let n = (num(2).max(0.0) as usize).min(max);
1839    let enc = if args.len() > 3 {
1840        arg_str(args, 3)
1841    } else {
1842        "utf8".into()
1843    };
1844    Some((off, n, enc))
1845}
1846
1847/// Truncate `bytes` to at most `max`, never splitting a multi-byte character.
1848///
1849/// `buf.write` writes whole characters only: node reports 2, not 4, for
1850/// `Buffer.alloc(4).write('é€')` — the 2-byte `é` fits and the 3-byte `€` is
1851/// dropped whole rather than half-written. Only the variable-width encodings
1852/// need this; the fixed-width ones are already aligned by construction.
1853fn truncate_chars(s: &str, enc: &str, max: usize) -> Vec<u8> {
1854    let bytes = decode_str(s, enc);
1855    if bytes.len() <= max {
1856        return bytes;
1857    }
1858    match enc.to_ascii_lowercase().as_str() {
1859        "utf16le" | "utf-16le" | "ucs2" | "ucs-2" => bytes[..max - max % 2].to_vec(),
1860        "hex" | "base64" | "base64url" | "ascii" | "latin1" | "binary" => bytes[..max].to_vec(),
1861        _ => {
1862            let mut end = max;
1863            while end > 0 && (bytes[end] & 0xC0) == 0x80 {
1864                end -= 1;
1865            }
1866            bytes[..end].to_vec()
1867        }
1868    }
1869}
1870
1871/// The validated byte offset for a fixed-width `buf.readXxx(offset)`.
1872///
1873/// Every read used to be `arg_num(args, 0).max(0.0) as usize` with
1874/// `bytes.get(i).unwrap_or(&0)` behind it, so an out-of-range read silently
1875/// produced zeroes instead of throwing — and a negative offset silently became
1876/// 0. Node raises one of two coded errors, and which one depends on whether the
1877/// buffer could hold the value at all:
1878///
1879/// ```text
1880/// Buffer.alloc(4).readUInt8(5)     RangeError [ERR_OUT_OF_RANGE]
1881///     The value of "offset" is out of range. It must be >= 0 and <= 3. Received 5
1882/// Buffer.alloc(0).readUInt8(0)     RangeError [ERR_BUFFER_OUT_OF_BOUNDS]
1883///     Attempt to access memory outside buffer bounds
1884/// ```
1885fn read_offset(args: &[Value], size: usize, len: usize) -> Result<usize, String> {
1886    checked_offset(args.first(), size, len)
1887}
1888
1889/// [`read_offset`] for a write, whose offset is the SECOND argument.
1890/// The BigInt a `writeBigInt64*` / `writeBigUInt64*` stores: `checkInt`
1891/// against the 64-bit range (a Number is compared too, as node's mixed `>`
1892/// does), and then a non-BigInt is refused by the BigInt arithmetic that
1893/// follows in node.
1894fn big_write_value(v: &Value, signed: bool) -> Result<num_bigint::BigInt, String> {
1895    use num_bigint::BigInt;
1896    let (min, max_excl) = if signed {
1897        (
1898            -(BigInt::from(1u8) << 63usize),
1899            BigInt::from(1u8) << 63usize,
1900        )
1901    } else {
1902        (BigInt::from(0u8), BigInt::from(1u8) << 64usize)
1903    };
1904    let range = if signed {
1905        ">= -(2n ** 63n) and < 2n ** 63n"
1906    } else {
1907        ">= 0n and < 2n ** 64n"
1908    };
1909    let out_of_range = |received: String| {
1910        crate::host::coded_error(
1911            "RangeError",
1912            "ERR_OUT_OF_RANGE",
1913            &format!(
1914                "The value of \"value\" is out of range. It must be {range}. Received {received}"
1915            ),
1916        )
1917    };
1918    match with_host(|h| h.get(v).cloned()) {
1919        Some(JsObj::BigInt(b)) => {
1920            if b < min || b >= max_excl {
1921                let mut shown = b.to_string();
1922                if b.magnitude() > &num_bigint::BigUint::from(1u64 << 32) {
1923                    shown = grouped_digits(&shown);
1924                }
1925                return Err(out_of_range(format!("{shown}n")));
1926            }
1927            Ok(b)
1928        }
1929        _ => {
1930            let n = with_host(|h| h.to_number(v));
1931            let (lo, hi) = if signed {
1932                (-(2f64.powi(63)), 2f64.powi(63))
1933            } else {
1934                (0.0, 2f64.powi(64))
1935            };
1936            if n < lo || n >= hi {
1937                return Err(out_of_range(out_of_range_received(n)));
1938            }
1939            Err(crate::host::type_error(
1940                "Cannot mix BigInt and other types, use explicit conversions",
1941            ))
1942        }
1943    }
1944}
1945
1946/// `addNumericalSeparator`: `_` every three digits from the right.
1947fn grouped_digits(shown: &str) -> String {
1948    let start = usize::from(shown.starts_with('-'));
1949    let mut i = shown.len();
1950    let mut groups = String::new();
1951    while i >= start + 4 {
1952        groups = format!("_{}{groups}", &shown[i - 3..i]);
1953        i -= 3;
1954    }
1955    format!("{}{groups}", &shown[..i])
1956}
1957
1958fn write_offset(args: &[Value], size: usize, len: usize) -> Result<usize, String> {
1959    checked_offset(args.get(1), size, len)
1960}
1961
1962/// `checkInt`'s value test from `lib/internal/buffer.js`: `value` (already
1963/// `+value`) must lie in `[min, max]`. `byte_len` is node's `byteLength`
1964/// argument there — the width minus one — which picks between the literal
1965/// bounds and the power-of-two spelling used past 32 bits.
1966fn check_int_value(value: f64, min: f64, max: f64, byte_len: usize) -> Result<(), String> {
1967    if !(value > max || value < min) {
1968        return Ok(());
1969    }
1970    let range = if byte_len > 3 {
1971        let bits = (byte_len + 1) * 8;
1972        if min == 0.0 {
1973            format!(">= 0 and < 2 ** {bits}")
1974        } else {
1975            format!(">= -(2 ** {}) and < 2 ** {}", bits - 1, bits - 1)
1976        }
1977    } else {
1978        format!(
1979            ">= {} and <= {}",
1980            crate::host::fmt_number(min),
1981            crate::host::fmt_number(max)
1982        )
1983    };
1984    Err(crate::host::coded_error(
1985        "RangeError",
1986        "ERR_OUT_OF_RANGE",
1987        &format!(
1988            "The value of \"value\" is out of range. It must be {range}. Received {}",
1989            out_of_range_received(value)
1990        ),
1991    ))
1992}
1993
1994/// The `byteLength` of the variable-width `readIntLE`/`writeUIntBE` family:
1995/// `validateNumber`, then node's `boundsError(byteLength, 6, 'byteLength')`.
1996fn variable_byte_length(v: Option<&Value>) -> Result<usize, String> {
1997    let v = v.cloned().unwrap_or(Value::Undef);
1998    if with_host(|h| h.type_of(&v)) != "number" {
1999        return Err(crate::host::invalid_arg_type(
2000            "byteLength",
2001            "argument",
2002            "number",
2003            &v,
2004        ));
2005    }
2006    let n = with_host(|h| h.to_number(&v));
2007    if n.fract() != 0.0 || n.is_nan() {
2008        return Err(crate::host::coded_error(
2009            "RangeError",
2010            "ERR_OUT_OF_RANGE",
2011            &format!(
2012                "The value of \"byteLength\" is out of range. It must be an integer. Received {}",
2013                crate::host::fmt_number(n)
2014            ),
2015        ));
2016    }
2017    if !(1.0..=6.0).contains(&n) {
2018        return Err(crate::host::coded_error(
2019            "RangeError",
2020            "ERR_OUT_OF_RANGE",
2021            &format!(
2022                "The value of \"byteLength\" is out of range. It must be >= 1 and <= 6. Received {}",
2023                crate::host::fmt_number(n)
2024            ),
2025        ));
2026    }
2027    Ok(n as usize)
2028}
2029
2030fn checked_offset(arg: Option<&Value>, size: usize, len: usize) -> Result<usize, String> {
2031    // `validateNumber(offset, 'offset')`: a present non-number is a type error.
2032    if let Some(v) = arg {
2033        if !matches!(v, Value::Undef) && with_host(|h| h.type_of(v)) != "number" {
2034            return Err(crate::host::invalid_arg_type(
2035                "offset", "argument", "number", v,
2036            ));
2037        }
2038    }
2039    if len < size {
2040        return Err(crate::host::coded_error(
2041            "RangeError",
2042            "ERR_BUFFER_OUT_OF_BOUNDS",
2043            "Attempt to access memory outside buffer bounds",
2044        ));
2045    }
2046    let max = len - size;
2047    let raw = match arg {
2048        None | Some(Value::Undef) => 0.0,
2049        Some(v) => with_host(|h| h.to_number(v)),
2050    };
2051    // A non-integer offset is its own rejection, with a different tail than the
2052    // range one — `readUInt8(1.5)` is "It must be an integer", not a bound.
2053    if raw.fract() != 0.0 || raw.is_nan() {
2054        return Err(crate::host::coded_error(
2055            "RangeError",
2056            "ERR_OUT_OF_RANGE",
2057            &format!(
2058                "The value of \"offset\" is out of range. It must be an integer. Received {}",
2059                crate::host::fmt_number(raw)
2060            ),
2061        ));
2062    }
2063    let off = raw;
2064    if off < 0.0 || off > max as f64 {
2065        return Err(crate::host::coded_error(
2066            "RangeError",
2067            "ERR_OUT_OF_RANGE",
2068            &format!(
2069                "The value of \"offset\" is out of range. It must be >= 0 and <= {max}. \
2070                 Received {}",
2071                crate::host::fmt_number(raw)
2072            ),
2073        ));
2074    }
2075    Ok(off as usize)
2076}
2077
2078/// `Buffer.copyBytesFrom(view[, offset[, length]])`, a port of `lib/buffer.js`:
2079/// a NEW Buffer holding a copy of the bytes behind `view`'s elements
2080/// `[offset, offset + length)` — `offset`/`length` count ELEMENTS, so a
2081/// `Uint16Array` contributes two bytes per element. It was absent.
2082fn copy_bytes_from(args: &[Value]) -> Result<Value, String> {
2083    let view = args.first().cloned().unwrap_or(Value::Undef);
2084    let Some(kind) = super::util_types::ta_kind(&view) else {
2085        return Err(crate::host::coded_error(
2086            "TypeError",
2087            "ERR_INVALID_ARG_TYPE",
2088            &format!(
2089                "The \"view\" argument must be an instance of TypedArray. Received {}",
2090                super::received_desc(&view)
2091            ),
2092        ));
2093    };
2094    let bytes = view_bytes(&view).unwrap_or_default();
2095    let bpe = crate::stdlib::typedarray::bytes_per_element(&kind);
2096    let len = bytes.len() / bpe;
2097    if len == 0 {
2098        return Ok(from_bytes(&[]));
2099    }
2100    let arg = |i: usize| args.get(i).filter(|v| !matches!(v, Value::Undef));
2101    let offset = match arg(1) {
2102        Some(v) => super::validate_integer(v, "offset", 0.0)? as usize,
2103        None => 0,
2104    };
2105    if offset >= len {
2106        return Ok(from_bytes(&[]));
2107    }
2108    let end = match arg(2) {
2109        Some(v) => {
2110            (offset as f64 + super::validate_integer(v, "length", 0.0)?).min(len as f64) as usize
2111        }
2112        None => len,
2113    };
2114    // `fromArrayLike(new Uint8Array(…))`: pooled like any array-like.
2115    Ok(pooled(&bytes[offset * bpe..end * bpe]))
2116}