Skip to main content

quickjs_jit_stdlib/llrt/llrt_buffer/
blob.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_buffer/src/blob.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::ops::RangeInclusive;
6
7use crate::stream_web::{
8    readable_byte_stream_controller_close_stream,
9    readable_byte_stream_controller_enqueue_bytes_borrowed,
10    readable_stream_default_controller_close_stream,
11    readable_stream_default_controller_enqueue_value, utils::promise::PromisePrimordials,
12    CancelAlgorithm, PullAlgorithm, ReadableStream, ReadableStreamControllerClass,
13};
14use crate::utils::{
15    array_buffer::shared_array_buffer_view,
16    bytes::{get_lossy_string, ObjectBytes},
17    object::not_a_object_error,
18    primordials::Primordial,
19    result::ResultExt,
20    string::get_coerced_defined_string,
21};
22use rquickjs::{
23    atom::PredefinedAtom, class::Trace, function::Opt, prelude::This, Array, ArrayBuffer, Class,
24    Coerced, Ctx, Exception, FromJs, IntoJs, JsIterator, Result, TypedArray, Value,
25};
26
27use super::file::File;
28
29struct ArrayPartsIter<'js> {
30    array: Array<'js>,
31    index: usize,
32}
33
34impl<'js> ArrayPartsIter<'js> {
35    fn new(array: Array<'js>) -> Self {
36        Self { array, index: 0 }
37    }
38}
39
40impl<'js> Iterator for ArrayPartsIter<'js> {
41    type Item = Result<Value<'js>>;
42
43    fn next(&mut self) -> Option<Self::Item> {
44        let len: usize = match self.array.as_object().get(PredefinedAtom::Length) {
45            Ok(v) => v,
46            Err(e) => return Some(Err(e)),
47        };
48        if self.index >= len {
49            return None;
50        }
51        let result = self.array.get(self.index);
52        self.index += 1;
53        Some(result)
54    }
55}
56
57enum EndingType {
58    Native,
59    Transparent,
60}
61
62#[cfg(windows)]
63const LINE_ENDING: &[u8] = b"\r\n";
64#[cfg(not(windows))]
65const LINE_ENDING: &[u8] = b"\n";
66
67#[rquickjs::class]
68#[derive(Trace, Clone, rquickjs::JsLifetime)]
69pub struct Blob<'js> {
70    /// Bytes live in a JS-owned `ArrayBuffer` so `.arrayBuffer()` / `.bytes()`
71    /// / `.stream()` can hand out refcount-bumped views without copying.
72    data: ArrayBuffer<'js>,
73    mime_type: String,
74}
75
76fn normalize_type(mut mime_type: String) -> String {
77    static INVALID_RANGE: RangeInclusive<u8> = 0x0020..=0x007E;
78
79    let bytes = unsafe { mime_type.as_bytes_mut() };
80    for byte in bytes {
81        if !INVALID_RANGE.contains(byte) {
82            return String::new();
83        }
84        byte.make_ascii_lowercase();
85    }
86    mime_type
87}
88
89#[rquickjs::methods]
90impl<'js> Blob<'js> {
91    #[qjs(constructor)]
92    pub fn new(
93        ctx: Ctx<'js>,
94        this: This<Value<'js>>,
95        parts: Opt<Value<'js>>,
96        options: Opt<Value<'js>>,
97    ) -> Result<Self> {
98        if this.as_function().is_none() {
99            return Err(Exception::throw_type(
100                &ctx,
101                "Failed to construct 'Blob': Please use the 'new' operator",
102            ));
103        }
104
105        Self::from_parts(ctx, parts, options)
106    }
107
108    #[qjs(get)]
109    pub fn size(&self) -> usize {
110        self.data.len()
111    }
112
113    #[qjs(get, rename = "type")]
114    pub fn mime_type(&self) -> String {
115        self.mime_type.clone()
116    }
117
118    pub async fn text(&self) -> String {
119        String::from_utf8_lossy(self.as_bytes()).to_string()
120    }
121
122    #[qjs(rename = "textStream")]
123    pub fn text_stream(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
124        let text = String::from_utf8_lossy(self.as_bytes()).to_string();
125        let pull = PullAlgorithm::from_fn_once(
126            move |ctx: Ctx<'js>, controller: ReadableStreamControllerClass<'js>| {
127                let ctrl = match controller {
128                    ReadableStreamControllerClass::ReadableStreamDefaultController(c) => c,
129                    _ => return Err(Exception::throw_type(&ctx, "Expected default controller")),
130                };
131                if !text.is_empty() {
132                    readable_stream_default_controller_enqueue_value(
133                        ctx.clone(),
134                        ctrl.clone(),
135                        text.clone().into_js(&ctx)?,
136                    )?;
137                }
138                readable_stream_default_controller_close_stream(ctx.clone(), ctrl)?;
139                Ok(PromisePrimordials::get(&ctx)?
140                    .promise_resolved_with_undefined
141                    .clone())
142            },
143        );
144        let stream = ReadableStream::from_pull_algorithm(
145            ctx,
146            pull,
147            CancelAlgorithm::ReturnPromiseUndefined,
148        )?;
149        Ok(stream.into_value())
150    }
151
152    #[qjs(rename = "arrayBuffer")]
153    pub async fn array_buffer(&self, ctx: Ctx<'js>) -> Result<ArrayBuffer<'js>> {
154        //should be mutable according to spec, thus copy is required
155        ArrayBuffer::new_copy(ctx, self.as_bytes())
156    }
157
158    pub async fn bytes(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
159        //should be mutable according to spec, thus copy is required
160        let ab = ArrayBuffer::new_copy(ctx, self.as_bytes())?;
161        TypedArray::<u8>::from_arraybuffer(ab).map(|t| t.into_value())
162    }
163
164    pub fn slice(
165        &self,
166        ctx: Ctx<'js>,
167        start: Opt<Value<'js>>,
168        end: Opt<Value<'js>>,
169        content_type: Opt<Value<'js>>,
170    ) -> Result<Blob<'js>> {
171        let start = start.0.and_then(|v| v.as_number()).map(clamp_long_long);
172        let end = end.0.and_then(|v| v.as_number()).map(clamp_long_long);
173        Self::slice_blob(self, &ctx, start, end, content_type.0)
174    }
175
176    pub fn stream(&self, ctx: Ctx<'js>) -> Result<Value<'js>> {
177        let data = self.data.clone();
178        let pull = PullAlgorithm::from_fn_once(
179            move |ctx: Ctx<'js>, controller: ReadableStreamControllerClass<'js>| {
180                let ctrl = match controller {
181                    ReadableStreamControllerClass::ReadableStreamByteController(c) => c,
182                    _ => return Err(Exception::throw_type(&ctx, "Expected byte controller")),
183                };
184                let len = data.len();
185                if len != 0 {
186                    let view = shared_array_buffer_view(&ctx, &data, 0, len)?;
187                    readable_byte_stream_controller_enqueue_bytes_borrowed(
188                        ctx.clone(),
189                        ctrl.clone(),
190                        view,
191                    )?;
192                }
193                readable_byte_stream_controller_close_stream(ctx.clone(), ctrl)?;
194                Ok(PromisePrimordials::get(&ctx)?
195                    .promise_resolved_with_undefined
196                    .clone())
197            },
198        );
199        // Byte-source stream so callers can use `getReader({ mode: 'byob' })`.
200        // Matches spec: Blob.stream() returns a `type: "bytes"` ReadableStream.
201        let stream = ReadableStream::from_byte_pull_algorithm(
202            ctx,
203            pull,
204            CancelAlgorithm::ReturnPromiseUndefined,
205        )?;
206        Ok(stream.into_value())
207    }
208
209    #[qjs(prop, rename = PredefinedAtom::SymbolToStringTag, configurable)]
210    pub fn to_string_tag() -> &'static str {
211        stringify!(Blob)
212    }
213
214    #[qjs(static, rename = PredefinedAtom::SymbolHasInstance)]
215    pub fn has_instance(value: Value<'js>) -> bool {
216        if let Some(obj) = value.as_object() {
217            return obj.instance_of::<Self>() || obj.instance_of::<File>();
218        }
219        false
220    }
221
222    #[qjs(skip)]
223    pub fn slice_blob(
224        &self,
225        ctx: &Ctx<'js>,
226        start: Option<isize>,
227        end: Option<isize>,
228        content_type: Option<Value<'js>>,
229    ) -> Result<Blob<'js>> {
230        let bytes = self.as_bytes();
231        let len = bytes.len();
232        let start = start.unwrap_or_default();
233        let start = if start < 0 {
234            (len as isize + start).max(0) as usize
235        } else {
236            len.min(start as usize)
237        };
238        let end = end.unwrap_or(len as isize);
239        let end = if end < 0 {
240            (len as isize + end).max(0) as usize
241        } else {
242            len.min(end as usize)
243        };
244        let data = shared_array_buffer_view(ctx, &self.data, start, end.saturating_sub(start))?;
245        let mime_type = get_coerced_defined_string(&content_type);
246        let mime_type = mime_type.map(normalize_type).unwrap_or_default();
247        Ok(Blob { mime_type, data })
248    }
249}
250
251impl<'js> Blob<'js> {
252    pub fn from_bytes(ctx: &Ctx<'js>, data: Vec<u8>, content_type: Option<String>) -> Result<Self> {
253        let mime_type = content_type.map(normalize_type).unwrap_or_default();
254        let data = ArrayBuffer::new_copy(ctx.clone(), data)?;
255        Ok(Self { mime_type, data })
256    }
257
258    pub fn from_parts(
259        ctx: Ctx<'js>,
260        parts: Opt<Value<'js>>,
261        options: Opt<Value<'js>>,
262    ) -> Result<Self> {
263        if let Some(options) = options.0.as_ref() {
264            if !options.is_null() && !options.is_undefined() && options.as_object().is_none() {
265                return Err(not_a_object_error(&ctx, "options"));
266            }
267        }
268
269        let mut endings = EndingType::Transparent;
270        if let Some(options) = options.0.as_ref() {
271            if let Some(opts) = options.as_object() {
272                if opts.contains_key("endings")? {
273                    if let Some(parsed) = parse_endings(&ctx, opts.get("endings")?)? {
274                        endings = parsed;
275                    }
276                }
277            }
278        }
279
280        let bytes = if let Some(parts) = parts.0 {
281            bytes_from_parts(&ctx, parts, endings)?
282        } else {
283            Vec::new()
284        };
285
286        let mut mime_type = String::new();
287        if let Some(options) = options.0.as_ref() {
288            if let Some(opts) = options.as_object() {
289                if let Some(x) = opts.get::<_, Option<Coerced<String>>>("type")? {
290                    mime_type = normalize_type(x.to_string());
291                }
292            }
293        }
294
295        // Transfer Vec ownership to JS — QuickJS calls the drop callback when
296        // the ArrayBuffer is GC'd, so no extra Rust-side copy.
297        let data = ArrayBuffer::new_copy(ctx, bytes)?;
298
299        Ok(Self { data, mime_type })
300    }
301
302    pub fn get_bytes(&self) -> Vec<u8> {
303        self.as_bytes().to_vec()
304    }
305
306    /// Zero-copy access to the underlying `ArrayBuffer`. Cloning the handle is
307    /// cheap (it's a JS-refcount bump); no bytes are copied. Useful for
308    /// consumers that want to pass the Blob body on to hyper via
309    /// `ObjectBytes::DataView` without the `get_bytes()` allocation.
310    pub fn array_buffer_ref(&self) -> ArrayBuffer<'js> {
311        self.data.clone()
312    }
313
314    /// Borrow the underlying bytes directly. Returns `&[]` if the ArrayBuffer
315    /// has been detached (shouldn't happen in normal blob flow).
316    pub fn as_bytes(&self) -> &[u8] {
317        unsafe { self.data.as_bytes() }.unwrap_or(&[])
318    }
319}
320
321fn bytes_from_parts<'js>(
322    ctx: &Ctx<'js>,
323    parts: Value<'js>,
324    endings: EndingType,
325) -> Result<Vec<u8>> {
326    if parts.is_undefined() {
327        return Ok(Vec::new());
328    }
329
330    if let Some(array) = parts.clone().into_array() {
331        return process_parts(ctx, ArrayPartsIter::new(array), endings);
332    }
333
334    process_parts(ctx, JsIterator::from_js(ctx, parts)?, endings)
335}
336
337fn process_parts<'js, I>(ctx: &Ctx<'js>, iter: I, endings: EndingType) -> Result<Vec<u8>>
338where
339    I: IntoIterator<Item = Result<Value<'js>>>,
340{
341    let mut data = Vec::new();
342    for elem in iter {
343        let elem = elem?;
344        if let Some(arr) = elem.as_array() {
345            let string = array_to_string(arr)?;
346            data.extend_from_slice(string.as_bytes());
347            continue;
348        }
349        if let Some(object) = elem.as_object() {
350            if let Some(x) = Class::<Blob>::from_object(object) {
351                data.extend_from_slice(x.borrow().as_bytes());
352                continue;
353            }
354            if let Some(x) = Class::<File>::from_object(object) {
355                let file = x.borrow();
356                let end = Some(file.size().try_into().or_throw(ctx)?);
357                let mime_type = Some(file.mime_type().into_js(ctx)?);
358                let sub = file.slice(ctx.clone(), Opt(Some(0)), Opt(end), Opt(mime_type))?;
359                data.extend_from_slice(sub.as_bytes());
360                continue;
361            }
362            if let Ok(x) = ObjectBytes::from(ctx, object) {
363                data.extend_from_slice(x.as_bytes(ctx).map_err(|_| {
364                    Exception::throw_type(ctx, "Cannot create a blob with detached buffer")
365                })?);
366                continue;
367            }
368            if let Some(x) = ArrayBuffer::from_object(object.clone()) {
369                data.extend_from_slice(unsafe { x.as_bytes() }.ok_or_else(|| {
370                    Exception::throw_type(ctx, "Cannot create a blob with detached buffer")
371                })?);
372                continue;
373            }
374        }
375
376        let string = if elem.is_string() {
377            get_lossy_string(elem)?
378        } else {
379            Coerced::<String>::from_js(ctx, elem)?.0
380        };
381        if let EndingType::Transparent = endings {
382            data.extend_from_slice(string.as_bytes());
383        } else {
384            let len = string.len();
385            data.reserve(len);
386
387            let bytes = string.as_bytes();
388            let mut iter = bytes.iter();
389
390            let mut start = 0usize;
391            let mut i = 0usize;
392            let line_ending_is_n = LINE_ENDING[0] == b'\n';
393
394            while let Some(byte) = iter.next() {
395                if byte == &b'\r' {
396                    if let Some(next_byte) = iter.next() {
397                        data.extend(&bytes[start..i]);
398                        i += 1;
399                        start = i + 1;
400                        if next_byte != &b'\n' {
401                            data.extend([b'\r', *next_byte]);
402                        } else {
403                            data.extend(LINE_ENDING);
404                        }
405                    }
406                } else if byte == &b'\n' && !line_ending_is_n {
407                    data.extend(&bytes[start..i]);
408                    data.extend(LINE_ENDING);
409                    start = i + 1;
410                };
411                i += 1;
412            }
413
414            if start < len {
415                data.extend(&bytes[start..len]);
416            }
417        }
418    }
419    Ok(data)
420}
421
422fn parse_endings<'js>(ctx: &Ctx<'js>, value: Value<'js>) -> Result<Option<EndingType>> {
423    if value.is_undefined() {
424        return Ok(None);
425    }
426    let endings = match Coerced::<String>::from_js(ctx, value)?.0.as_str() {
427        "transparent" => Some(EndingType::Transparent),
428        "native" => Some(EndingType::Native),
429        _ => {
430            return Err(Exception::throw_type(
431                ctx,
432                r#"expected 'endings' to be either 'transparent' or 'native'"#,
433            ));
434        }
435    };
436    Ok(endings)
437}
438
439fn array_to_string(array: &Array) -> Result<String> {
440    let mut itoa_buffer = itoa::Buffer::new();
441    let mut ryu_buffer = ryu::Buffer::new();
442
443    let parts = array
444        .clone()
445        .into_iter()
446        .map(|value| {
447            let value = value?;
448            if let Some(string) = value.as_string() {
449                Ok(string.to_string()?)
450            } else if let Some(number) = value.as_int() {
451                Ok(itoa_buffer.format(number).to_string())
452            } else if let Some(number) = value.as_float() {
453                Ok(ryu_buffer.format(number).to_string())
454            } else {
455                Ok(String::new())
456            }
457        })
458        .collect::<Result<Vec<_>>>()?;
459
460    Ok(parts.join(","))
461}
462
463fn clamp_long_long(value: f64) -> isize {
464    if value.is_nan() {
465        return 0;
466    }
467    let rounded = value.round_ties_even();
468    rounded.clamp(isize::MIN as f64, isize::MAX as f64) as isize
469}