Skip to main content

quickjs_jit_stdlib/llrt/llrt_buffer/
buffer.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_buffer/src/buffer.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py, with local patches.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::{ptr, slice};
6
7use crate::encoding::Encoder;
8use crate::utils::{
9    bytes::{get_array_bytes, get_start_end_indexes, ObjectBytes},
10    error_messages::{ERROR_MSG_ARRAY_BUFFER_DETACHED, ERROR_MSG_NOT_ARRAY_BUFFER},
11    iterable_enum,
12    primordials::Primordial,
13    result::ResultExt,
14    string::{get_coerced_string, get_string},
15};
16use rquickjs::{
17    atom::PredefinedAtom,
18    function::{Constructor, Opt},
19    prelude::{Func, Rest, This},
20    Array, ArrayBuffer, Ctx, Exception, Function, IntoJs, JsLifetime, Object, Result, TypedArray,
21    Value,
22};
23
24#[derive(JsLifetime)]
25pub struct BufferPrimordials<'js> {
26    constructor: Constructor<'js>,
27}
28
29impl<'js> Primordial<'js> for BufferPrimordials<'js> {
30    fn new(ctx: &Ctx<'js>) -> Result<Self>
31    where
32        Self: Sized,
33    {
34        let constructor: Constructor = ctx.globals().get(stringify!(Buffer))?;
35
36        Ok(Self { constructor })
37    }
38}
39
40pub struct Buffer(pub Vec<u8>);
41
42fn resolve_view_bytes<'js>(
43    ctx: &Ctx<'js>,
44    array_buffer: ArrayBuffer<'js>,
45    byte_length: usize,
46    byte_offset: usize,
47) -> Result<&'js mut [u8]> {
48    let raw = array_buffer
49        .as_raw()
50        .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED)
51        .or_throw(ctx)?;
52
53    if byte_offset > raw.len() || byte_length > raw.len() - byte_offset {
54        return Err(Exception::throw_range(
55            ctx,
56            "The value of \"byteOffset\" is out of range",
57        ));
58    }
59
60    // SAFETY: bounds checked above.
61    Ok(unsafe {
62        slice::from_raw_parts_mut(raw.cast::<u8>().as_ptr().add(byte_offset), byte_length)
63    })
64}
65
66/// A new `ArrayBuffer` of `length` bytes that QuickJS allocates, so it counts against
67/// the runtime's memory limit (an out-of-memory exception past it), zeroed and then
68/// filled by `fill`.
69pub fn new_array_buffer<'js>(
70    ctx: &Ctx<'js>,
71    length: usize,
72    fill: impl FnOnce(&mut [u8]),
73) -> Result<ArrayBuffer<'js>> {
74    // SAFETY: a null source makes QuickJS allocate `length` zeroed bytes itself.
75    let value = unsafe {
76        let raw =
77            rquickjs::qjs::JS_NewArrayBufferCopy(ctx.as_raw().as_ptr(), ptr::null(), length as _);
78        if rquickjs::qjs::JS_IsException(raw) {
79            return Err(rquickjs::Error::Exception);
80        }
81        Value::from_raw(ctx.clone(), raw)
82    };
83    let array_buffer = ArrayBuffer::from_value(value).or_throw(ctx)?;
84    if length > 0 {
85        let mut raw = array_buffer
86            .as_raw()
87            .or_throw_msg(ctx, ERROR_MSG_ARRAY_BUFFER_DETACHED)?;
88        // SAFETY: the buffer is new, so nothing else can observe it while `fill` runs.
89        fill(unsafe { raw.as_mut() });
90    }
91    Ok(array_buffer)
92}
93
94impl<'js> IntoJs<'js> for Buffer {
95    fn into_js(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
96        let array_buffer =
97            new_array_buffer(ctx, self.0.len(), |bytes| bytes.copy_from_slice(&self.0))?;
98        Self::from_array_buffer(ctx, array_buffer)
99    }
100}
101
102impl<'js> Buffer {
103    pub fn alloc(length: usize) -> Self {
104        Self(vec![0; length])
105    }
106
107    pub fn to_string(&self, ctx: &Ctx<'js>, encoding: &str) -> Result<String> {
108        Encoder::from_str(encoding)
109            .and_then(|enc| enc.encode_to_string(self.0.as_ref(), true))
110            .or_throw(ctx)
111    }
112
113    fn from_array_buffer(ctx: &Ctx<'js>, buffer: ArrayBuffer<'js>) -> Result<Value<'js>> {
114        BufferPrimordials::get(ctx)?
115            .constructor
116            .construct((buffer,))
117    }
118
119    fn from_array_buffer_offset_length(
120        ctx: &Ctx<'js>,
121        array_buffer: ArrayBuffer<'js>,
122        offset: usize,
123        length: usize,
124    ) -> Result<Value<'js>> {
125        BufferPrimordials::get(ctx)?
126            .constructor
127            .construct((array_buffer, offset, length))
128    }
129
130    fn from_encoding(
131        ctx: &Ctx<'js>,
132        mut bytes: Vec<u8>,
133        encoding: Option<String>,
134    ) -> Result<Value<'js>> {
135        if let Some(encoding) = encoding {
136            let encoder = Encoder::from_str(&encoding).or_throw(ctx)?;
137            bytes = encoder.decode(bytes).or_throw(ctx)?;
138        }
139        Buffer(bytes).into_js(ctx)
140    }
141
142    fn from_string_encoding(
143        ctx: &Ctx<'js>,
144        string: String,
145        encoding: Option<String>,
146    ) -> Result<Value<'js>> {
147        let bytes = if let Some(encoding) = encoding {
148            let encoder = Encoder::from_str(&encoding).or_throw(ctx)?;
149            encoder.decode_from_string(string).or_throw(ctx)?
150        } else {
151            string.into_bytes()
152        };
153        Buffer(bytes).into_js(ctx)
154    }
155}
156
157// Static Methods
158fn alloc<'js>(
159    ctx: Ctx<'js>,
160    length: usize,
161    fill: Opt<Value<'js>>,
162    encoding: Opt<String>,
163) -> Result<Value<'js>> {
164    if let Some(value) = fill.0 {
165        if let Some(value) = value.as_string() {
166            let string = value.to_string()?;
167
168            if let Some(encoding) = encoding.0 {
169                let encoder = Encoder::from_str(&encoding).or_throw(&ctx)?;
170                let bytes = encoder.decode_from_string(string).or_throw(&ctx)?;
171                return alloc_byte_ref(&ctx, &bytes, length);
172            }
173
174            let byte_ref = string.as_bytes();
175
176            return alloc_byte_ref(&ctx, byte_ref, length);
177        }
178        if let Some(value) = value.as_int() {
179            let array_buffer = new_array_buffer(&ctx, length, |bytes| bytes.fill(value as u8))?;
180            return Buffer::from_array_buffer(&ctx, array_buffer);
181        }
182        if let Some(obj) = value.as_object() {
183            if let Some(ob) = ObjectBytes::from_array_buffer(obj)? {
184                let bytes = ob.as_bytes(&ctx)?;
185                return alloc_byte_ref(&ctx, bytes, length);
186            }
187        }
188    }
189
190    Buffer::from_array_buffer(&ctx, new_array_buffer(&ctx, length, |_| {})?)
191}
192
193fn alloc_byte_ref<'js>(ctx: &Ctx<'js>, byte_ref: &[u8], length: usize) -> Result<Value<'js>> {
194    let byte_ref_length = byte_ref.len();
195    let array_buffer = new_array_buffer(ctx, length, |bytes| {
196        for (i, byte) in bytes.iter_mut().enumerate() {
197            *byte = byte_ref[i % byte_ref_length];
198        }
199    })?;
200    Buffer::from_array_buffer(ctx, array_buffer)
201}
202
203fn alloc_unsafe(ctx: Ctx<'_>, size: usize) -> Result<Value<'_>> {
204    Buffer::from_array_buffer(&ctx, new_array_buffer(&ctx, size, |_| {})?)
205}
206
207#[cfg(any())]
208fn maybeuninit_to_u8(vec: Vec<std::mem::MaybeUninit<u8>>) -> Vec<u8> {
209    let len = vec.len();
210    let capacity = vec.capacity();
211    let ptr = vec.as_ptr() as *mut u8;
212
213    std::mem::forget(vec);
214
215    // This conversion is safe because MaybeUninit has the same memory layout as u8, meaning the underlying bytes are identical.
216    // Since Vec<MaybeUninit> and Vec share the same memory representation, a simple reinterpretation of the pointer is valid.
217    // Additionally, Vec::from_raw_parts correctly reconstructs the vector using the original length and capacity, ensuring that memory ownership remains consistent.
218    // The call to std::mem::forget(vec) prevents the original Vec<MaybeUninit> from being dropped, avoiding double frees or memory corruption.
219    // However, this conversion is only safe if all elements of MaybeUninit are properly initialized.
220    // If any uninitialized values exist, reading them as u8 would lead to undefined behavior.
221    unsafe { Vec::from_raw_parts(ptr, len, capacity) }
222}
223
224fn alloc_unsafe_slow(ctx: Ctx<'_>, size: usize) -> Result<Value<'_>> {
225    Buffer::from_array_buffer(&ctx, new_array_buffer(&ctx, size, |_| {})?)
226}
227
228fn byte_length<'js>(ctx: Ctx<'js>, value: Value<'js>, encoding: Opt<String>) -> Result<usize> {
229    //slow path
230    if let Some(encoding) = encoding.0 {
231        let encoder = Encoder::from_str(&encoding).or_throw(&ctx)?;
232        let a = ObjectBytes::from(&ctx, &value)?;
233        let bytes = a.as_bytes(&ctx)?;
234        return Ok(encoder.decode(bytes).or_throw(&ctx)?.len());
235    }
236    //fast path
237    if let Some(val) = value.as_string() {
238        return Ok(val.to_string()?.len());
239    }
240
241    if value.is_array() {
242        let array = value.as_array().unwrap();
243
244        for val in array.iter::<u8>() {
245            val.or_throw_msg(&ctx, "array value is not u8")?;
246        }
247
248        return Ok(array.len());
249    }
250
251    if let Some(obj) = value.as_object() {
252        if let Some(ob) = ObjectBytes::from_array_buffer(obj)? {
253            return Ok(ob.as_bytes(&ctx)?.len());
254        }
255    }
256
257    Err(Exception::throw_message(
258        &ctx,
259        "value must be typed DataView, Buffer, ArrayBuffer, Uint8Array or string",
260    ))
261}
262
263fn concat<'js>(ctx: Ctx<'js>, list: Array<'js>, max_length: Opt<usize>) -> Result<Value<'js>> {
264    let mut bytes = Vec::new();
265    let mut total_length = 0;
266    let mut length;
267    for value in list.iter::<Object>() {
268        let typed_array = TypedArray::<u8>::from_object(value?)?;
269        let bytes_ref: &[u8] = unsafe { typed_array.as_slice() };
270
271        length = bytes_ref.len();
272
273        if length == 0 {
274            continue;
275        }
276
277        if let Some(max_length) = max_length.0 {
278            total_length += length;
279            if total_length > max_length {
280                let diff = max_length - (total_length - length);
281                bytes.extend_from_slice(&bytes_ref[0..diff]);
282                break;
283            }
284        }
285        bytes.extend_from_slice(bytes_ref);
286    }
287
288    Buffer(bytes).into_js(&ctx)
289}
290
291fn from<'js>(
292    ctx: Ctx<'js>,
293    value: Value<'js>,
294    offset_or_encoding: Opt<Value<'js>>,
295    length: Opt<usize>,
296) -> Result<Value<'js>> {
297    let mut encoding: Option<String> = None;
298    let mut offset = 0;
299
300    if let Some(offset_or_encoding) = offset_or_encoding.0 {
301        if offset_or_encoding.is_string() {
302            encoding = Some(offset_or_encoding.get()?);
303        } else if offset_or_encoding.is_number() {
304            offset = offset_or_encoding.get()?;
305        }
306    }
307
308    // WARN: This is currently bugged for strings that can't be converted to utf8
309    // See https://github.com/quickjs-ng/quickjs/issues/992
310    if let Some(string) = get_string(&value)? {
311        return Buffer::from_string_encoding(&ctx, string, encoding)?.into_js(&ctx);
312    }
313    if let Some(bytes) = get_array_bytes(&value, offset, length.0)? {
314        return Buffer::from_encoding(&ctx, bytes, encoding)?.into_js(&ctx);
315    }
316
317    if let Some(obj) = value.as_object() {
318        if let Some(ab_bytes) = ObjectBytes::from_array_buffer(obj)? {
319            let bytes = ab_bytes.as_bytes(&ctx)?;
320            let (start, end) = get_start_end_indexes(bytes.len(), length.0, offset);
321
322            //buffers from buffer should be copied
323            if obj
324                .get::<_, Option<String>>(PredefinedAtom::Meta)?
325                .as_deref()
326                == Some(stringify!(Buffer))
327                || encoding.is_some()
328            {
329                let bytes = bytes.into();
330                return Buffer::from_encoding(&ctx, bytes, encoding)?.into_js(&ctx);
331            } else {
332                let (array_buffer, _, source_offset) = ab_bytes.get_array_buffer()?.unwrap(); //we know it's an array buffer
333                return Buffer::from_array_buffer_offset_length(
334                    &ctx,
335                    array_buffer,
336                    start + source_offset,
337                    end - start,
338                );
339            }
340        }
341    }
342
343    if let Some(string) = get_coerced_string(&value) {
344        return Buffer::from_string_encoding(&ctx, string, encoding)?.into_js(&ctx);
345    }
346
347    Err(Exception::throw_message(
348        &ctx,
349        "value must be typed DataView, Buffer, ArrayBuffer, Uint8Array or interpretable as string",
350    ))
351}
352
353fn is_buffer<'js>(ctx: Ctx<'js>, value: Value<'js>) -> Result<bool> {
354    if let Some(object) = value.as_object() {
355        let constructor = BufferPrimordials::get(&ctx)?;
356        return Ok(object.is_instance_of(&constructor.constructor));
357    }
358
359    Ok(false)
360}
361
362fn is_encoding(value: Value) -> Result<bool> {
363    if let Some(js_string) = value.as_string() {
364        let std_string = js_string.to_string()?;
365        return Ok(Encoder::from_str(std_string.as_str()).is_ok());
366    }
367
368    Ok(false)
369}
370
371// Prototype Methods
372fn copy<'js>(
373    this: This<Object<'js>>,
374    ctx: Ctx<'js>,
375    target: ObjectBytes<'js>,
376    args: Rest<usize>,
377) -> Result<usize> {
378    let mut args_iter = args.0.into_iter();
379    let target_start = args_iter.next().unwrap_or_default();
380    let source_start = args_iter.next().unwrap_or_default();
381    let source_end = args_iter.next().unwrap_or_else(|| this.0.len());
382
383    let source_bytes = ObjectBytes::from(&ctx, this.0.as_inner())?;
384    let source_bytes = source_bytes.as_bytes(&ctx)?;
385
386    if source_start > source_bytes.len() {
387        return Err(Exception::throw_range(
388            &ctx,
389            "The value of \"sourceStart\" is out of range",
390        ));
391    }
392
393    // sourceEnd is clamped (not an error), unlike sourceStart above.
394    let source_end = source_end.min(source_bytes.len());
395
396    let mut copyable_length = 0;
397
398    if source_start >= source_end {
399        return Ok(copyable_length);
400    }
401
402    if let Some((array_buffer, target_byte_length, target_byte_offset)) =
403        target.get_array_buffer()?
404    {
405        let target_bytes =
406            resolve_view_bytes(&ctx, array_buffer, target_byte_length, target_byte_offset)?;
407
408        if target_start <= target_bytes.len() {
409            copyable_length = (source_end - source_start).min(target_bytes.len() - target_start);
410
411            target_bytes[target_start..target_start + copyable_length]
412                .copy_from_slice(&source_bytes[source_start..source_start + copyable_length]);
413        }
414    }
415
416    Ok(copyable_length)
417}
418
419fn subarray<'js>(
420    this: This<Object<'js>>,
421    ctx: Ctx<'js>,
422    start: Opt<isize>,
423    end: Opt<isize>,
424) -> Result<Value<'js>> {
425    let view = TypedArray::<u8>::from_object(this.0.clone())?;
426
427    let array_buffer = view.arraybuffer()?;
428    let view_offset = this.0.get::<_, isize>("byteOffset")?;
429    let view_length = this.0.get::<_, isize>("byteLength")?;
430
431    let start_index = start.map_or(0, |s| {
432        if s < 0 {
433            (view_length + s).max(0)
434        } else {
435            s.min(view_length)
436        }
437    });
438
439    let end_index = end.map_or(view_length, |e| {
440        if e < 0 {
441            (view_length + e).max(0)
442        } else {
443            e.min(view_length)
444        }
445    });
446
447    let length = (end_index - start_index).max(0) as usize;
448    let new_offset = (view_offset + start_index).max(0) as usize;
449
450    Buffer::from_array_buffer_offset_length(&ctx, array_buffer, new_offset, length)
451}
452
453fn to_string(
454    this: This<Object<'_>>,
455    ctx: Ctx,
456    encoding: Opt<String>,
457    start: Opt<i32>,
458    end: Opt<i32>,
459) -> Result<String> {
460    let typed_array = TypedArray::<u8>::from_object(this.0)?;
461    let bytes: &[u8] = unsafe { typed_array.as_slice() };
462
463    let start = start
464        .0
465        .map(|s| s.max(0) as usize)
466        .unwrap_or(0)
467        .min(bytes.len());
468    let end = end
469        .0
470        .map(|e| e.max(0) as usize)
471        .unwrap_or(bytes.len())
472        .min(bytes.len());
473    let bytes = &bytes[start..end];
474
475    let encoder = Encoder::from_optional_str(encoding.as_deref()).or_throw(&ctx)?;
476    encoder.encode_to_string(bytes, true).or_throw(&ctx)
477}
478
479fn write<'js>(
480    this: This<Object<'js>>,
481    ctx: Ctx<'js>,
482    string: String,
483    args: Rest<Value<'js>>,
484) -> Result<usize> {
485    let (offset, length, encoding) = get_write_parameters(&ctx, &args, this.0.len())?;
486
487    let target = ObjectBytes::from(&ctx, this.0.as_inner())?;
488
489    let mut writable_length = 0;
490
491    if let Some((array_buffer, target_byte_length, target_byte_offset)) =
492        target.get_array_buffer()?
493    {
494        let target_bytes =
495            resolve_view_bytes(&ctx, array_buffer, target_byte_length, target_byte_offset)?;
496
497        let encoder = Encoder::from_str(&encoding).or_throw(&ctx)?;
498
499        if encoder.as_label() == "utf-8" {
500            let (source_slice, valid_length) = safe_byte_slice(&string, length.min(string.len()));
501            writable_length = valid_length;
502            target_bytes[offset..offset + writable_length].copy_from_slice(source_slice);
503        } else {
504            let decode_bytes = encoder.decode_from_string(string).or_throw(&ctx)?;
505            writable_length = length.min(decode_bytes.len());
506            target_bytes[offset..offset + writable_length]
507                .copy_from_slice(&decode_bytes[..writable_length]);
508        };
509    }
510
511    Ok(writable_length)
512}
513
514fn get_write_parameters<'js>(
515    ctx: &Ctx<'js>,
516    args: &Rest<Value<'js>>,
517    len: usize,
518) -> Result<(usize, usize, String)> {
519    let mut offset = 0;
520    let mut length = len;
521    let mut encoding = "utf8".to_owned();
522
523    if let Some(v1) = args.0.first() {
524        if let Some(s) = v1.as_string() {
525            return Ok((0, len, s.to_string()?));
526        }
527        offset = v1.as_int().unwrap_or(0) as usize;
528        if offset > len {
529            return Err(Exception::throw_range(
530                ctx,
531                "The value of \"offset\" is out of range",
532            ));
533        }
534        length = len - offset;
535    }
536
537    if let Some(v2) = args.0.get(1) {
538        if let Some(s) = v2.as_string() {
539            return Ok((offset, len - offset, s.to_string()?));
540        }
541        length = v2
542            .as_int()
543            .map_or(len - offset, |l| (l as usize).min(len - offset));
544    }
545
546    if let Some(v3) = args.0.get(2) {
547        if let Some(s) = v3.as_string() {
548            encoding = s.to_string()?;
549        }
550    }
551
552    Ok((offset, length, encoding))
553}
554
555fn safe_byte_slice(s: &str, end: usize) -> (&[u8], usize) {
556    let bytes = s.as_bytes();
557
558    if bytes.len() <= end {
559        return (bytes, bytes.len());
560    }
561
562    let valid_end = s
563        .char_indices()
564        .map(|(i, _)| i)
565        .rfind(|&i| i <= end)
566        .unwrap_or(0);
567
568    (&bytes[0..valid_end], valid_end)
569}
570
571#[derive(Clone, Copy)]
572pub enum Endian {
573    Little,
574    Big,
575}
576
577#[derive(Clone, Copy, PartialEq, Eq)]
578pub enum NumberKind {
579    Int8,
580    UInt8,
581    Int16,
582    UInt16,
583    Int32,
584    UInt32,
585    Float32,
586    Float64,
587    BigInt,
588    BigUInt,
589}
590
591impl NumberKind {
592    pub fn bits(&self) -> u8 {
593        match self {
594            NumberKind::Int8 => 8,
595            NumberKind::UInt8 => 8,
596            NumberKind::Int16 => 16,
597            NumberKind::UInt16 => 16,
598            NumberKind::Int32 => 32,
599            NumberKind::UInt32 => 32,
600            NumberKind::Float32 => 32,
601            NumberKind::Float64 => 64,
602            NumberKind::BigInt => 64,
603            NumberKind::BigUInt => 64,
604        }
605    }
606
607    pub fn is_signed(&self) -> bool {
608        matches!(
609            self,
610            NumberKind::Int8 | NumberKind::Int16 | NumberKind::Int32
611        )
612    }
613
614    pub fn prototype(&self) -> &'static [(Endian, &'static str, Option<&'static str>)] {
615        match self {
616            NumberKind::Int8 => &[(Endian::Little, "Int8", None)],
617            NumberKind::UInt8 => &[(Endian::Little, "UInt8", Some("Uint8"))],
618            NumberKind::Int16 => &[
619                (Endian::Little, "Int16LE", None),
620                (Endian::Big, "Int16BE", None),
621            ],
622            NumberKind::UInt16 => &[
623                (Endian::Little, "UInt16LE", Some("Uint16LE")),
624                (Endian::Big, "UInt16BE", Some("Uint16BE")),
625            ],
626            NumberKind::Int32 => &[
627                (Endian::Little, "Int32LE", None),
628                (Endian::Big, "Int32BE", None),
629            ],
630            NumberKind::UInt32 => &[
631                (Endian::Little, "UInt32LE", Some("Uint32LE")),
632                (Endian::Big, "UInt32BE", Some("Uint32BE")),
633            ],
634            NumberKind::Float32 => &[
635                (Endian::Little, "FloatLE", None),
636                (Endian::Big, "FloatBE", None),
637            ],
638            NumberKind::Float64 => &[
639                (Endian::Little, "DoubleLE", None),
640                (Endian::Big, "DoubleBE", None),
641            ],
642            NumberKind::BigInt => &[
643                (Endian::Little, "BigInt64LE", None),
644                (Endian::Big, "BigInt64BE", None),
645            ],
646            NumberKind::BigUInt => &[
647                (Endian::Little, "BigUInt64LE", Some("BigUint64LE")),
648                (Endian::Big, "BigUInt64BE", Some("BigUint64BE")),
649            ],
650        }
651    }
652}
653
654iterable_enum!(
655    NumberKind, Int8, UInt8, Int16, UInt16, Int32, UInt32, Float32, Float64, BigInt, BigUInt
656);
657
658#[allow(clippy::too_many_arguments)]
659fn write_buf<'js>(
660    this: &This<Object<'js>>,
661    ctx: &Ctx<'js>,
662    value: &Value<'js>,
663    offset: &Opt<usize>,
664    endian: Endian,
665    kind: NumberKind,
666) -> Result<usize> {
667    let offset = offset.0.unwrap_or_default();
668
669    // Extract and convert value
670    let (byte_count, bytes) = match kind {
671        NumberKind::BigInt => {
672            let Some(bigint) = value.as_big_int() else {
673                return Err(Exception::throw_type(ctx, "Expected BigInt"));
674            };
675            let (byte_count, val) = (8, bigint.clone().to_i64().or_throw(ctx)? as u64);
676            (byte_count, endian_bytes(val, endian))
677        }
678        NumberKind::BigUInt => {
679            return Err(Exception::throw_type(ctx, "Uint64 is not supported"));
680        }
681        NumberKind::Float32 => {
682            let Some(float_val) = value.as_float() else {
683                return Err(Exception::throw_type(ctx, "Expected number"));
684            };
685            match endian {
686                Endian::Big => (4, (float_val as f32).to_bits().to_be_bytes().to_vec()),
687                Endian::Little => (4, (float_val as f32).to_bits().to_le_bytes().to_vec()),
688            }
689        }
690        NumberKind::Float64 => {
691            let Some(float_val) = value.as_float() else {
692                return Err(Exception::throw_type(ctx, "Expected number"));
693            };
694            match endian {
695                Endian::Big => (8, float_val.to_bits().to_be_bytes().to_vec()),
696                Endian::Little => (8, float_val.to_bits().to_le_bytes().to_vec()),
697            }
698        }
699        NumberKind::Int8
700        | NumberKind::UInt8
701        | NumberKind::Int16
702        | NumberKind::UInt16
703        | NumberKind::Int32
704        | NumberKind::UInt32 => {
705            let Some(int_val) = value.as_number() else {
706                return Err(Exception::throw_type(ctx, "Expected number"));
707            };
708            let int_val = int_val as i64;
709            let bit_mask = (1i64 << kind.bits()) - 1;
710            let max_val = if kind.is_signed() {
711                (1i64 << (kind.bits() - 1)) - 1
712            } else {
713                bit_mask
714            };
715            let min_val = if kind.is_signed() { -max_val - 1 } else { 0 };
716
717            if int_val < min_val || int_val > max_val {
718                return Err(Exception::throw_range(ctx, "Value out of range"));
719            }
720
721            let masked = int_val & bit_mask;
722            (
723                (kind.bits() / 8) as usize,
724                shifted_bytes(masked as u64, kind.bits(), endian),
725            )
726        }
727    };
728
729    if offset >= this.0.len() || offset + byte_count > this.0.len() {
730        return Err(Exception::throw_range(
731            ctx,
732            "The specified offset is out of range",
733        ));
734    }
735
736    let target = ObjectBytes::from(ctx, this.0.as_inner())?;
737    let mut writable_length = 0;
738
739    if let Some((array_buffer, target_byte_length, target_byte_offset)) =
740        target.get_array_buffer()?
741    {
742        let target_bytes =
743            resolve_view_bytes(ctx, array_buffer, target_byte_length, target_byte_offset)?;
744
745        writable_length = offset + bytes.len();
746        target_bytes[offset..writable_length].copy_from_slice(&bytes);
747    }
748
749    Ok(writable_length)
750}
751
752fn read_buf<'js>(
753    this: &This<Object<'js>>,
754    ctx: &Ctx<'js>,
755    offset: &Opt<usize>,
756    endian: Endian,
757    kind: NumberKind,
758) -> Result<Value<'js>> {
759    // Retrieve the array buffer
760    let target = ObjectBytes::from(ctx, this.0.as_inner())?;
761    let Some((array_buffer, target_byte_length, target_byte_offset)) = target.get_array_buffer()?
762    else {
763        return Err(Exception::throw_message(ctx, ERROR_MSG_NOT_ARRAY_BUFFER));
764    };
765    let target_bytes =
766        resolve_view_bytes(ctx, array_buffer, target_byte_length, target_byte_offset)?;
767
768    // Enforce the bounds
769    let start = offset.0.unwrap_or_default();
770    let end = start + (kind.bits() / 8) as usize;
771    if end > target_bytes.len() {
772        return Err(Exception::throw_range(
773            ctx,
774            "The value of \"offset\" is out of range",
775        ));
776    }
777
778    let bytes = &target_bytes[start..end];
779
780    let value = match kind {
781        NumberKind::BigInt => {
782            let value = match endian {
783                Endian::Big => i64::from_be_bytes(bytes.try_into().unwrap()),
784                Endian::Little => i64::from_le_bytes(bytes.try_into().unwrap()),
785            };
786            Value::new_big_int(ctx.clone(), value)?
787        }
788        NumberKind::BigUInt => {
789            return Err(Exception::throw_type(ctx, "Uint64 is not supported"));
790        }
791        NumberKind::Float32 => {
792            let value = match endian {
793                Endian::Big => f32::from_be_bytes(bytes.try_into().unwrap()),
794                Endian::Little => f32::from_le_bytes(bytes.try_into().unwrap()),
795            };
796            Value::new_float(ctx.clone(), value as f64)
797        }
798        NumberKind::Float64 => {
799            let value = match endian {
800                Endian::Big => f64::from_be_bytes(bytes.try_into().unwrap()),
801                Endian::Little => f64::from_le_bytes(bytes.try_into().unwrap()),
802            };
803            Value::new_float(ctx.clone(), value)
804        }
805        NumberKind::Int8 => {
806            let value = match endian {
807                Endian::Big => i8::from_be_bytes(bytes.try_into().unwrap()),
808                Endian::Little => i8::from_le_bytes(bytes.try_into().unwrap()),
809            };
810            Value::new_int(ctx.clone(), value as i32)
811        }
812        NumberKind::UInt8 => {
813            let value = match endian {
814                Endian::Big => u8::from_be_bytes(bytes.try_into().unwrap()),
815                Endian::Little => u8::from_le_bytes(bytes.try_into().unwrap()),
816            };
817            Value::new_int(ctx.clone(), value as i32)
818        }
819        NumberKind::Int16 => {
820            let value = match endian {
821                Endian::Big => i16::from_be_bytes(bytes.try_into().unwrap()),
822                Endian::Little => i16::from_le_bytes(bytes.try_into().unwrap()),
823            };
824            Value::new_int(ctx.clone(), value as i32)
825        }
826        NumberKind::UInt16 => {
827            let value = match endian {
828                Endian::Big => u16::from_be_bytes(bytes.try_into().unwrap()),
829                Endian::Little => u16::from_le_bytes(bytes.try_into().unwrap()),
830            };
831            Value::new_int(ctx.clone(), value as i32)
832        }
833        NumberKind::Int32 => {
834            let value = match endian {
835                Endian::Big => i32::from_be_bytes(bytes.try_into().unwrap()),
836                Endian::Little => i32::from_le_bytes(bytes.try_into().unwrap()),
837            };
838            Value::new_int(ctx.clone(), value)
839        }
840        NumberKind::UInt32 => {
841            let value = match endian {
842                Endian::Big => u32::from_be_bytes(bytes.try_into().unwrap()),
843                Endian::Little => u32::from_le_bytes(bytes.try_into().unwrap()),
844            };
845            Value::new_float(ctx.clone(), value as f64)
846        }
847    };
848    Ok(value)
849}
850
851// Pure mathematical byte generation
852fn endian_bytes(mut val: u64, endian: Endian) -> Vec<u8> {
853    let mut bytes = vec![0u8; 8];
854
855    #[allow(clippy::needless_range_loop)]
856    for i in 0..8 {
857        bytes[i] = match endian {
858            Endian::Big => (val >> (56 - i * 8)) as u8,
859            Endian::Little => (val >> (i * 8)) as u8,
860        };
861        // Clear processed bits
862        match endian {
863            Endian::Big => val &= !(0xFF << ((7 - i) * 8)),
864            Endian::Little => val &= !(0xFF << (i * 8)),
865        }
866    }
867    bytes
868}
869
870fn shifted_bytes(mut val: u64, bits: u8, endian: Endian) -> Vec<u8> {
871    let byte_count = (bits / 8) as usize;
872    let mut bytes = vec![0u8; byte_count];
873
874    #[allow(clippy::needless_range_loop)]
875    for i in 0..byte_count {
876        let shift = match endian {
877            Endian::Big => (byte_count - 1 - i) * 8,
878            Endian::Little => i * 8,
879        };
880        bytes[i] = (val >> shift) as u8;
881        val &= !(0xFF << shift); // Clear processed bits
882    }
883    bytes
884}
885
886pub(crate) fn set_prototype<'js>(ctx: &Ctx<'js>, constructor: Object<'js>) -> Result<()> {
887    let _ = &constructor.set("alloc", Func::from(alloc))?;
888    let _ = &constructor.set("allocUnsafe", Func::from(alloc_unsafe))?;
889    let _ = &constructor.set("allocUnsafeSlow", Func::from(alloc_unsafe_slow))?;
890    let _ = &constructor.set("byteLength", Func::from(byte_length))?;
891    let _ = &constructor.set("concat", Func::from(concat))?;
892    let _ = &constructor.set(PredefinedAtom::From, Func::from(from))?;
893    let _ = &constructor.set("isBuffer", Func::from(is_buffer))?;
894    let _ = &constructor.set("isEncoding", Func::from(is_encoding))?;
895
896    let prototype: &Object = &constructor.get(PredefinedAtom::Prototype)?;
897    prototype.set("copy", Func::from(copy))?;
898    prototype.set("subarray", Func::from(subarray))?;
899    prototype.set(PredefinedAtom::ToString, Func::from(to_string))?;
900    prototype.set("write", Func::from(write))?;
901
902    // Set all write and read methods
903    for kind in NumberKind::iter() {
904        for (endian, name, alias) in kind.prototype() {
905            let write_func = Function::new(ctx.clone(), |t, c, v, o| {
906                write_buf(&t, &c, &v, &o, *endian, *kind)
907            })?;
908            let read_func =
909                Function::new(ctx.clone(), |t, c, o| read_buf(&t, &c, &o, *endian, *kind))?;
910            if let Some(alias) = alias {
911                prototype.set(["write", alias].concat(), write_func.clone())?;
912                prototype.set(["read", alias].concat(), read_func.clone())?;
913            }
914            prototype.set(["write", name].concat(), write_func)?;
915            prototype.set(["read", name].concat(), read_func)?;
916        }
917    }
918
919    //not assessable from js
920    prototype.prop(PredefinedAtom::Meta, stringify!(Buffer))?;
921
922    ctx.globals().set(stringify!(Buffer), constructor)?;
923
924    Ok(())
925}
926
927#[cfg(test)]
928mod tests {
929    use crate::test_support::{call_test, test_async_with, ModuleEvaluator};
930
931    use crate::buffer::BufferModule;
932
933    #[tokio::test]
934    async fn test_subarray() {
935        test_async_with(|ctx| {
936            Box::pin(async move {
937                crate::buffer::init(&ctx).unwrap();
938                ModuleEvaluator::eval_rust::<BufferModule>(ctx.clone(), "buffer")
939                    .await
940                    .unwrap();
941
942                let data = "hello world".to_string().into_bytes();
943                let module = ModuleEvaluator::eval_js(
944                    ctx.clone(),
945                    "test",
946                    r#"
947                        import { Buffer } from 'buffer';
948
949                        export async function test(data) {
950                            let buffer = Buffer.from(data);
951                            let sub = buffer.subarray(6, 11); // "world" part
952                            return sub.toString();
953                        }
954                    "#,
955                )
956                .await
957                .unwrap();
958                let result = call_test::<String, _>(&ctx, &module, (data,)).await;
959                assert_eq!(result, "world");
960            })
961        })
962        .await;
963    }
964
965    #[tokio::test]
966    async fn test_subarray_partial() {
967        test_async_with(|ctx| {
968            Box::pin(async move {
969                crate::buffer::init(&ctx).unwrap();
970                ModuleEvaluator::eval_rust::<BufferModule>(ctx.clone(), "buffer")
971                    .await
972                    .unwrap();
973
974                let data = "hello world".to_string().into_bytes();
975                let module = ModuleEvaluator::eval_js(
976                    ctx.clone(),
977                    "test",
978                    r#"
979                        import { Buffer } from 'buffer';
980
981                        export async function test(data) {
982                            let buffer = Buffer.from(data);
983                            let sub = buffer.subarray(0, 5); // "hello" part
984                            return sub.toString();
985                        }
986                    "#,
987                )
988                .await
989                .unwrap();
990                let result = call_test::<String, _>(&ctx, &module, (data,)).await;
991                assert_eq!(result, "hello");
992            })
993        })
994        .await;
995    }
996
997    #[tokio::test]
998    async fn test_subarray_out_of_bounds() {
999        test_async_with(|ctx| {
1000            Box::pin(async move {
1001                crate::buffer::init(&ctx).unwrap();
1002                ModuleEvaluator::eval_rust::<BufferModule>(ctx.clone(), "buffer")
1003                    .await
1004                    .unwrap();
1005
1006                let data = "hello world".to_string().into_bytes();
1007                let module = ModuleEvaluator::eval_js(
1008                    ctx.clone(),
1009                    "test",
1010                    r#"
1011                        import { Buffer } from 'buffer';
1012
1013                        export async function test(data) {
1014                            let buffer = Buffer.from(data);
1015                            let sub = buffer.subarray(6, 20); // "world" part but goes out of bounds
1016                            return sub.toString();
1017                        }
1018                    "#,
1019                )
1020                .await
1021                .unwrap();
1022                let result = call_test::<String, _>(&ctx, &module, (data,)).await;
1023                assert_eq!(result, "world");
1024            })
1025        })
1026        .await;
1027    }
1028
1029    #[tokio::test]
1030    async fn test_read_int_32_be() {
1031        test_async_with(|ctx| {
1032            Box::pin(async move {
1033                crate::buffer::init(&ctx).unwrap();
1034                ModuleEvaluator::eval_rust::<BufferModule>(ctx.clone(), "buffer")
1035                    .await
1036                    .unwrap();
1037
1038                let data = "hello world".to_string().into_bytes();
1039                let module = ModuleEvaluator::eval_js(
1040                    ctx.clone(),
1041                    "test",
1042                    r#"
1043                        import { Buffer } from 'buffer';
1044
1045                        export async function test(data) {
1046                            const buf = Buffer.from([1, 2, 3, 4, 0, 0, 0, 0]);
1047                            return buf.readInt32BE();
1048                        }
1049                    "#,
1050                )
1051                .await
1052                .unwrap();
1053                let result = call_test::<i32, _>(&ctx, &module, (data,)).await;
1054                assert_eq!(result, 0x01020304);
1055            })
1056        })
1057        .await;
1058    }
1059}