Skip to main content

quickjs_jit_stdlib/llrt/llrt_utils/
bytes.rs

1// Vendored from LLRT d9fd873e793c (libs/llrt_utils/src/bytes.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
4// SPDX-License-Identifier: Apache-2.0
5use std::rc::Rc;
6
7use half::f16;
8use rquickjs::{
9    atom::PredefinedAtom,
10    class::{Trace, Tracer},
11    function::Constructor,
12    ArrayBuffer, Coerced, Ctx, Exception, FromJs, IntoJs, JsLifetime, Object, Result, TypedArray,
13    U8Clamped, Value,
14};
15
16/// Convert a JS string to a `String`, replacing lone UTF-16 surrogates
17/// with U+FFFD per WHATWG USVString. Use when ill-formed strings must
18/// not fail.
19//
20// SAFETY (module-wide): QuickJS only emits valid WTF-8, so any run
21// without 0xED is valid strict UTF-8.
22pub fn get_lossy_string(string_value: Value) -> Result<String> {
23    let bytes = get_wtf8_string_bytes(string_value)?;
24
25    let first = match memchr::memchr(0xED, &bytes) {
26        None => return Ok(unsafe { String::from_utf8_unchecked(bytes) }),
27        Some(idx) => idx,
28    };
29    let mut result = String::with_capacity(bytes.len());
30    result.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[..first]) });
31    qjs_substitute_into(&bytes[first..], &mut result);
32    Ok(result)
33}
34
35fn qjs_substitute_into(bytes: &[u8], result: &mut String) {
36    let mut start = 0;
37    while start < bytes.len() {
38        let next_ed = match memchr::memchr(0xED, &bytes[start..]) {
39            None => {
40                result.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[start..]) });
41                return;
42            }
43            Some(rel) => start + rel,
44        };
45        if next_ed > start {
46            result.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[start..next_ed]) });
47        }
48        if next_ed + 3 > bytes.len() {
49            replace_invalid_utf8_and_utf16_into(&bytes[next_ed..], result);
50            return;
51        }
52        let b1 = bytes[next_ed + 1];
53        let b2 = bytes[next_ed + 2];
54        if (b1 & 0xC0) != 0x80 || (b2 & 0xC0) != 0x80 {
55            replace_invalid_utf8_and_utf16_into(&bytes[next_ed..], result);
56            return;
57        }
58        if (b1 & 0xE0) == 0xA0 {
59            result.push('\u{FFFD}');
60        } else {
61            result.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[next_ed..next_ed + 3]) });
62        }
63        start = next_ed + 3;
64    }
65}
66
67#[doc(hidden)]
68pub fn replace_invalid_utf8_and_utf16(bytes: &[u8]) -> String {
69    let err = match simdutf8::compat::from_utf8(bytes) {
70        Ok(s) => return s.to_owned(),
71        Err(e) => e,
72    };
73    let valid_up_to = err.valid_up_to();
74    let mut result = String::with_capacity(bytes.len());
75    result.push_str(unsafe { std::str::from_utf8_unchecked(&bytes[..valid_up_to]) });
76    replace_invalid_utf8_and_utf16_into(&bytes[valid_up_to..], &mut result);
77    result
78}
79
80fn replace_invalid_utf8_and_utf16_into(bytes: &[u8], result: &mut String) {
81    let mut i = 0;
82
83    while i < bytes.len() {
84        let current = bytes[i];
85        match current {
86            0x00..=0x7F => {
87                result.push(current as char);
88                i += 1;
89            }
90            0xC0..=0xDF if i + 1 < bytes.len() => {
91                let next = bytes[i + 1];
92                if (next & 0xC0) == 0x80 {
93                    let code_point = ((current as u32 & 0x1F) << 6) | (next as u32 & 0x3F);
94                    result.push(char::from_u32(code_point).unwrap_or('\u{FFFD}'));
95                    i += 2;
96                } else {
97                    result.push('\u{FFFD}');
98                    i += 1;
99                }
100            }
101            0xE0..=0xEF if i + 2 < bytes.len() => {
102                let next1 = bytes[i + 1];
103                let next2 = bytes[i + 2];
104                if (next1 & 0xC0) == 0x80 && (next2 & 0xC0) == 0x80 {
105                    let code_point = ((current as u32 & 0x0F) << 12)
106                        | ((next1 as u32 & 0x3F) << 6)
107                        | (next2 as u32 & 0x3F);
108                    result.push(char::from_u32(code_point).unwrap_or('\u{FFFD}'));
109                    i += 3;
110                } else {
111                    result.push('\u{FFFD}');
112                    i += 1;
113                }
114            }
115            0xF0..=0xF7 if i + 3 < bytes.len() => {
116                let next1 = bytes[i + 1];
117                let next2 = bytes[i + 2];
118                let next3 = bytes[i + 3];
119                if (next1 & 0xC0) == 0x80 && (next2 & 0xC0) == 0x80 && (next3 & 0xC0) == 0x80 {
120                    let code_point = ((current as u32 & 0x07) << 18)
121                        | ((next1 as u32 & 0x3F) << 12)
122                        | ((next2 as u32 & 0x3F) << 6)
123                        | (next3 as u32 & 0x3F);
124                    result.push(char::from_u32(code_point).unwrap_or('\u{FFFD}'));
125                    i += 4;
126                } else {
127                    result.push('\u{FFFD}');
128                    i += 1;
129                }
130            }
131            _ => {
132                result.push('\u{FFFD}');
133                i += 1;
134            }
135        }
136    }
137}
138
139#[cfg(test)]
140mod replace_invalid_utf8_tests {
141    use super::replace_invalid_utf8_and_utf16;
142
143    fn cases() -> Vec<(&'static str, Vec<u8>, &'static str)> {
144        vec![
145            ("empty", vec![], ""),
146            ("ascii", b"hello world".to_vec(), "hello world"),
147            (
148                "ascii_with_control",
149                vec![b'a', 0x00, b'b', 0x7f, b'c'],
150                "a\u{0}b\u{7f}c",
151            ),
152            ("two_byte_latin1", vec![0xC3, 0xA9], "\u{00E9}"),
153            ("three_byte_cjk", vec![0xE4, 0xB8, 0x96], "\u{4e16}"),
154            ("four_byte_emoji", vec![0xF0, 0x9F, 0xA6, 0x80], "\u{1f980}"),
155            ("lone_high_surrogate", vec![0xED, 0xA0, 0xBD], "\u{FFFD}"),
156            ("lone_low_surrogate", vec![0xED, 0xB0, 0x80], "\u{FFFD}"),
157            (
158                "surrogate_pair_in_wtf8",
159                vec![0xED, 0xA0, 0xBD, 0xED, 0xB2, 0xA9],
160                "\u{FFFD}\u{FFFD}",
161            ),
162            ("stray_continuation", vec![0x80], "\u{FFFD}"),
163            ("truncated_two_byte", vec![0xC3], "\u{FFFD}"),
164            ("truncated_three_byte", vec![0xE0, 0xA0], "\u{FFFD}\u{FFFD}"),
165            (
166                "truncated_four_byte",
167                vec![0xF0, 0x9F, 0xA6],
168                "\u{FFFD}\u{FFFD}\u{FFFD}",
169            ),
170            (
171                "two_byte_bad_continuation",
172                vec![0xC3, 0x20, b'a'],
173                "\u{FFFD} a",
174            ),
175            (
176                "three_byte_bad_continuation",
177                vec![0xE4, 0xB8, 0x20, b'a'],
178                "\u{FFFD}\u{FFFD} a",
179            ),
180            ("high_byte_above_f7", vec![0xF8, b'a'], "\u{FFFD}a"),
181            (
182                "mixed_valid_and_invalid",
183                {
184                    let mut v = b"hello ".to_vec();
185                    v.extend_from_slice(&[0xED, 0xA0, 0xBD]);
186                    v.extend_from_slice(" world".as_bytes());
187                    v
188                },
189                "hello \u{FFFD} world",
190            ),
191            (
192                "long_ascii",
193                b"the quick brown fox jumps over the lazy dog".repeat(20),
194                &*Box::leak(
195                    "the quick brown fox jumps over the lazy dog"
196                        .repeat(20)
197                        .into_boxed_str(),
198                ),
199            ),
200        ]
201    }
202
203    #[test]
204    fn matches_contract() {
205        for (name, input, expected) in cases() {
206            let got = replace_invalid_utf8_and_utf16(&input);
207            assert_eq!(
208                got, expected,
209                "case `{}`: got {:?}, expected {:?}",
210                name, got, expected
211            );
212        }
213    }
214}
215
216use crate::utils::{error_messages::ERROR_MSG_ARRAY_BUFFER_DETACHED, result::ResultExt};
217
218#[derive(Clone, PartialEq)]
219pub enum ObjectBytes<'js> {
220    U8Array(TypedArray<'js, u8>),
221    I8Array(TypedArray<'js, i8>),
222    U16Array(TypedArray<'js, u16>),
223    I16Array(TypedArray<'js, i16>),
224    U32Array(TypedArray<'js, u32>),
225    I32Array(TypedArray<'js, i32>),
226    U64Array(TypedArray<'js, u64>),
227    I64Array(TypedArray<'js, i64>),
228    F16Array(TypedArray<'js, f16>),
229    F32Array(TypedArray<'js, f32>),
230    F64Array(TypedArray<'js, f64>),
231    U8ClampedArray(TypedArray<'js, U8Clamped>),
232    DataView(ArrayBuffer<'js>, usize, usize), // buffer, offset, length
233    Vec(Vec<u8>),
234}
235
236// Requires manual implementation because rquickjs hasn't implemented JsLifetime for f32 or f64
237unsafe impl<'js> JsLifetime<'js> for ObjectBytes<'js> {
238    type Changed<'to> = ObjectBytes<'to>;
239}
240
241impl<'js> Trace<'js> for ObjectBytes<'js> {
242    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
243        match self {
244            ObjectBytes::U8Array(a) => a.trace(tracer),
245            ObjectBytes::I8Array(a) => a.trace(tracer),
246            ObjectBytes::U16Array(a) => a.trace(tracer),
247            ObjectBytes::I16Array(a) => a.trace(tracer),
248            ObjectBytes::U32Array(a) => a.trace(tracer),
249            ObjectBytes::I32Array(a) => a.trace(tracer),
250            ObjectBytes::U64Array(a) => a.trace(tracer),
251            ObjectBytes::I64Array(a) => a.trace(tracer),
252            ObjectBytes::F16Array(a) => a.trace(tracer),
253            ObjectBytes::F32Array(a) => a.trace(tracer),
254            ObjectBytes::F64Array(a) => a.trace(tracer),
255            ObjectBytes::U8ClampedArray(a) => a.trace(tracer),
256            ObjectBytes::DataView(ab, _, _) => ab.trace(tracer),
257            ObjectBytes::Vec(v) => v.trace(tracer),
258        }
259    }
260}
261
262impl<'js> IntoJs<'js> for ObjectBytes<'js> {
263    fn into_js(self, ctx: &Ctx<'js>) -> Result<Value<'js>> {
264        match self {
265            ObjectBytes::U8Array(a) => a.into_js(ctx),
266            ObjectBytes::I8Array(a) => a.into_js(ctx),
267            ObjectBytes::U16Array(a) => a.into_js(ctx),
268            ObjectBytes::I16Array(a) => a.into_js(ctx),
269            ObjectBytes::U32Array(a) => a.into_js(ctx),
270            ObjectBytes::I32Array(a) => a.into_js(ctx),
271            ObjectBytes::U64Array(a) => a.into_js(ctx),
272            ObjectBytes::I64Array(a) => a.into_js(ctx),
273            ObjectBytes::F16Array(a) => a.into_js(ctx),
274            ObjectBytes::F32Array(a) => a.into_js(ctx),
275            ObjectBytes::F64Array(a) => a.into_js(ctx),
276            ObjectBytes::U8ClampedArray(a) => a.into_js(ctx),
277            ObjectBytes::DataView(ab, _, _) => {
278                let ctor: Constructor = ctx.globals().get(PredefinedAtom::DataView)?;
279                ctor.construct((ab,))
280            }
281            ObjectBytes::Vec(v) => v.into_js(ctx),
282        }
283    }
284}
285
286impl<'js> TryFrom<ObjectBytes<'js>> for Vec<u8> {
287    type Error = Rc<str>;
288    fn try_from(value: ObjectBytes<'js>) -> std::result::Result<Self, Self::Error> {
289        value.into_bytes_inner()
290    }
291}
292
293impl<'a, 'js> TryFrom<&'a ObjectBytes<'js>> for &'a [u8] {
294    type Error = Rc<str>;
295    fn try_from(value: &'a ObjectBytes<'js>) -> std::result::Result<Self, Self::Error> {
296        value.as_bytes_inner()
297    }
298}
299
300impl<'js> FromJs<'js> for ObjectBytes<'js> {
301    fn from_js(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Self> {
302        Self::from_offset(ctx, &value, 0, None)
303    }
304}
305
306impl<'js> ObjectBytes<'js> {
307    pub fn from(ctx: &Ctx<'js>, value: &Value<'js>) -> Result<Self> {
308        Self::from_offset(ctx, value, 0, None)
309    }
310
311    pub fn from_offset(
312        ctx: &Ctx<'js>,
313        value: &Value<'js>,
314        offset: usize,
315        length: Option<usize>,
316    ) -> Result<Self> {
317        if value.is_undefined() {
318            return Ok(ObjectBytes::Vec(vec![]));
319        }
320        if let Some(bytes) = get_string_bytes(value, offset, length)? {
321            return Ok(ObjectBytes::Vec(bytes));
322        }
323        if let Some(bytes) = get_array_bytes(value, offset, length)? {
324            return Ok(ObjectBytes::Vec(bytes));
325        }
326
327        if let Some(obj) = value.as_object() {
328            if let Some(bytes) = Self::from_array_buffer(obj)? {
329                return Ok(bytes);
330            }
331        }
332
333        if let Some(bytes) = get_coerced_string_bytes(value, offset, length) {
334            return Ok(ObjectBytes::Vec(bytes));
335        }
336
337        Err(Exception::throw_message(
338        ctx,
339        "value must be typed DataView, Buffer, ArrayBuffer, Uint8Array or interpretable as string",
340    ))
341    }
342
343    pub fn as_bytes(&self, ctx: &Ctx<'js>) -> Result<&[u8]> {
344        self.as_bytes_inner().or_throw(ctx)
345    }
346
347    /// Returns the underlying bytes, or `None` if the buffer is detached or
348    /// the DataView range is invalid (including arithmetic overflow). Unlike
349    /// [`as_bytes`], does not raise a JS exception.
350    pub fn as_bytes_opt(&self) -> Option<&[u8]> {
351        self.as_bytes_inner().ok()
352    }
353
354    fn as_bytes_inner(&self) -> std::result::Result<&[u8], Rc<str>> {
355        // Safety: the returned slice is used immediately and no JS runs while
356        // it's alive, so the backing store can't be written, detached, or
357        // reallocated out from under it.
358        unsafe {
359            match self {
360                ObjectBytes::U8Array(array) => array.as_bytes(),
361                ObjectBytes::I8Array(array) => array.as_bytes(),
362                ObjectBytes::U16Array(array) => array.as_bytes(),
363                ObjectBytes::I16Array(array) => array.as_bytes(),
364                ObjectBytes::U32Array(array) => array.as_bytes(),
365                ObjectBytes::I32Array(array) => array.as_bytes(),
366                ObjectBytes::U64Array(array) => array.as_bytes(),
367                ObjectBytes::I64Array(array) => array.as_bytes(),
368                ObjectBytes::F16Array(array) => array.as_bytes(),
369                ObjectBytes::F32Array(array) => array.as_bytes(),
370                ObjectBytes::F64Array(array) => array.as_bytes(),
371                ObjectBytes::U8ClampedArray(array) => array.as_bytes(),
372                ObjectBytes::DataView(ab, offset, length) => ab.as_bytes().and_then(|bytes| {
373                    let end = offset.checked_add(*length)?;
374                    bytes.get(*offset..end)
375                }),
376                ObjectBytes::Vec(bytes) => Some(bytes.as_ref()),
377            }
378        }
379        .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED.into())
380    }
381
382    pub fn into_bytes(self, ctx: &Ctx<'_>) -> Result<Vec<u8>> {
383        self.into_bytes_inner().or_throw(ctx)
384    }
385
386    fn into_bytes_inner(self) -> std::result::Result<Vec<u8>, Rc<str>> {
387        if let ObjectBytes::Vec(bytes) = self {
388            return Ok(bytes);
389        }
390        Ok(self.as_bytes_inner()?.to_vec())
391    }
392
393    pub fn from_array_buffer(obj: &Object<'js>) -> Result<Option<ObjectBytes<'js>>> {
394        //most common
395        if let Ok(typed_array) = TypedArray::<u8>::from_object(obj.clone()) {
396            return Ok(Some(ObjectBytes::U8Array(typed_array)));
397        }
398        //second most common
399        if let Some(array_buffer) = ArrayBuffer::from_object(obj.clone()) {
400            let len = array_buffer.len();
401            return Ok(Some(ObjectBytes::DataView(array_buffer, 0, len)));
402        }
403
404        if let Ok(typed_array) = TypedArray::<i8>::from_object(obj.clone()) {
405            return Ok(Some(ObjectBytes::I8Array(typed_array)));
406        }
407
408        if let Ok(typed_array) = TypedArray::<u16>::from_object(obj.clone()) {
409            return Ok(Some(ObjectBytes::U16Array(typed_array)));
410        }
411
412        if let Ok(typed_array) = TypedArray::<i16>::from_object(obj.clone()) {
413            return Ok(Some(ObjectBytes::I16Array(typed_array)));
414        }
415
416        if let Ok(typed_array) = TypedArray::<u32>::from_object(obj.clone()) {
417            return Ok(Some(ObjectBytes::U32Array(typed_array)));
418        }
419
420        if let Ok(typed_array) = TypedArray::<i32>::from_object(obj.clone()) {
421            return Ok(Some(ObjectBytes::I32Array(typed_array)));
422        }
423
424        if let Ok(typed_array) = TypedArray::<u64>::from_object(obj.clone()) {
425            return Ok(Some(ObjectBytes::U64Array(typed_array)));
426        }
427
428        if let Ok(typed_array) = TypedArray::<i64>::from_object(obj.clone()) {
429            return Ok(Some(ObjectBytes::I64Array(typed_array)));
430        }
431
432        if let Ok(typed_array) = TypedArray::<f16>::from_object(obj.clone()) {
433            return Ok(Some(ObjectBytes::F16Array(typed_array)));
434        }
435
436        if let Ok(typed_array) = TypedArray::<f32>::from_object(obj.clone()) {
437            return Ok(Some(ObjectBytes::F32Array(typed_array)));
438        }
439
440        if let Ok(typed_array) = TypedArray::<f64>::from_object(obj.clone()) {
441            return Ok(Some(ObjectBytes::F64Array(typed_array)));
442        }
443
444        if let Ok(typed_array) = TypedArray::<U8Clamped>::from_object(obj.clone()) {
445            return Ok(Some(ObjectBytes::U8ClampedArray(typed_array)));
446        }
447
448        if let Ok(ab) = obj.get::<_, ArrayBuffer>("buffer") {
449            let offset: usize = obj.get("byteOffset").unwrap_or(0);
450            let length: usize = obj.get("byteLength").unwrap_or_else(|_| ab.len());
451            return Ok(Some(ObjectBytes::DataView(ab, offset, length)));
452        }
453
454        Ok(None)
455    }
456
457    pub fn get_array_buffer(&self) -> Result<Option<(ArrayBuffer<'js>, usize, usize)>> {
458        let buffer = match self {
459            ObjectBytes::U8Array(typed_array) => {
460                let byte_length = typed_array.len();
461                (
462                    typed_array.arraybuffer()?,
463                    byte_length,
464                    typed_array.get("byteOffset")?,
465                )
466            }
467            ObjectBytes::I8Array(typed_array) => {
468                let byte_length = typed_array.len();
469                (
470                    typed_array.arraybuffer()?,
471                    byte_length,
472                    typed_array.get("byteOffset")?,
473                )
474            }
475            ObjectBytes::U16Array(typed_array) => {
476                let byte_length = typed_array.len() * 2;
477                (
478                    typed_array.arraybuffer()?,
479                    byte_length,
480                    typed_array.get("byteOffset")?,
481                )
482            }
483            ObjectBytes::I16Array(typed_array) => {
484                let byte_length = typed_array.len() * 2;
485                (
486                    typed_array.arraybuffer()?,
487                    byte_length,
488                    typed_array.get("byteOffset")?,
489                )
490            }
491            ObjectBytes::U32Array(typed_array) => {
492                let byte_length = typed_array.len() * 4;
493                (
494                    typed_array.arraybuffer()?,
495                    byte_length,
496                    typed_array.get("byteOffset")?,
497                )
498            }
499            ObjectBytes::I32Array(typed_array) => {
500                let byte_length = typed_array.len() * 4;
501                (
502                    typed_array.arraybuffer()?,
503                    byte_length,
504                    typed_array.get("byteOffset")?,
505                )
506            }
507            ObjectBytes::U64Array(typed_array) => {
508                let byte_length = typed_array.len() * 8;
509                (
510                    typed_array.arraybuffer()?,
511                    byte_length,
512                    typed_array.get("byteOffset")?,
513                )
514            }
515            ObjectBytes::I64Array(typed_array) => {
516                let byte_length = typed_array.len() * 8;
517                (
518                    typed_array.arraybuffer()?,
519                    byte_length,
520                    typed_array.get("byteOffset")?,
521                )
522            }
523            ObjectBytes::F16Array(typed_array) => {
524                let byte_length = typed_array.len() * 2;
525                (
526                    typed_array.arraybuffer()?,
527                    byte_length,
528                    typed_array.get("byteOffset")?,
529                )
530            }
531            ObjectBytes::F32Array(typed_array) => {
532                let byte_length = typed_array.len() * 4;
533                (
534                    typed_array.arraybuffer()?,
535                    byte_length,
536                    typed_array.get("byteOffset")?,
537                )
538            }
539            ObjectBytes::F64Array(typed_array) => {
540                let byte_length = typed_array.len() * 8;
541                (
542                    typed_array.arraybuffer()?,
543                    byte_length,
544                    typed_array.get("byteOffset")?,
545                )
546            }
547            ObjectBytes::U8ClampedArray(typed_array) => {
548                let byte_length = typed_array.len();
549                (
550                    typed_array.arraybuffer()?,
551                    byte_length,
552                    typed_array.get("byteOffset")?,
553                )
554            }
555            ObjectBytes::DataView(array_buffer, offset, length) => {
556                (array_buffer.clone(), *length, *offset)
557            }
558            _ => return Ok(None),
559        };
560
561        Ok(Some(buffer))
562    }
563}
564
565#[cfg(test)]
566mod object_bytes_tests {
567    use super::{ObjectBytes, ERROR_MSG_ARRAY_BUFFER_DETACHED};
568    use rquickjs::{ArrayBuffer, Context, Runtime};
569
570    #[test]
571    fn data_view_ranges_are_checked() {
572        let rt = Runtime::new().unwrap();
573        let ctx = Context::full(&rt).unwrap();
574
575        ctx.with(|ctx| {
576            let buffer = ArrayBuffer::new_copy(ctx, [1_u8, 2, 3, 4]).unwrap();
577            for (offset, length) in [(3, 2), (usize::MAX, 1)] {
578                let bytes = ObjectBytes::DataView(buffer.clone(), offset, length);
579
580                assert_eq!(
581                    bytes.as_bytes_inner().unwrap_err().as_ref(),
582                    ERROR_MSG_ARRAY_BUFFER_DETACHED
583                );
584            }
585
586            let valid_bytes = ObjectBytes::DataView(buffer, 1, 2);
587            assert_eq!(valid_bytes.as_bytes_inner().unwrap(), &[2, 3]);
588        });
589    }
590
591    #[test]
592    fn data_view_detached_buffer_returns_error() {
593        let rt = Runtime::new().unwrap();
594        let ctx = Context::full(&rt).unwrap();
595
596        ctx.with(|ctx| {
597            let mut buffer = ArrayBuffer::new_copy(ctx, [1_u8, 2, 3, 4]).unwrap();
598            buffer.detach();
599            let bytes = ObjectBytes::DataView(buffer, 0, 4);
600
601            assert_eq!(
602                bytes.as_bytes_inner().unwrap_err().as_ref(),
603                ERROR_MSG_ARRAY_BUFFER_DETACHED
604            );
605        });
606    }
607}
608
609pub fn get_start_end_indexes(
610    source_len: usize,
611    target_len: Option<usize>,
612    offset: usize,
613) -> (usize, usize) {
614    if offset > source_len {
615        return (0, 0);
616    }
617
618    let target_len = target_len.unwrap_or(source_len - offset);
619
620    if offset + target_len > source_len {
621        return (offset, source_len);
622    }
623
624    (offset, target_len + offset)
625}
626
627pub fn get_array_bytes(
628    value: &Value<'_>,
629    offset: usize,
630    length: Option<usize>,
631) -> Result<Option<Vec<u8>>> {
632    if value.is_array() {
633        let array = value.as_array().unwrap();
634        let (start, end) = get_start_end_indexes(array.len(), length, offset);
635        let size = end - start;
636        let mut bytes: Vec<u8> = Vec::with_capacity(size);
637
638        for val in array.iter::<u8>().skip(start).take(size) {
639            let val: u8 = val?;
640            bytes.push(val);
641        }
642
643        return Ok(Some(bytes));
644    }
645    Ok(None)
646}
647
648pub fn get_coerced_string_bytes(
649    value: &Value<'_>,
650    offset: usize,
651    length: Option<usize>,
652) -> Option<Vec<u8>> {
653    if let Ok(val) = value.get::<Coerced<String>>() {
654        return Some(bytes_from_js_string(val.0, offset, length));
655    };
656    None
657}
658
659fn bytes_from_js_string(string: String, offset: usize, length: Option<usize>) -> Vec<u8> {
660    let (start, end) = get_start_end_indexes(string.len(), length, offset);
661    string.as_bytes()[start..end].to_vec()
662}
663
664#[inline]
665pub fn get_string_bytes(
666    value: &Value<'_>,
667    offset: usize,
668    length: Option<usize>,
669) -> Result<Option<Vec<u8>>> {
670    if value.is_string() {
671        let string = get_lossy_string(value.clone())?;
672        return Ok(Some(bytes_from_js_string(string, offset, length)));
673    }
674    Ok(None)
675}
676
677pub fn get_wtf8_string_bytes(value: Value<'_>) -> Result<Vec<u8>> {
678    let ctx = value.ctx().clone();
679    let string = value
680        .into_string()
681        .ok_or_else(|| Exception::throw_type(&ctx, "value must be a string"))?;
682    let cstr = string.to_cstring()?;
683    let bytes: &[u8] = cstr.as_ref();
684    Ok(bytes.to_vec())
685}
686
687pub fn encode_wtf8(bytes: &[u8], pending: &mut Option<u16>, output: &mut Vec<u8>) {
688    let mut index = 0;
689    while index < bytes.len() {
690        let (code_point, width) = decode_wtf8(bytes, index);
691        index += width;
692        let unit = code_point as u16;
693        if let Some(high) = pending.take() {
694            if (0xdc00..=0xdfff).contains(&unit) {
695                let scalar = 0x10000 + (((high - 0xd800) as u32) << 10) + (unit - 0xdc00) as u32;
696                append_code_point(scalar, output);
697                continue;
698            }
699            append_code_point(0xfffd, output);
700        }
701        if (0xd800..=0xdbff).contains(&unit) {
702            *pending = Some(unit);
703        } else if (0xdc00..=0xdfff).contains(&unit) {
704            append_code_point(0xfffd, output);
705        } else {
706            append_code_point(code_point, output);
707        }
708    }
709}
710
711pub fn flush_wtf8(pending: &mut Option<u16>, output: &mut Vec<u8>) {
712    if pending.take().is_some() {
713        append_code_point(0xfffd, output);
714    }
715}
716
717fn decode_wtf8(bytes: &[u8], index: usize) -> (u32, usize) {
718    let first = bytes[index];
719    if first < 0x80 {
720        return (first as u32, 1);
721    }
722    if first < 0xe0 {
723        return (
724            ((first & 0x1f) as u32) << 6 | (bytes[index + 1] & 0x3f) as u32,
725            2,
726        );
727    }
728    if first < 0xf0 {
729        return (
730            ((first & 0x0f) as u32) << 12
731                | ((bytes[index + 1] & 0x3f) as u32) << 6
732                | (bytes[index + 2] & 0x3f) as u32,
733            3,
734        );
735    }
736    (
737        ((first & 0x07) as u32) << 18
738            | ((bytes[index + 1] & 0x3f) as u32) << 12
739            | ((bytes[index + 2] & 0x3f) as u32) << 6
740            | (bytes[index + 3] & 0x3f) as u32,
741        4,
742    )
743}
744
745fn append_code_point(code_point: u32, output: &mut Vec<u8>) {
746    if let Some(ch) = char::from_u32(code_point) {
747        let mut encoded = [0; 4];
748        output.extend_from_slice(ch.encode_utf8(&mut encoded).as_bytes());
749    }
750}
751
752pub fn bytes_to_typed_array<'js>(ctx: Ctx<'js>, bytes: &[u8]) -> Result<Value<'js>> {
753    TypedArray::<u8>::new(ctx.clone(), bytes).into_js(&ctx)
754}