Skip to main content

quickjs_jit_stdlib/llrt/llrt_stream_web/readable/
byte_controller.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_stream_web/src/readable/byte_controller.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3use std::collections::VecDeque;
4
5use crate::utils::{
6    error_messages::ERROR_MSG_ARRAY_BUFFER_DETACHED,
7    option::{Null, Undefined},
8    primordials::{BasePrimordials, Primordial},
9    result::ResultExt,
10};
11use rquickjs::{
12    class::{OwnedBorrow, OwnedBorrowMut, Trace, Tracer},
13    function::Constructor,
14    methods,
15    prelude::{Opt, This},
16    ArrayBuffer, Class, Ctx, Error, Exception, Function, IntoJs, JsLifetime, Object, Promise,
17    Result, TypedArray, Value,
18};
19
20use crate::stream_web::{
21    readable::{
22        byob_reader::{ArrayConstructorPrimordials, ReadableStreamReadIntoRequest, ViewBytes},
23        controller::{
24            ReadableStreamController, ReadableStreamControllerClass, ReadableStreamControllerOwned,
25        },
26        default_controller::ReadableStreamDefaultControllerOwned,
27        default_reader::ReadableStreamReadRequest,
28        objects::{
29            ReadableByteStreamObjects, ReadableStreamBYOBObjects, ReadableStreamClassObjects,
30            ReadableStreamDefaultReaderObjects, ReadableStreamObjects,
31        },
32        reader::ReadableStreamReader,
33        stream::{
34            algorithms::{CancelAlgorithm, PullAlgorithm, StartAlgorithm},
35            source::UnderlyingSource,
36            ReadableStream, ReadableStreamClass, ReadableStreamOwned, ReadableStreamState,
37        },
38    },
39    utils::{
40        class_from_owned_borrow_mut,
41        promise::{promise_resolved_with, upon_promise},
42        UnwrapOrUndefined,
43    },
44};
45
46#[derive(JsLifetime)]
47#[rquickjs::class]
48pub struct ReadableByteStreamController<'js> {
49    auto_allocate_chunk_size: Option<usize>,
50    byob_request: Option<Class<'js, ReadableStreamBYOBRequest<'js>>>,
51    cancel_algorithm: Option<CancelAlgorithm<'js>>,
52    close_requested: bool,
53    pull_again: bool,
54    pull_algorithm: Option<PullAlgorithm<'js>>,
55    pulling: bool,
56    pub(super) pending_pull_intos: VecDeque<PullIntoDescriptor<'js>>,
57    queue: VecDeque<ReadableByteStreamQueueEntry<'js>>,
58    queue_total_size: usize,
59    started: bool,
60    strategy_hwm: f64,
61    pub(super) stream: ReadableStreamClass<'js>,
62
63    pub(super) array_constructor_primordials: ArrayConstructorPrimordials<'js>,
64    constructor_array_buffer: Constructor<'js>,
65    pub(super) function_array_buffer_is_view: Function<'js>,
66}
67
68impl<'js> Trace<'js> for ReadableByteStreamController<'js> {
69    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
70        self.auto_allocate_chunk_size.trace(tracer);
71        self.byob_request.trace(tracer);
72        self.cancel_algorithm.trace(tracer);
73        self.pull_algorithm.trace(tracer);
74        self.pending_pull_intos.trace(tracer);
75        self.queue.trace(tracer);
76        self.queue_total_size.trace(tracer);
77        self.started.trace(tracer);
78        self.strategy_hwm.trace(tracer);
79        self.stream.trace(tracer);
80        self.array_constructor_primordials.trace(tracer);
81        self.constructor_array_buffer.trace(tracer);
82        self.function_array_buffer_is_view.trace(tracer);
83    }
84}
85
86pub type ReadableByteStreamControllerClass<'js> = Class<'js, ReadableByteStreamController<'js>>;
87pub(crate) type ReadableByteStreamControllerOwned<'js> =
88    OwnedBorrowMut<'js, ReadableByteStreamController<'js>>;
89
90impl<'js> ReadableByteStreamController<'js> {
91    // SetUpReadableByteStreamControllerFromUnderlyingSource
92    pub(super) fn set_up_readable_byte_stream_controller_from_underlying_source(
93        ctx: &Ctx<'js>,
94        stream: ReadableStreamOwned<'js>,
95        underlying_source: Null<Undefined<Object<'js>>>,
96        underlying_source_dict: UnderlyingSource<'js>,
97        high_water_mark: f64,
98    ) -> Result<()> {
99        let (start_algorithm, pull_algorithm, cancel_algorithm, auto_allocate_chunk_size) = (
100            // If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list
101            // « controller » and callback this value underlyingSource.
102            underlying_source_dict
103                .start
104                .map(|f| StartAlgorithm::Function {
105                    f,
106                    underlying_source: underlying_source.clone(),
107                })
108                .unwrap_or(StartAlgorithm::ReturnUndefined),
109            // If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list
110            // « controller » and callback this value underlyingSource.
111            underlying_source_dict
112                .pull
113                .map(|f| PullAlgorithm::Function {
114                    f,
115                    underlying_source: underlying_source.clone(),
116                })
117                .unwrap_or(PullAlgorithm::ReturnPromiseUndefined),
118            // If underlyingSourceDict["cancel"] exists, then set cancelAlgorithm to an algorithm which takes an argument reason and returns the result of invoking underlyingSourceDict["cancel"] with argument list
119            // « reason » and callback this value underlyingSource.
120            underlying_source_dict
121                .cancel
122                .map(|f| CancelAlgorithm::Function {
123                    f,
124                    underlying_source,
125                })
126                .unwrap_or(CancelAlgorithm::ReturnPromiseUndefined),
127            // Let autoAllocateChunkSize be underlyingSourceDict["autoAllocateChunkSize"], if it exists, or undefined otherwise.
128            underlying_source_dict.auto_allocate_chunk_size,
129        );
130
131        // If autoAllocateChunkSize is 0, then throw a TypeError exception.
132        if auto_allocate_chunk_size == Some(0) {
133            return Err(Exception::throw_type(
134                ctx,
135                "autoAllocateChunkSize must be greater than 0",
136            ));
137        }
138
139        Self::set_up_readable_byte_stream_controller(
140            ctx.clone(),
141            stream,
142            start_algorithm,
143            pull_algorithm,
144            cancel_algorithm,
145            high_water_mark,
146            auto_allocate_chunk_size,
147        )?;
148
149        Ok(())
150    }
151
152    pub(super) fn set_up_readable_byte_stream_controller(
153        ctx: Ctx<'js>,
154        stream: ReadableStreamOwned<'js>,
155        start_algorithm: StartAlgorithm<'js>,
156        pull_algorithm: PullAlgorithm<'js>,
157        cancel_algorithm: CancelAlgorithm<'js>,
158        high_water_mark: f64,
159        auto_allocate_chunk_size: Option<usize>,
160    ) -> Result<Class<'js, Self>> {
161        let (stream_class, mut stream) = class_from_owned_borrow_mut(stream);
162
163        let array_constructor_primordials = ArrayConstructorPrimordials::get(&ctx)?.clone();
164        let BasePrimordials {
165            constructor_array_buffer,
166            function_array_buffer_is_view,
167            ..
168        } = &*BasePrimordials::get(&ctx)?;
169
170        let controller = Self {
171            // Set controller.[[stream]] to stream.
172            stream: stream_class,
173
174            // Set controller.[[pullAgain]] and controller.[[pulling]] to false.
175            pull_again: false,
176            pulling: false,
177
178            // Set controller.[[byobRequest]] to null.
179            byob_request: None,
180
181            // Perform ! ResetQueue(controller).
182            queue: VecDeque::new(),
183            queue_total_size: 0,
184
185            // Set controller.[[closeRequested]] and controller.[[started]] to false.
186            close_requested: false,
187            started: false,
188
189            // Set controller.[[strategyHWM]] to highWaterMark.
190            strategy_hwm: high_water_mark,
191
192            // Set controller.[[pullAlgorithm]] to pullAlgorithm.
193            pull_algorithm: Some(pull_algorithm),
194            cancel_algorithm: Some(cancel_algorithm),
195
196            // Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
197            auto_allocate_chunk_size,
198
199            pending_pull_intos: VecDeque::new(),
200
201            array_constructor_primordials,
202            constructor_array_buffer: constructor_array_buffer.clone(),
203            function_array_buffer_is_view: function_array_buffer_is_view.clone(),
204        };
205
206        let controller_class = Class::instance(ctx.clone(), controller)?;
207
208        // Set stream.[[controller]] to controller.
209        stream.controller =
210            ReadableStreamControllerClass::ReadableStreamByteController(controller_class.clone());
211
212        let objects =
213            ReadableStreamObjects::new_byte(stream, OwnedBorrowMut::from_class(controller_class))
214                .refresh_reader();
215
216        let promise_primordials = objects.stream.promise_primordials.clone();
217
218        // Let startResult be the result of performing startAlgorithm.
219        let (start_result, objects_class) =
220            Self::start_algorithm(ctx.clone(), objects, start_algorithm)?;
221
222        // Let startPromise be a promise resolved with startResult.
223        let start_promise = promise_resolved_with(&ctx, &promise_primordials, Ok(start_result))?;
224
225        let _ = upon_promise(ctx.clone(), start_promise, {
226            let objects_class = objects_class.clone();
227            Box::new(move |ctx, result| {
228                let mut objects =
229                    ReadableStreamObjects::from_class_no_reader(objects_class).refresh_reader();
230                match result {
231                    // Upon fulfillment of startPromise,
232                    Ok(_) => {
233                        // Set controller.[[started]] to true.
234                        objects.controller.started = true;
235                        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
236                        Self::readable_byte_stream_controller_call_pull_if_needed(
237                            ctx.clone(),
238                            objects,
239                        )?;
240                        Ok(Value::new_undefined(ctx))
241                    }
242                    // Upon rejection of startPromise with reason r,
243                    Err(r) => {
244                        // Perform ! ReadableByteStreamControllerError(controller, r).
245                        Self::readable_byte_stream_controller_error(objects, r)?;
246                        Ok(Value::new_undefined(ctx))
247                    }
248                }
249            })
250        })?;
251
252        Ok(objects_class.controller)
253    }
254
255    fn readable_byte_stream_controller_call_pull_if_needed<R: ReadableStreamReader<'js>>(
256        ctx: Ctx<'js>,
257        objects: ReadableByteStreamObjects<'js, R>,
258    ) -> Result<ReadableByteStreamObjects<'js, R>> {
259        // Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
260        let (should_pull, mut objects) =
261            Self::readable_byte_stream_controller_should_call_pull(objects);
262
263        // If shouldPull is false, return.
264        if !should_pull {
265            return Ok(objects);
266        }
267
268        // If controller.[[pulling]] is true,
269        if objects.controller.pulling {
270            // Set controller.[[pullAgain]] to true.
271            objects.controller.pull_again = true;
272
273            // Return.
274            return Ok(objects);
275        }
276
277        // Set controller.[[pulling]] to true.
278        objects.controller.pulling = true;
279
280        // Let pullPromise be the result of performing controller.[[pullAlgorithm]].
281        let (pull_promise, objects_class) = Self::pull_algorithm(ctx.clone(), objects)?;
282
283        upon_promise(ctx, pull_promise, {
284            let objects_class = objects_class.clone();
285            Box::new(move |ctx, result| {
286                let mut objects =
287                    ReadableStreamObjects::from_class_no_reader(objects_class).refresh_reader();
288                match result {
289                    // Upon fulfillment of pullPromise,
290                    Ok(_) => {
291                        // Set controller.[[pulling]] to false.
292                        objects.controller.pulling = false;
293                        // If controller.[[pullAgain]] is true,
294                        if objects.controller.pull_again {
295                            // Set controller.[[pullAgain]] to false.
296                            objects.controller.pull_again = false;
297                            // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
298                            Self::readable_byte_stream_controller_call_pull_if_needed(
299                                ctx.clone(),
300                                objects,
301                            )?;
302                        };
303                        Ok(Value::new_undefined(ctx))
304                    }
305                    // Upon rejection of pullPromise with reason e,
306                    Err(e) => {
307                        // Perform ! ReadableByteStreamControllerError(controller, e).
308                        Self::readable_byte_stream_controller_error(objects, e)?;
309                        Ok(Value::new_undefined(ctx))
310                    }
311                }
312            })
313        })?;
314
315        Ok(ReadableStreamObjects::from_class(objects_class))
316    }
317
318    fn readable_byte_stream_controller_should_call_pull<R: ReadableStreamReader<'js>>(
319        mut objects: ReadableByteStreamObjects<'js, R>,
320    ) -> (bool, ReadableByteStreamObjects<'js, R>) {
321        // Let stream be controller.[[stream]].
322        match objects.stream.state {
323            ReadableStreamState::Readable => {}
324            // If stream.[[state]] is not "readable", return false.
325            _ => return (false, objects),
326        }
327
328        // If controller.[[closeRequested]] is true, return false.
329        if objects.controller.close_requested {
330            return (false, objects);
331        }
332
333        // If controller.[[started]] is false, return false.
334        if !objects.controller.started {
335            return (false, objects);
336        }
337
338        let (mut has_read_requests, mut has_read_into_requests) = (false, false);
339        objects = objects
340            .with_reader(
341                |objects| {
342                    // If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
343                    if ReadableStream::readable_stream_get_num_read_requests(&objects.reader) > 0 {
344                        has_read_requests = true;
345                    }
346                    Ok(objects)
347                },
348                |objects| {
349                    // If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0, return true.
350                    if ReadableStream::readable_stream_get_num_read_into_requests(&objects.reader)
351                        > 0
352                    {
353                        has_read_into_requests = true;
354                    }
355                    Ok(objects)
356                },
357                Ok,
358            )
359            .unwrap();
360
361        if has_read_requests || has_read_into_requests {
362            return (true, objects);
363        }
364
365        // Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
366        let desired_size = objects
367            .controller
368            .readable_byte_stream_controller_get_desired_size(&objects.stream);
369
370        // Assert: desiredSize is not null.
371        if desired_size.0.expect("desired_size must not be null") > 0.0 {
372            // If desiredSize > 0, return true.
373            return (true, objects);
374        }
375
376        // Return false.
377        (false, objects)
378    }
379
380    pub(super) fn readable_byte_stream_controller_error<R: ReadableStreamReader<'js>>(
381        // Let stream be controller.[[stream]].
382        mut objects: ReadableByteStreamObjects<'js, R>,
383        e: Value<'js>,
384    ) -> Result<ReadableByteStreamObjects<'js, R>> {
385        // If stream.[[state]] is not "readable", return.
386        if !matches!(objects.stream.state, ReadableStreamState::Readable) {
387            return Ok(objects);
388        };
389
390        // Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
391        objects
392            .controller
393            .readable_byte_stream_controller_clear_pending_pull_intos();
394
395        // Perform ! ResetQueue(controller).
396        objects.controller.reset_queue();
397
398        // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
399        objects
400            .controller
401            .readable_byte_stream_controller_clear_algorithms();
402
403        // Perform ! ReadableStreamError(stream, e).
404        ReadableStream::readable_stream_error(objects, e)
405    }
406
407    fn readable_byte_stream_controller_clear_pending_pull_intos(&mut self) {
408        // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
409        self.readable_byte_stream_controller_invalidate_byob_request();
410
411        // Set controller.[[pendingPullIntos]] to a new empty list.
412        self.pending_pull_intos.clear();
413    }
414
415    fn readable_byte_stream_controller_invalidate_byob_request(&mut self) {
416        let byob_request = match self.byob_request {
417            // If controller.[[byobRequest]] is null, return.
418            None => return,
419            Some(ref byob_request) => byob_request.clone(),
420        };
421        let mut byob_request = OwnedBorrowMut::from_class(byob_request);
422        byob_request.controller = None;
423        byob_request.view = None;
424
425        self.byob_request = None;
426    }
427
428    fn readable_byte_stream_controller_clear_algorithms(&mut self) {
429        self.pull_algorithm = None;
430        self.cancel_algorithm = None;
431    }
432
433    pub(super) fn readable_byte_stream_controller_get_byob_request(
434        ctx: Ctx<'js>,
435        controller: OwnedBorrowMut<'js, Self>,
436    ) -> Result<(
437        Null<Class<'js, ReadableStreamBYOBRequest<'js>>>,
438        OwnedBorrowMut<'js, Self>,
439    )> {
440        // If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,
441        if controller.byob_request.is_none() && !controller.pending_pull_intos.is_empty() {
442            // Let firstDescriptor be controller.[[pendingPullIntos]][0].
443            let first_descriptor = &controller.pending_pull_intos[0];
444
445            // Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer, firstDescriptor’s byte offset + firstDescriptor’s bytes filled, firstDescriptor’s byte length − firstDescriptor’s bytes filled »).
446            let view = ViewBytes::from_value(
447                &ctx,
448                &controller.function_array_buffer_is_view,
449                Some(
450                    &controller
451                        .array_constructor_primordials
452                        .constructor_uint8array
453                        .construct((
454                            first_descriptor.buffer.clone(),
455                            first_descriptor.byte_offset + first_descriptor.bytes_filled,
456                            first_descriptor.byte_length - first_descriptor.bytes_filled,
457                        ))?,
458                ),
459            )?;
460
461            let (controller_class, mut controller) = class_from_owned_borrow_mut(controller);
462
463            // Let byobRequest be a new ReadableStreamBYOBRequest.
464            let byob_request = ReadableStreamBYOBRequest {
465                // Set byobRequest.[[controller]] to controller.
466                controller: Some(controller_class),
467                // Set byobRequest.[[view]] to view.
468                view: Some(view),
469            };
470
471            // Set controller.[[byobRequest]] to byobRequest.
472            controller.byob_request = Some(Class::instance(ctx, byob_request)?);
473
474            Ok((Null(controller.byob_request.clone()), controller))
475        } else {
476            // Return controller.[[byobRequest]].
477            Ok((Null(controller.byob_request.clone()), controller))
478        }
479    }
480
481    fn readable_byte_stream_controller_get_desired_size(
482        &self,
483        stream: &ReadableStream<'js>,
484    ) -> Null<f64> {
485        // Let state be controller.[[stream]].[[state]].
486        match stream.state {
487            // If state is "errored", return null.
488            ReadableStreamState::Errored(_) => Null(None),
489            // If state is "closed", return 0.
490            ReadableStreamState::Closed => Null(Some(0.0)),
491            // Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
492            _ => Null(Some(self.strategy_hwm - self.queue_total_size as f64)),
493        }
494    }
495
496    fn reset_queue(&mut self) {
497        // Set container.[[queue]] to a new empty list.
498        self.queue.clear();
499        // Set container.[[queueTotalSize]] to 0.
500        self.queue_total_size = 0;
501    }
502
503    pub(super) fn readable_byte_stream_controller_close<R: ReadableStreamReader<'js>>(
504        ctx: Ctx<'js>,
505        // Let stream be controller.[[stream]].
506        mut objects: ReadableByteStreamObjects<'js, R>,
507    ) -> Result<ReadableByteStreamObjects<'js, R>> {
508        // If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
509        if objects.controller.close_requested
510            || !matches!(objects.stream.state, ReadableStreamState::Readable)
511        {
512            return Ok(objects);
513        }
514
515        // If controller.[[queueTotalSize]] > 0,
516        if objects.controller.queue_total_size > 0 {
517            // Set controller.[[closeRequested]] to true.
518            objects.controller.close_requested = true;
519            // Return.
520            return Ok(objects);
521        }
522
523        // If controller.[[pendingPullIntos]] is not empty,
524        // Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
525        if let Some(first_pending_pull_into) = objects.controller.pending_pull_intos.front() {
526            // If the remainder after dividing firstPendingPullInto’s bytes filled by firstPendingPullInto’s element size is not 0,
527            if first_pending_pull_into.bytes_filled % first_pending_pull_into.element_size != 0 {
528                // Let e be a new TypeError exception.
529                let e: Value = objects
530                    .stream
531                    .constructor_type_error
532                    .call(("Insufficient bytes to fill elements in the given buffer",))?;
533                Self::readable_byte_stream_controller_error(objects, e.clone())?;
534                return Err(ctx.throw(e));
535            }
536        }
537
538        // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
539        objects
540            .controller
541            .readable_byte_stream_controller_clear_algorithms();
542
543        // Perform ! ReadableStreamClose(stream).
544        ReadableStream::readable_stream_close(ctx, objects)
545    }
546
547    pub(super) fn readable_byte_stream_controller_enqueue<R: ReadableStreamReader<'js>>(
548        ctx: &Ctx<'js>,
549        // Let stream be controller.[[stream]].
550        objects: ReadableByteStreamObjects<'js, R>,
551        chunk: ViewBytes<'js>,
552    ) -> Result<ReadableByteStreamObjects<'js, R>> {
553        Self::readable_byte_stream_controller_enqueue_impl(
554            ctx, objects, chunk, /*skip_transfer=*/ false,
555        )
556    }
557
558    /// Like [`readable_byte_stream_controller_enqueue`] but skips the
559    /// spec-mandated `TransferArrayBuffer(chunk)` step on the incoming
560    /// chunk. Used by producers that already own the backing allocation
561    /// and want to hand it to the stream without QuickJS copying or
562    /// detaching it (e.g. `Blob.stream()`, where the backing
563    /// `ArrayBuffer` must survive multiple `.stream()` calls).
564    ///
565    /// Safety vs. correctness: the chunk we enqueue is NOT detached from
566    /// the producer's perspective, so both producer and consumer see the
567    /// same underlying bytes. This matches the existing non-isolation
568    /// behaviour of `Blob.arrayBuffer()` / `Blob.bytes()`, which already
569    /// return handles that alias the blob's storage. Pending BYOB
570    /// transfers of reader-provided buffers are unaffected — those are
571    /// separate buffers and still use spec-mandated transfer.
572    pub(super) fn readable_byte_stream_controller_enqueue_borrowed<R: ReadableStreamReader<'js>>(
573        ctx: &Ctx<'js>,
574        objects: ReadableByteStreamObjects<'js, R>,
575        chunk: ViewBytes<'js>,
576    ) -> Result<ReadableByteStreamObjects<'js, R>> {
577        Self::readable_byte_stream_controller_enqueue_impl(
578            ctx, objects, chunk, /*skip_transfer=*/ true,
579        )
580    }
581
582    fn readable_byte_stream_controller_enqueue_impl<R: ReadableStreamReader<'js>>(
583        ctx: &Ctx<'js>,
584        mut objects: ReadableByteStreamObjects<'js, R>,
585        chunk: ViewBytes<'js>,
586        skip_transfer: bool,
587    ) -> Result<ReadableByteStreamObjects<'js, R>> {
588        // If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
589        if objects.controller.close_requested
590            || !matches!(objects.stream.state, ReadableStreamState::Readable)
591        {
592            return Ok(objects);
593        };
594
595        // Let buffer be chunk.[[ViewedArrayBuffer]].
596        // Let byteOffset be chunk.[[ByteOffset]].
597        // Let byteLength be chunk.[[ByteLength]].
598        let (buffer, byte_length, byte_offset) = chunk.get_array_buffer()?;
599
600        // If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
601        buffer.as_raw().ok_or(Exception::throw_type(
602            ctx,
603            "chunk's buffer is detached and so cannot be enqueued",
604        ))?;
605
606        // Let transferredBuffer be ? TransferArrayBuffer(buffer).
607        // (When `skip_transfer` is true, the caller guarantees that the
608        // buffer is already owned exclusively by the stream for the
609        // purposes of this enqueue — see
610        // `readable_byte_stream_controller_enqueue_borrowed`.)
611        let transferred_buffer = if skip_transfer {
612            buffer
613        } else {
614            transfer_array_buffer(buffer)?
615        };
616
617        // If controller.[[pendingPullIntos]] is not empty,
618        // Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
619        if !objects.controller.pending_pull_intos.is_empty() {
620            // If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
621            objects.controller.pending_pull_intos[0]
622                    .buffer
623                    .as_raw()
624                    .or_throw_type(
625                        ctx,
626                        "The BYOB request's buffer has been detached and so cannot be filled with an enqueued chunk",
627                    )?;
628
629            // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
630            objects
631                .controller
632                .readable_byte_stream_controller_invalidate_byob_request();
633
634            // Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
635            objects.controller.pending_pull_intos[0].buffer =
636                transfer_array_buffer(objects.controller.pending_pull_intos[0].buffer.clone())?;
637
638            // If firstPendingPullInto’s reader type is "none", perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, firstPendingPullInto).
639            if let PullIntoDescriptorReaderType::None =
640                objects.controller.pending_pull_intos[0].reader_type
641            {
642                objects = Self::readable_byte_stream_enqueue_detached_pull_into_to_queue(
643                    ctx.clone(),
644                    objects,
645                    0,
646                )?;
647            }
648        }
649
650        objects = objects.with_reader(
651            // If ! ReadableStreamHasDefaultReader(stream) is true,
652            |mut objects| {
653                // Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
654                objects = Self::readable_byte_stream_controller_process_read_requests_using_queue(
655                    objects, ctx,
656                )?;
657
658                // If ! ReadableStreamGetNumReadRequests(stream) is 0,
659                if ReadableStream::readable_stream_get_num_read_requests(&objects.reader) == 0 {
660                    // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
661                    objects
662                        .controller
663                        .readable_byte_stream_controller_enqueue_chunk_to_queue(
664                            transferred_buffer.clone(),
665                            byte_offset,
666                            byte_length,
667                        )
668                } else {
669                    // Otherwise,
670                    // If controller.[[pendingPullIntos]] is not empty,
671                    if !objects.controller.pending_pull_intos.is_empty() {
672                        // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
673                        objects
674                            .controller
675                            .readable_byte_stream_controller_shift_pending_pull_into();
676                    }
677
678                    // Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
679                    let transferred_view = ViewBytes::from_value(
680                        ctx,
681                        &objects.controller.function_array_buffer_is_view,
682                        Some(
683                            &objects
684                                .controller
685                                .array_constructor_primordials
686                                .constructor_uint8array
687                                .construct((
688                                    transferred_buffer.clone(),
689                                    byte_offset,
690                                    byte_length,
691                                ))?,
692                        ),
693                    );
694
695                    // Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
696                    objects = ReadableStream::readable_stream_fulfill_read_request(
697                        ctx,
698                        objects,
699                        transferred_view.into_js(ctx)?,
700                        false,
701                    )?;
702                }
703
704                Ok(objects)
705            },
706            |mut objects| {
707                // Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
708                // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
709                objects
710                    .controller
711                    .readable_byte_stream_controller_enqueue_chunk_to_queue(
712                        transferred_buffer.clone(),
713                        byte_offset,
714                        byte_length,
715                    );
716                // Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
717
718                Self::readable_byte_stream_controller_process_pull_into_descriptors_using_queue(
719                    ctx, objects,
720                )
721            },
722            |mut objects| {
723                // Otherwise,
724                // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, transferredBuffer, byteOffset, byteLength).
725                objects
726                    .controller
727                    .readable_byte_stream_controller_enqueue_chunk_to_queue(
728                        transferred_buffer.clone(),
729                        byte_offset,
730                        byte_length,
731                    );
732
733                Ok(objects)
734            },
735        )?;
736
737        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
738        Self::readable_byte_stream_controller_call_pull_if_needed(ctx.clone(), objects)
739    }
740
741    fn readable_byte_stream_enqueue_detached_pull_into_to_queue<R: ReadableStreamReader<'js>>(
742        ctx: Ctx<'js>,
743        mut objects: ReadableByteStreamObjects<'js, R>,
744        pull_into_descriptor_index: usize,
745    ) -> Result<ReadableByteStreamObjects<'js, R>> {
746        let pull_into_descriptor =
747            &objects.controller.pending_pull_intos[pull_into_descriptor_index];
748        // If pullIntoDescriptor’s bytes filled > 0, perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
749        if pull_into_descriptor.bytes_filled > 0 {
750            let buffer = pull_into_descriptor.buffer.clone();
751            let byte_offset = pull_into_descriptor.byte_offset;
752            let bytes_filled = pull_into_descriptor.bytes_filled;
753            objects = Self::readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(
754                ctx,
755                objects,
756                &buffer,
757                byte_offset,
758                bytes_filled,
759            )?;
760        }
761
762        // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
763        objects
764            .controller
765            .readable_byte_stream_controller_shift_pending_pull_into();
766
767        Ok(objects)
768    }
769
770    fn readable_byte_stream_controller_process_read_requests_using_queue(
771        mut objects: ReadableStreamDefaultReaderObjects<'js, OwnedBorrowMut<'js, Self>>,
772        ctx: &Ctx<'js>,
773    ) -> Result<ReadableStreamDefaultReaderObjects<'js, OwnedBorrowMut<'js, Self>>> {
774        // While reader.[[readRequests]] is not empty,
775        while !objects.reader.read_requests.is_empty() {
776            // If controller.[[queueTotalSize]] is 0, return.
777            if objects.controller.queue_total_size == 0 {
778                return Ok(objects);
779            }
780
781            // Let readRequest be reader.[[readRequests]][0].
782            // Remove readRequest from reader.[[readRequests]].
783            let read_request = objects.reader.read_requests.pop_front().unwrap();
784            // Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(controller, readRequest).
785            objects = Self::readable_byte_stream_controller_fill_read_request_from_queue(
786                ctx,
787                objects,
788                read_request,
789            )?;
790        }
791
792        Ok(objects)
793    }
794
795    fn readable_byte_stream_controller_shift_pending_pull_into(
796        &mut self,
797    ) -> PullIntoDescriptor<'js> {
798        // Invalidate byobRequest since the first pending pull-into is being removed
799        self.readable_byte_stream_controller_invalidate_byob_request();
800        // Let descriptor be controller.[[pendingPullIntos]][0].
801        // Remove descriptor from controller.[[pendingPullIntos]].
802        // Return descriptor.
803        self.pending_pull_intos.pop_front().expect(
804            "ReadableByteStreamControllerShiftPendingPullInto called on empty pendingPullIntos",
805        )
806    }
807
808    fn readable_byte_stream_controller_enqueue_chunk_to_queue(
809        &mut self,
810        buffer: ArrayBuffer<'js>,
811        byte_offset: usize,
812        byte_length: usize,
813    ) {
814        // Append a new readable byte stream queue entry with buffer buffer, byte offset byteOffset, and byte length byteLength to controller.[[queue]].
815        self.queue.push_back(ReadableByteStreamQueueEntry {
816            buffer,
817            byte_offset,
818            byte_length,
819        });
820
821        // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
822        self.queue_total_size += byte_length;
823    }
824
825    fn readable_byte_stream_controller_process_pull_into_descriptors_using_queue<
826        R: ReadableStreamReader<'js>,
827    >(
828        ctx: &Ctx<'js>,
829        mut objects: ReadableByteStreamObjects<'js, R>,
830    ) -> Result<ReadableByteStreamObjects<'js, R>> {
831        // While controller.[[pendingPullIntos]] is not empty,
832        while !objects.controller.pending_pull_intos.is_empty() {
833            // If controller.[[queueTotalSize]] is 0, return.
834            if objects.controller.queue_total_size == 0 {
835                return Ok(objects);
836            }
837
838            // Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
839            let mut pull_into_descriptor_ref = PullIntoDescriptorRefMut::Index(0);
840
841            // If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
842            if objects
843                .controller
844                .readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(
845                    ctx,
846                    &mut pull_into_descriptor_ref,
847                )?
848            {
849                // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
850                let pull_into_descriptor = objects
851                    .controller
852                    .readable_byte_stream_controller_shift_pending_pull_into();
853
854                // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
855                objects = Self::readable_byte_stream_controller_commit_pull_into_descriptor(
856                    ctx.clone(),
857                    objects,
858                    pull_into_descriptor,
859                )?;
860            }
861        }
862        Ok(objects)
863    }
864
865    fn readable_byte_stream_controller_enqueue_cloned_chunk_to_queue<
866        R: ReadableStreamReader<'js>,
867    >(
868        ctx: Ctx<'js>,
869        mut objects: ReadableByteStreamObjects<'js, R>,
870        buffer: &ArrayBuffer<'js>,
871        byte_offset: usize,
872        byte_length: usize,
873    ) -> Result<ReadableByteStreamObjects<'js, R>> {
874        // Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
875        let clone_result = match ArrayBuffer::new_copy(
876            ctx.clone(),
877            &unsafe { buffer.as_bytes() }.expect(
878                "ReadableByteStreamControllerEnqueueClonedChunkToQueue called on detached buffer",
879            )[byte_offset..byte_offset + byte_length],
880        ) {
881            Ok(clone_result) => clone_result,
882            Err(Error::Exception) => {
883                let err = ctx.catch();
884                Self::readable_byte_stream_controller_error(objects, err.clone())?;
885                return Err(ctx.throw(err));
886            }
887            Err(err) => return Err(err),
888        };
889
890        // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(controller, cloneResult.[[Value]], 0, byteLength).
891        objects
892            .controller
893            .readable_byte_stream_controller_enqueue_chunk_to_queue(clone_result, 0, byte_length);
894
895        Ok(objects)
896    }
897
898    fn readable_byte_stream_controller_fill_read_request_from_queue(
899        ctx: &Ctx<'js>,
900        mut objects: ReadableStreamDefaultReaderObjects<'js, OwnedBorrowMut<'js, Self>>,
901        read_request: impl ReadableStreamReadRequest<'js>,
902    ) -> Result<ReadableStreamDefaultReaderObjects<'js, OwnedBorrowMut<'js, Self>>> {
903        let entry = {
904            // Assert: controller.[[queueTotalSize]] > 0.
905            // Let entry be controller.[[queue]][0].
906            // Remove entry from controller.[[queue]].
907            let entry = objects.controller.queue.pop_front().expect(
908                "ReadableByteStreamControllerFillReadRequestFromQueue called with empty queue",
909            );
910
911            // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
912            objects.controller.queue_total_size -= entry.byte_length;
913
914            entry
915        };
916
917        // Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
918        objects = Self::readable_byte_stream_controller_handle_queue_drain(ctx.clone(), objects)?;
919
920        // Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
921        let view: TypedArray<u8> = objects
922            .controller
923            .array_constructor_primordials
924            .constructor_uint8array
925            .construct((entry.buffer, entry.byte_offset, entry.byte_length))?;
926
927        // Perform readRequest’s chunk steps, given view.
928        read_request.chunk_steps_typed(objects, view.into_value())
929    }
930
931    fn readable_byte_stream_controller_fill_pull_into_descriptor_from_queue<'a>(
932        &'a mut self,
933        ctx: &Ctx<'js>,
934        pull_into_descriptor_ref: &mut PullIntoDescriptorRefMut<'js, 'a>,
935    ) -> Result<bool> {
936        let (mut total_bytes_to_copy_remaining, ready) = {
937            let pull_into_descriptor = match pull_into_descriptor_ref {
938                PullIntoDescriptorRefMut::Index(i) => &mut self.pending_pull_intos[*i],
939                PullIntoDescriptorRefMut::Owned(r) => r,
940            };
941            // Let maxBytesToCopy be min(controller.[[queueTotalSize]], pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
942            let max_bytes_to_copy: usize = std::cmp::min(
943                self.queue_total_size,
944                pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled,
945            );
946
947            // Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
948            let max_bytes_filled = pull_into_descriptor.bytes_filled + max_bytes_to_copy;
949
950            // Let totalBytesToCopyRemaining be maxBytesToCopy.
951            let mut total_bytes_to_copy_remaining = max_bytes_to_copy;
952
953            // Let ready be false.
954            let mut ready = false;
955
956            // Let remainderBytes be the remainder after dividing maxBytesFilled by pullIntoDescriptor’s element size.
957            let remainder_bytes = max_bytes_filled % pull_into_descriptor.element_size;
958
959            // Let maxAlignedBytes be maxBytesFilled − remainderBytes.
960            let max_aligned_bytes = max_bytes_filled - remainder_bytes;
961
962            // If maxAlignedBytes ≥ pullIntoDescriptor’s minimum fill,
963            if max_aligned_bytes >= pull_into_descriptor.minimum_fill {
964                // Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.
965                total_bytes_to_copy_remaining =
966                    max_aligned_bytes - pull_into_descriptor.bytes_filled;
967                // Set ready to true.
968                ready = true
969            }
970
971            (total_bytes_to_copy_remaining, ready)
972        };
973
974        // Let queue be controller.[[queue]].
975        // While totalBytesToCopyRemaining > 0,
976        while total_bytes_to_copy_remaining > 0 {
977            let bytes_to_copy = {
978                let pull_into_descriptor = match pull_into_descriptor_ref {
979                    PullIntoDescriptorRefMut::Index(i) => &mut self.pending_pull_intos[*i],
980                    PullIntoDescriptorRefMut::Owned(r) => r,
981                };
982
983                // Let headOfQueue be queue[0].
984                let head_of_queue = self
985                    .queue
986                    .front_mut()
987                    .expect("empty queue with bytes to copy");
988                // Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
989                let bytes_to_copy: usize =
990                    std::cmp::min(total_bytes_to_copy_remaining, head_of_queue.byte_length);
991                // Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
992                let dest_start: usize =
993                    pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
994                // Perform ! CopyDataBlockBytes(pullIntoDescriptor’s buffer.[[ArrayBufferData]], destStart, headOfQueue’s buffer.[[ArrayBufferData]], headOfQueue’s byte offset, bytesToCopy).
995                copy_data_block_bytes(
996                    ctx,
997                    &pull_into_descriptor.buffer,
998                    dest_start,
999                    &head_of_queue.buffer,
1000                    head_of_queue.byte_offset,
1001                    bytes_to_copy,
1002                )?;
1003                if head_of_queue.byte_length == bytes_to_copy {
1004                    // If headOfQueue’s byte length is bytesToCopy,
1005                    // Remove queue[0].
1006                    self.queue.pop_front();
1007                } else {
1008                    // Otherwise,
1009                    // Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
1010                    head_of_queue.byte_offset += bytes_to_copy;
1011                    // Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
1012                    head_of_queue.byte_length -= bytes_to_copy
1013                }
1014
1015                // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
1016                self.queue_total_size -= bytes_to_copy;
1017
1018                bytes_to_copy
1019            };
1020
1021            // Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesToCopy, pullIntoDescriptor).
1022            self.readable_byte_stream_controller_fill_head_pull_into_descriptor(
1023                bytes_to_copy,
1024                pull_into_descriptor_ref,
1025            );
1026
1027            // Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
1028            total_bytes_to_copy_remaining -= bytes_to_copy
1029        }
1030
1031        Ok(ready)
1032    }
1033
1034    fn readable_byte_stream_controller_commit_pull_into_descriptor<R: ReadableStreamReader<'js>>(
1035        ctx: Ctx<'js>,
1036        objects: ReadableByteStreamObjects<'js, R>,
1037        pull_into_descriptor: PullIntoDescriptor<'js>,
1038    ) -> Result<ReadableByteStreamObjects<'js, R>> {
1039        // Let done be false.
1040        let mut done = false;
1041        // If stream.[[state]] is "closed",
1042        if matches!(objects.stream.state, ReadableStreamState::Closed) {
1043            // Set done to true.
1044            done = true
1045        }
1046
1047        let reader_type = pull_into_descriptor.reader_type;
1048
1049        // Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
1050        let filled_view = Self::readable_byte_stream_controller_convert_pull_into_descriptor(
1051            ctx.clone(),
1052            &objects.stream.function_array_buffer_is_view,
1053            pull_into_descriptor,
1054        )?;
1055
1056        if let PullIntoDescriptorReaderType::Default = reader_type {
1057            // If pullIntoDescriptor’s reader type is "default",
1058            objects.with_assert_default_reader(|objects| {
1059                // Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
1060                ReadableStream::readable_stream_fulfill_read_request(
1061                    &ctx,
1062                    objects,
1063                    filled_view.into_js(&ctx)?,
1064                    done,
1065                )
1066            })
1067        } else {
1068            // Otherwise,
1069            objects.with_assert_byob_reader(|objects| {
1070                // Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
1071                ReadableStream::readable_stream_fulfill_read_into_request(
1072                    &ctx,
1073                    objects,
1074                    filled_view,
1075                    done,
1076                )
1077            })
1078        }
1079    }
1080
1081    fn readable_byte_stream_controller_handle_queue_drain<R: ReadableStreamReader<'js>>(
1082        ctx: Ctx<'js>,
1083        mut objects: ReadableByteStreamObjects<'js, R>,
1084    ) -> Result<ReadableByteStreamObjects<'js, R>> {
1085        // If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
1086        if objects.controller.queue_total_size == 0 && objects.controller.close_requested {
1087            // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
1088            objects
1089                .controller
1090                .readable_byte_stream_controller_clear_algorithms();
1091            // Perform ! ReadableStreamClose(controller.[[stream]]).
1092            ReadableStream::readable_stream_close(ctx, objects)
1093        } else {
1094            // Otherwise,
1095            // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
1096            Self::readable_byte_stream_controller_call_pull_if_needed(ctx.clone(), objects)
1097        }
1098    }
1099
1100    fn readable_byte_stream_controller_convert_pull_into_descriptor(
1101        ctx: Ctx<'js>,
1102        function_array_buffer_is_view: &Function<'js>,
1103        pull_into_descriptor: PullIntoDescriptor<'js>,
1104    ) -> Result<ViewBytes<'js>> {
1105        let PullIntoDescriptor {
1106            // Let bytesFilled be pullIntoDescriptor’s bytes filled.
1107            bytes_filled,
1108            // Let elementSize be pullIntoDescriptor’s element size.
1109            element_size,
1110            byte_offset,
1111            buffer,
1112            ..
1113        } = pull_into_descriptor;
1114        // Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
1115        let buffer = transfer_array_buffer(buffer);
1116        // Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
1117        let view: Object = pull_into_descriptor.view_constructor.construct((
1118            buffer,
1119            byte_offset,
1120            bytes_filled / element_size,
1121        ))?;
1122        ViewBytes::from_object(&ctx, function_array_buffer_is_view, &view)
1123    }
1124
1125    pub(super) fn readable_byte_stream_controller_pull_into(
1126        ctx: &Ctx<'js>,
1127        // Let stream be controller.[[stream]].
1128        mut objects: ReadableStreamBYOBObjects<'js>,
1129        view: ViewBytes<'js>,
1130        min: u64,
1131        read_into_request: impl ReadableStreamReadIntoRequest<'js> + 'js,
1132    ) -> Result<ReadableStreamBYOBObjects<'js>> {
1133        // Set elementSize to the element size specified in the typed array constructors table for view.[[TypedArrayName]].
1134        // Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
1135        let (element_size, ctor) = (
1136            view.element_size(),
1137            objects
1138                .controller
1139                .array_constructor_primordials
1140                .for_view_bytes(&view),
1141        );
1142
1143        // Let minimumFill be min × elementSize.
1144        let minimum_fill: usize = (min as usize) * element_size;
1145
1146        // Let byteOffset be view.[[ByteOffset]].
1147        // Let byteLength be view.[[ByteLength]].
1148        let (buffer, byte_length, byte_offset) = view.get_array_buffer()?;
1149
1150        // Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
1151        let buffer_result = transfer_array_buffer(buffer);
1152        let buffer = match buffer_result {
1153            // If bufferResult is an abrupt completion,
1154            Err(Error::Exception) => {
1155                // Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
1156                objects = read_into_request.error_steps(objects, ctx.catch())?;
1157                // Return.
1158                return Ok(objects);
1159            }
1160            Err(err) => return Err(err),
1161            // Let buffer be bufferResult.[[Value]].
1162            Ok(buffer) => buffer,
1163        };
1164
1165        let buffer_byte_length = buffer.len();
1166        // Let pullIntoDescriptor be a new pull-into descriptor with
1167        let mut pull_into_descriptor = PullIntoDescriptor {
1168            buffer,
1169            buffer_byte_length,
1170            byte_offset,
1171            byte_length,
1172            bytes_filled: 0,
1173            minimum_fill,
1174            element_size,
1175            view_constructor: ctor.clone(),
1176            reader_type: PullIntoDescriptorReaderType::Byob,
1177        };
1178
1179        // If controller.[[pendingPullIntos]] is not empty,
1180        if !objects.controller.pending_pull_intos.is_empty() {
1181            // Append pullIntoDescriptor to controller.[[pendingPullIntos]].
1182            objects
1183                .controller
1184                .pending_pull_intos
1185                .push_back(pull_into_descriptor);
1186
1187            // Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
1188            ReadableStream::readable_stream_add_read_into_request(
1189                &mut objects.reader,
1190                read_into_request,
1191            );
1192
1193            // Return.
1194            return Ok(objects);
1195        }
1196
1197        // If stream.[[state]] is "closed",
1198        if matches!(objects.stream.state, ReadableStreamState::Closed) {
1199            // Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, 0 »).
1200            let empty_view: Value<'js> = ctor.construct((
1201                pull_into_descriptor.buffer,
1202                pull_into_descriptor.byte_offset,
1203                0,
1204            ))?;
1205
1206            // Perform readIntoRequest’s close steps, given emptyView.
1207            objects = read_into_request.close_steps(objects, empty_view)?;
1208
1209            // Return.
1210            return Ok(objects);
1211        }
1212
1213        // If controller.[[queueTotalSize]] > 0,
1214        if objects.controller.queue_total_size > 0 {
1215            // If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
1216            if objects
1217                .controller
1218                .readable_byte_stream_controller_fill_pull_into_descriptor_from_queue(
1219                    ctx,
1220                    &mut PullIntoDescriptorRefMut::Owned(&mut pull_into_descriptor),
1221                )?
1222            {
1223                // Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
1224                let filled_view = objects
1225                    .controller
1226                    .readable_byte_steam_controller_convert_pull_into_descriptor(
1227                        pull_into_descriptor,
1228                    )?;
1229
1230                // Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
1231                objects =
1232                    Self::readable_byte_stream_controller_handle_queue_drain(ctx.clone(), objects)?;
1233
1234                // Perform readIntoRequest’s chunk steps, given filledView.
1235                // Return.
1236                return read_into_request.chunk_steps(objects, filled_view);
1237            }
1238
1239            // If controller.[[closeRequested]] is true,
1240            if objects.controller.close_requested {
1241                // Let e be a TypeError exception.
1242                let e: Value = objects
1243                    .stream
1244                    .constructor_type_error
1245                    .call(("Insufficient bytes to fill elements in the given buffer",))?;
1246
1247                // Perform ! ReadableByteStreamControllerError(controller, e).
1248                objects = Self::readable_byte_stream_controller_error(objects, e.clone())?;
1249
1250                // Perform readIntoRequest’s error steps, given e.
1251                // Return.
1252                return read_into_request.error_steps(objects, e);
1253            }
1254        }
1255
1256        // Append pullIntoDescriptor to controller.[[pendingPullIntos]].
1257        objects
1258            .controller
1259            .pending_pull_intos
1260            .push_back(pull_into_descriptor);
1261
1262        // Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
1263        ReadableStream::readable_stream_add_read_into_request(
1264            &mut objects.reader,
1265            read_into_request,
1266        );
1267
1268        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
1269        Self::readable_byte_stream_controller_call_pull_if_needed(ctx.clone(), objects)
1270    }
1271
1272    fn readable_byte_steam_controller_convert_pull_into_descriptor(
1273        &mut self,
1274        pull_into_descriptor: PullIntoDescriptor<'js>,
1275    ) -> Result<Value<'js>> {
1276        // Let bytesFilled be pullIntoDescriptor’s bytes filled.
1277        let bytes_filled = pull_into_descriptor.bytes_filled;
1278
1279        // Let elementSize be pullIntoDescriptor’s element size.
1280        let element_size = pull_into_descriptor.element_size;
1281
1282        // Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
1283        let buffer = transfer_array_buffer(pull_into_descriptor.buffer)?;
1284
1285        // Return ! Construct(pullIntoDescriptor’s view constructor, « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
1286        pull_into_descriptor.view_constructor.construct((
1287            buffer,
1288            pull_into_descriptor.byte_offset,
1289            bytes_filled / element_size,
1290        ))
1291    }
1292
1293    pub(super) fn readable_byte_stream_controller_respond<R: ReadableStreamReader<'js>>(
1294        ctx: Ctx<'js>,
1295        mut objects: ReadableByteStreamObjects<'js, R>,
1296        bytes_written: usize,
1297    ) -> Result<()> {
1298        // Let firstDescriptor be controller.[[pendingPullIntos]][0].
1299        let first_descriptor = &mut objects.controller.pending_pull_intos[0];
1300
1301        // Let state be controller.[[stream]].[[state]].
1302        match objects.stream.state {
1303            // If state is "closed",
1304            ReadableStreamState::Closed => {
1305                // If bytesWritten is not 0, throw a TypeError exception.
1306                if bytes_written != 0 {
1307                    return Err(Exception::throw_type(
1308                        &ctx,
1309                        "bytesWritten must be 0 when calling respond() on a closed stream",
1310                    ));
1311                }
1312            }
1313            // Otherwise,
1314            _ => {
1315                // If bytesWritten is 0, throw a TypeError exception.
1316                if bytes_written == 0 {
1317                    return Err(Exception::throw_type(
1318                        &ctx,
1319                        "bytesWritten must be greater than 0 when calling respond() on a readable stream",
1320                    ));
1321                }
1322
1323                // If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length, throw a RangeError exception.
1324                if first_descriptor.bytes_filled + bytes_written > first_descriptor.byte_length {
1325                    return Err(Exception::throw_range(&ctx, "bytesWritten out of range'"));
1326                }
1327            }
1328        };
1329
1330        // Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).
1331        first_descriptor.buffer = transfer_array_buffer(first_descriptor.buffer.clone())?;
1332
1333        // Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).
1334        Self::readable_byte_stream_controller_respond_internal(ctx, objects, bytes_written)
1335    }
1336
1337    fn readable_byte_stream_controller_respond_internal<R: ReadableStreamReader<'js>>(
1338        ctx: Ctx<'js>,
1339        mut objects: ReadableByteStreamObjects<'js, R>,
1340        bytes_written: usize,
1341    ) -> Result<()> {
1342        // Let firstDescriptor be controller.[[pendingPullIntos]][0].
1343        let first_descriptor_index = 0;
1344
1345        // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
1346        objects
1347            .controller
1348            .readable_byte_stream_controller_invalidate_byob_request();
1349
1350        // Let state be controller.[[stream]].[[state]].
1351        match objects.stream.state {
1352            // If state is "closed",
1353            ReadableStreamState::Closed => {
1354                // Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).
1355                objects = Self::readable_byte_stream_controller_respond_in_closed_state(
1356                    ctx.clone(),
1357                    objects,
1358                    first_descriptor_index,
1359                )?;
1360            }
1361            // Otherwise
1362            _ => {
1363                // Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).
1364                objects = Self::readable_byte_stream_controller_respond_in_readable_state(
1365                    ctx.clone(),
1366                    objects,
1367                    bytes_written,
1368                    first_descriptor_index,
1369                )?
1370            }
1371        };
1372
1373        _ = Self::readable_byte_stream_controller_call_pull_if_needed(ctx, objects)?;
1374        Ok(())
1375    }
1376
1377    fn readable_byte_stream_controller_respond_in_closed_state<R: ReadableStreamReader<'js>>(
1378        ctx: Ctx<'js>,
1379        // Let stream be controller.[[stream]].
1380        mut objects: ReadableByteStreamObjects<'js, R>,
1381        first_descriptor_index: usize,
1382    ) -> Result<ReadableByteStreamObjects<'js, R>> {
1383        // If firstDescriptor’s reader type is "none", perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1384        if let PullIntoDescriptorReaderType::None =
1385            objects.controller.pending_pull_intos[first_descriptor_index].reader_type
1386        {
1387            objects
1388                .controller
1389                .readable_byte_stream_controller_shift_pending_pull_into();
1390        }
1391
1392        // If ! ReadableStreamHasBYOBReader(stream) is true,
1393        objects.with_reader(
1394            Ok,
1395            |mut objects| {
1396                // While ! ReadableStreamGetNumReadIntoRequests(stream) > 0,
1397                while ReadableStream::readable_stream_get_num_read_into_requests(&objects.reader)
1398                    > 0
1399                {
1400                    // Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1401                    let pull_into_descriptor = objects
1402                        .controller
1403                        .readable_byte_stream_controller_shift_pending_pull_into();
1404
1405                    // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, pullIntoDescriptor).
1406                    objects = Self::readable_byte_stream_controller_commit_pull_into_descriptor(
1407                        ctx.clone(),
1408                        objects,
1409                        pull_into_descriptor,
1410                    )?;
1411                }
1412
1413                Ok(objects)
1414            },
1415            Ok,
1416        )
1417    }
1418
1419    fn readable_byte_stream_controller_respond_in_readable_state<R: ReadableStreamReader<'js>>(
1420        ctx: Ctx<'js>,
1421        // Let stream be controller.[[stream]].
1422        mut objects: ReadableByteStreamObjects<'js, R>,
1423        bytes_written: usize,
1424        pull_into_descriptor_index: usize,
1425    ) -> Result<ReadableByteStreamObjects<'js, R>> {
1426        // Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(controller, bytesWritten, pullIntoDescriptor).
1427        objects
1428            .controller
1429            .readable_byte_stream_controller_fill_head_pull_into_descriptor(
1430                bytes_written,
1431                &mut PullIntoDescriptorRefMut::Index(pull_into_descriptor_index),
1432            );
1433
1434        // If pullIntoDescriptor’s reader type is "none",
1435        if let PullIntoDescriptorReaderType::None =
1436            objects.controller.pending_pull_intos[pull_into_descriptor_index].reader_type
1437        {
1438            // Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).
1439            objects = Self::readable_byte_stream_enqueue_detached_pull_into_to_queue(
1440                ctx.clone(),
1441                objects,
1442                pull_into_descriptor_index,
1443            )?;
1444            // Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
1445            // Return.
1446            return Self::readable_byte_stream_controller_process_pull_into_descriptors_using_queue(
1447                &ctx, objects,
1448            );
1449        }
1450
1451        // If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.
1452        if objects.controller.pending_pull_intos[pull_into_descriptor_index].bytes_filled
1453            < objects.controller.pending_pull_intos[pull_into_descriptor_index].minimum_fill
1454        {
1455            return Ok(objects);
1456        }
1457
1458        // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1459        let mut pull_into_descriptor = objects
1460            .controller
1461            .readable_byte_stream_controller_shift_pending_pull_into();
1462
1463        // Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes filled by pullIntoDescriptor’s element size.
1464        let remainder_size = pull_into_descriptor.bytes_filled % pull_into_descriptor.element_size;
1465
1466        // If remainderSize > 0,
1467        if remainder_size > 0 {
1468            // Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
1469            let end = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled;
1470
1471            let buffer = pull_into_descriptor.buffer.clone();
1472
1473            // Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller, pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).
1474            objects = Self::readable_byte_stream_controller_enqueue_cloned_chunk_to_queue(
1475                ctx.clone(),
1476                objects,
1477                &buffer,
1478                end - remainder_size,
1479                remainder_size,
1480            )?;
1481        }
1482
1483        // Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.
1484        pull_into_descriptor.bytes_filled -= remainder_size;
1485
1486        // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
1487        objects = Self::readable_byte_stream_controller_commit_pull_into_descriptor(
1488            ctx.clone(),
1489            objects,
1490            pull_into_descriptor,
1491        )?;
1492
1493        // Perform ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
1494        Self::readable_byte_stream_controller_process_pull_into_descriptors_using_queue(
1495            &ctx, objects,
1496        )
1497    }
1498
1499    pub(super) fn readable_byte_stream_controller_respond_with_new_view<
1500        R: ReadableStreamReader<'js>,
1501    >(
1502        ctx: Ctx<'js>,
1503        mut objects: ReadableByteStreamObjects<'js, R>,
1504        view: ViewBytes<'js>,
1505    ) -> Result<()> {
1506        // Let firstDescriptor be controller.[[pendingPullIntos]][0].
1507        let first_descriptor_index = 0;
1508
1509        let (buffer, byte_length, byte_offset) = view.get_array_buffer()?;
1510
1511        // Let state be controller.[[stream]].[[state]].
1512        match objects.stream.state {
1513            // If state is "closed",
1514            ReadableStreamState::Closed => {
1515                // If view.[[ByteLength]] is not 0, throw a TypeError exception.
1516                if byte_length != 0 {
1517                    return Err(Exception::throw_type(&ctx, "The view's length must be 0 when calling respondWithNewView() on a closed stream"));
1518                }
1519            }
1520            // Otherwise
1521            _ => {
1522                // If view.[[ByteLength]] is 0, throw a TypeError exception.
1523                if byte_length == 0 {
1524                    return Err(Exception::throw_type(&ctx, "The view's length must be greater than 0 when calling respondWithNewView() on a readable stream"));
1525                }
1526            }
1527        };
1528
1529        {
1530            let first_descriptor =
1531                &mut objects.controller.pending_pull_intos[first_descriptor_index];
1532
1533            // If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]], throw a RangeError exception.
1534            if first_descriptor.byte_offset + first_descriptor.bytes_filled != byte_offset {
1535                return Err(Exception::throw_range(
1536                    &ctx,
1537                    "The region specified by view does not match byobRequest",
1538                ));
1539            };
1540
1541            // If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]], throw a RangeError exception.
1542            if first_descriptor.buffer_byte_length != buffer.len() {
1543                return Err(Exception::throw_range(
1544                    &ctx,
1545                    "The buffer of view has different capacity than byobRequest",
1546                ));
1547            };
1548
1549            // If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length, throw a RangeError exception.
1550            if first_descriptor.bytes_filled + byte_length > first_descriptor.byte_length {
1551                return Err(Exception::throw_range(
1552                    &ctx,
1553                    "The region specified by view is larger than byobRequest",
1554                ));
1555            }
1556
1557            // Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
1558            first_descriptor.buffer = transfer_array_buffer(buffer)?;
1559        }
1560
1561        // Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).
1562        Self::readable_byte_stream_controller_respond_internal(ctx, objects, byte_length)
1563    }
1564
1565    fn readable_byte_stream_controller_fill_head_pull_into_descriptor<'a>(
1566        &mut self,
1567        size: usize,
1568        pull_into_descriptor_ref: &mut PullIntoDescriptorRefMut<'js, 'a>,
1569    ) {
1570        let pull_into_descriptor = match pull_into_descriptor_ref {
1571            PullIntoDescriptorRefMut::Index(i) => &mut self.pending_pull_intos[*i],
1572            PullIntoDescriptorRefMut::Owned(r) => *r,
1573        };
1574
1575        // Set pullIntoDescriptor’s bytes filled to bytes filled + size.
1576        pull_into_descriptor.bytes_filled += size;
1577    }
1578
1579    fn start_algorithm<R: ReadableStreamReader<'js>>(
1580        ctx: Ctx<'js>,
1581        objects: ReadableByteStreamObjects<'js, R>,
1582        start_algorithm: StartAlgorithm<'js>,
1583    ) -> Result<(
1584        Value<'js>,
1585        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
1586    )> {
1587        let objects_class = objects.into_inner();
1588
1589        Ok((
1590            start_algorithm.call(
1591                ctx,
1592                ReadableStreamControllerClass::ReadableStreamByteController(
1593                    objects_class.controller.clone(),
1594                ),
1595            )?,
1596            objects_class,
1597        ))
1598    }
1599
1600    fn pull_algorithm<R: ReadableStreamReader<'js>>(
1601        ctx: Ctx<'js>,
1602        objects: ReadableByteStreamObjects<'js, R>,
1603    ) -> Result<(
1604        Promise<'js>,
1605        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
1606    )> {
1607        let pull_algorithm = objects
1608            .controller
1609            .pull_algorithm
1610            .clone()
1611            .expect("pull algorithm used after ReadableStreamDefaultControllerClearAlgorithms");
1612        let promise_primordials = objects.stream.promise_primordials.clone();
1613        let objects_class = objects.into_inner();
1614
1615        Ok((
1616            pull_algorithm.call(
1617                ctx,
1618                &promise_primordials,
1619                ReadableStreamControllerClass::ReadableStreamByteController(
1620                    objects_class.controller.clone(),
1621                ),
1622            )?,
1623            objects_class,
1624        ))
1625    }
1626
1627    fn cancel_algorithm<R: ReadableStreamReader<'js>>(
1628        ctx: Ctx<'js>,
1629        objects: ReadableByteStreamObjects<'js, R>,
1630        reason: Value<'js>,
1631    ) -> Result<(
1632        Promise<'js>,
1633        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
1634    )> {
1635        let cancel_algorithm =
1636            objects.controller.cancel_algorithm.clone().expect(
1637                "cancel algorithm used after ReadableStreamDefaultControllerClearAlgorithms",
1638            );
1639        let promise_primordials = objects.stream.promise_primordials.clone();
1640        let objects_class = objects.into_inner();
1641
1642        Ok((
1643            cancel_algorithm.call(ctx, &promise_primordials, reason)?,
1644            objects_class,
1645        ))
1646    }
1647}
1648
1649#[methods(rename_all = "camelCase")]
1650impl<'js> ReadableByteStreamController<'js> {
1651    #[qjs(constructor)]
1652    fn new(ctx: Ctx<'js>) -> Result<Class<'js, Self>> {
1653        Err(Exception::throw_type(&ctx, "Illegal constructor"))
1654    }
1655
1656    // readonly attribute ReadableStreamBYOBRequest? byobRequest;
1657    #[qjs(get, rename = "byobRequest")]
1658    fn byob_request_getter(
1659        ctx: Ctx<'js>,
1660        controller: This<Class<'js, Self>>,
1661    ) -> Result<Null<Class<'js, ReadableStreamBYOBRequest<'js>>>> {
1662        // Use `try_borrow_mut` so that reentrant access during enqueue
1663        // (e.g. via a patched `Object.prototype.then` getter, WPT
1664        // `readable-byte-streams/patched-global`) doesn't hard-error with
1665        // "can't borrow" when the outer enqueue already holds the mut
1666        // borrow. If the controller IS currently borrowed, we can still
1667        // answer correctly by reading the state via an immutable try_borrow;
1668        // materialization is only needed when state is consistent.
1669        if let Ok(owned) = rquickjs::class::OwnedBorrowMut::try_from_class(controller.0.clone()) {
1670            let (request, _) = Self::readable_byte_stream_controller_get_byob_request(ctx, owned)?;
1671            return Ok(request);
1672        }
1673        // Reentrant access mid-enqueue: can't acquire immutable borrow
1674        // either (because enqueue holds mut). Return null — the spec's
1675        // observable state during this transient window is that the
1676        // byob request has been invalidated (the enqueue path clears it
1677        // as pull-into descriptors are filled).
1678        Ok(Null(None))
1679    }
1680
1681    // readonly attribute unrestricted double? desiredSize;
1682    #[qjs(get)]
1683    fn desired_size(&self) -> Null<f64> {
1684        let stream = OwnedBorrow::from_class(self.stream.clone());
1685        self.readable_byte_stream_controller_get_desired_size(&stream)
1686    }
1687
1688    // undefined close();
1689    fn close(ctx: Ctx<'js>, controller: This<OwnedBorrowMut<'js, Self>>) -> Result<()> {
1690        // If this.[[closeRequested]] is true, throw a TypeError exception.
1691        if controller.close_requested {
1692            return Err(Exception::throw_type(&ctx, "close() called more than once"));
1693        }
1694
1695        let objects = ReadableStreamObjects::from_byte_controller(controller.0).refresh_reader();
1696
1697        if !matches!(objects.stream.state, ReadableStreamState::Readable) {
1698            return Err(Exception::throw_type(
1699                &ctx,
1700                "close() called when stream is not readable",
1701            ));
1702        };
1703
1704        // Perform ? ReadableByteStreamControllerClose(this).
1705        Self::readable_byte_stream_controller_close(ctx, objects)?;
1706        Ok(())
1707    }
1708
1709    // undefined enqueue(ArrayBufferView chunk);
1710    fn enqueue(
1711        this: This<OwnedBorrowMut<'js, Self>>,
1712        ctx: Ctx<'js>,
1713        chunk: Value<'js>,
1714    ) -> Result<()> {
1715        let chunk = ViewBytes::from_value(&ctx, &this.function_array_buffer_is_view, Some(&chunk))?;
1716
1717        let (array_buffer, byte_length, _) = chunk.get_array_buffer()?;
1718
1719        // If chunk.[[ByteLength]] is 0, throw a TypeError exception.
1720        if byte_length == 0 {
1721            return Err(Exception::throw_type(
1722                &ctx,
1723                "chunk must have non-zero byteLength",
1724            ));
1725        }
1726
1727        // If chunk.[[ViewedArrayBuffer]].[[ArrayBufferByteLength]] is 0, throw a TypeError exception.
1728        if array_buffer.is_empty() {
1729            return Err(Exception::throw_type(
1730                &ctx,
1731                "chunk must have non-zero buffer byteLength",
1732            ));
1733        }
1734
1735        // If this.[[closeRequested]] is true, throw a TypeError exception.
1736        if this.close_requested {
1737            return Err(Exception::throw_type(&ctx, "stream is closed or draining"));
1738        }
1739
1740        let objects = ReadableStreamObjects::from_byte_controller(this.0).refresh_reader();
1741
1742        // If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.
1743        if !matches!(objects.stream.state, ReadableStreamState::Readable) {
1744            return Err(Exception::throw_type(
1745                &ctx,
1746                "The stream is not in the readable state and cannot be enqueued to",
1747            ));
1748        };
1749
1750        // Return ? ReadableByteStreamControllerEnqueue(this, chunk).
1751        Self::readable_byte_stream_controller_enqueue(&ctx, objects, chunk)?;
1752        Ok(())
1753    }
1754
1755    // undefined error(optional any e);
1756    fn error(
1757        ctx: Ctx<'js>,
1758        controller: This<OwnedBorrowMut<'js, Self>>,
1759        e: Opt<Value<'js>>,
1760    ) -> Result<()> {
1761        let objects = ReadableStreamObjects::from_byte_controller(controller.0).refresh_reader();
1762
1763        // Perform ! ReadableByteStreamControllerError(this, e).
1764        Self::readable_byte_stream_controller_error(objects, e.0.unwrap_or_undefined(&ctx))?;
1765        Ok(())
1766    }
1767}
1768
1769impl<'js> ReadableStreamController<'js> for ReadableByteStreamControllerOwned<'js> {
1770    type Class = ReadableByteStreamControllerClass<'js>;
1771
1772    fn with_controller<C, O>(
1773        self,
1774        ctx: C,
1775        _: impl FnOnce(
1776            C,
1777            ReadableStreamDefaultControllerOwned<'js>,
1778        ) -> Result<(O, ReadableStreamDefaultControllerOwned<'js>)>,
1779        byte: impl FnOnce(
1780            C,
1781            ReadableByteStreamControllerOwned<'js>,
1782        ) -> Result<(O, ReadableByteStreamControllerOwned<'js>)>,
1783    ) -> Result<(O, Self)> {
1784        let (ctx, reader) = byte(ctx, self)?;
1785        Ok((ctx, reader))
1786    }
1787
1788    fn into_inner(self) -> Self::Class {
1789        OwnedBorrowMut::into_inner(self)
1790    }
1791
1792    fn from_class(class: Self::Class) -> Self {
1793        OwnedBorrowMut::from_class(class)
1794    }
1795
1796    fn into_erased(self) -> ReadableStreamControllerOwned<'js> {
1797        ReadableStreamControllerOwned::ReadableStreamByteController(self)
1798    }
1799
1800    fn try_from_erased(erased: ReadableStreamControllerOwned<'js>) -> Option<Self> {
1801        match erased {
1802            ReadableStreamControllerOwned::ReadableStreamDefaultController(_) => None,
1803            ReadableStreamControllerOwned::ReadableStreamByteController(r) => Some(r),
1804        }
1805    }
1806
1807    fn pull_steps(
1808        ctx: &Ctx<'js>,
1809        mut objects: ReadableStreamDefaultReaderObjects<'js, Self>,
1810        read_request: impl ReadableStreamReadRequest<'js> + 'js,
1811    ) -> Result<ReadableStreamDefaultReaderObjects<'js, Self>> {
1812        // If this.[[queueTotalSize]] > 0,
1813        if objects.controller.queue_total_size > 0 {
1814            // Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest).
1815            // Return.
1816            return ReadableByteStreamController::readable_byte_stream_controller_fill_read_request_from_queue(
1817                ctx,
1818                objects,
1819                read_request,
1820            );
1821        }
1822
1823        // Let autoAllocateChunkSize be this.[[autoAllocateChunkSize]].
1824        let auto_allocate_chunk_size = objects.controller.auto_allocate_chunk_size;
1825
1826        // If autoAllocateChunkSize is not undefined,
1827        if let Some(auto_allocate_chunk_size) = auto_allocate_chunk_size {
1828            // Let buffer be Construct(%ArrayBuffer%, « autoAllocateChunkSize »).
1829            let buffer: ArrayBuffer = match objects
1830                .controller
1831                .constructor_array_buffer
1832                .construct((auto_allocate_chunk_size,))
1833            {
1834                // If buffer is an abrupt completion,
1835                Err(Error::Exception) => {
1836                    // Perform readRequest’s error steps, given buffer.[[Value]].
1837                    return read_request.error_steps_typed(objects, ctx.catch());
1838                }
1839                Err(err) => return Err(err),
1840                Ok(buffer) => buffer,
1841            };
1842
1843            // Let pullIntoDescriptor be a new pull-into descriptor with...
1844            let pull_into_descriptor = PullIntoDescriptor {
1845                buffer,
1846                buffer_byte_length: auto_allocate_chunk_size,
1847                byte_offset: 0,
1848                byte_length: auto_allocate_chunk_size,
1849                bytes_filled: 0,
1850                minimum_fill: 1,
1851                element_size: 1,
1852                view_constructor: objects
1853                    .controller
1854                    .array_constructor_primordials
1855                    .constructor_uint8array
1856                    .clone(),
1857                reader_type: PullIntoDescriptorReaderType::Default,
1858            };
1859
1860            // Append pullIntoDescriptor to this.[[pendingPullIntos]].
1861            objects
1862                .controller
1863                .pending_pull_intos
1864                .push_back(pull_into_descriptor);
1865        }
1866
1867        // Perform ! ReadableStreamAddReadRequest(stream, readRequest).
1868        objects
1869            .stream
1870            .readable_stream_add_read_request(&mut objects.reader, read_request);
1871
1872        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(this).
1873        ReadableByteStreamController::readable_byte_stream_controller_call_pull_if_needed(
1874            ctx.clone(),
1875            objects,
1876        )
1877    }
1878
1879    fn cancel_steps<R: ReadableStreamReader<'js>>(
1880        ctx: &Ctx<'js>,
1881        mut objects: ReadableStreamObjects<'js, Self, R>,
1882        reason: Value<'js>,
1883    ) -> Result<(Promise<'js>, ReadableStreamObjects<'js, Self, R>)> {
1884        // Perform ! ReadableByteStreamControllerClearPendingPullIntos(this).
1885        objects
1886            .controller
1887            .readable_byte_stream_controller_clear_pending_pull_intos();
1888
1889        // Perform ! ResetQueue(this).
1890        objects.controller.reset_queue();
1891
1892        // Let result be the result of performing this.[[cancelAlgorithm]], passing in reason.
1893        let (result, objects_class) =
1894            ReadableByteStreamController::cancel_algorithm(ctx.clone(), objects, reason)?;
1895
1896        objects = ReadableStreamObjects::from_class(objects_class);
1897
1898        // Perform ! ReadableByteStreamControllerClearAlgorithms(this).
1899        objects
1900            .controller
1901            .readable_byte_stream_controller_clear_algorithms();
1902
1903        // Return result.
1904        Ok((result, objects))
1905    }
1906
1907    fn release_steps(&mut self) {
1908        // If this.[[pendingPullIntos]] is not empty,
1909        if !self.pending_pull_intos.is_empty() {
1910            // Let firstPendingPullInto be this.[[pendingPullIntos]][0].
1911            let first_pending_pull_into = &mut self.pending_pull_intos[0];
1912
1913            // Set firstPendingPullInto’s reader type to "none".
1914            first_pending_pull_into.reader_type = PullIntoDescriptorReaderType::None;
1915
1916            // Set this.[[pendingPullIntos]] to the list « firstPendingPullInto ».
1917            _ = self.pending_pull_intos.split_off(1);
1918        }
1919    }
1920}
1921
1922#[derive(JsLifetime, Trace, Clone)]
1923#[rquickjs::class]
1924pub(crate) struct ReadableStreamBYOBRequest<'js> {
1925    pub(super) view: Option<ViewBytes<'js>>,
1926    controller: Option<ReadableByteStreamControllerClass<'js>>,
1927}
1928
1929#[methods(rename_all = "camelCase")]
1930impl<'js> ReadableStreamBYOBRequest<'js> {
1931    #[qjs(constructor)]
1932    fn new(ctx: Ctx<'js>) -> Result<Class<'js, Self>> {
1933        Err(Exception::throw_type(&ctx, "Illegal constructor"))
1934    }
1935
1936    #[qjs(get)]
1937    fn view(&self) -> Null<ViewBytes<'js>> {
1938        Null(self.view.clone())
1939    }
1940
1941    fn respond(
1942        ctx: Ctx<'js>,
1943        byob_request: This<OwnedBorrowMut<'js, Self>>,
1944        bytes_written: usize,
1945    ) -> Result<()> {
1946        // If this.[[controller]] is undefined, throw a TypeError exception.
1947        let (controller, view) = match (&byob_request.controller, &byob_request.view) {
1948            (Some(controller), Some(view)) => (controller.clone(), view),
1949            _ => {
1950                return Err(Exception::throw_type(
1951                    &ctx,
1952                    "This BYOB request has been invalidated",
1953                ));
1954            }
1955        };
1956        let (buffer, _, _) = view.get_array_buffer()?;
1957        drop(byob_request);
1958
1959        // If ! IsDetachedBuffer(this.[[view]].[[ArrayBuffer]]) is true, throw a TypeError exception.
1960        if buffer.as_raw().is_none() {
1961            return Err(Exception::throw_type(
1962                &ctx,
1963                "The BYOB request's buffer has been detached and so cannot be used as a response",
1964            ));
1965        }
1966
1967        let objects =
1968            ReadableStreamObjects::from_byte_controller(OwnedBorrowMut::from_class(controller))
1969                .refresh_reader();
1970
1971        // Perform ? ReadableByteStreamControllerRespond(this.[[controller]], bytesWritten).
1972        ReadableByteStreamController::readable_byte_stream_controller_respond(
1973            ctx,
1974            objects,
1975            bytes_written,
1976        )
1977    }
1978
1979    fn respond_with_new_view(
1980        ctx: Ctx<'js>,
1981        byob_request: This<OwnedBorrowMut<'js, Self>>,
1982        view: Opt<Value<'js>>,
1983    ) -> Result<()> {
1984        // If this.[[controller]] is undefined, throw a TypeError exception.
1985        let controller = match &byob_request.controller {
1986            Some(controller) => controller.clone(),
1987            _ => {
1988                return Err(Exception::throw_type(
1989                    &ctx,
1990                    "This BYOB request has been invalidated",
1991                ));
1992            }
1993        };
1994        drop(byob_request);
1995
1996        let controller = OwnedBorrowMut::from_class(controller);
1997
1998        let view = ViewBytes::from_value(
1999            &ctx,
2000            &controller.function_array_buffer_is_view,
2001            view.0.as_ref(),
2002        )?;
2003
2004        let (buffer, _, _) = view.get_array_buffer()?;
2005
2006        // If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, throw a TypeError exception.
2007        if buffer.as_raw().is_none() {
2008            return Err(Exception::throw_type(
2009                &ctx,
2010                "The given view's buffer has been detached and so cannot be used as a response",
2011            ));
2012        }
2013
2014        let objects = ReadableStreamObjects::from_byte_controller(controller).refresh_reader();
2015
2016        // Return ? ReadableByteStreamControllerRespondWithNewView(this.[[controller]], view).
2017        ReadableByteStreamController::readable_byte_stream_controller_respond_with_new_view(
2018            ctx, objects, view,
2019        )
2020    }
2021}
2022
2023#[derive(JsLifetime)]
2024pub(super) struct PullIntoDescriptor<'js> {
2025    buffer: ArrayBuffer<'js>,
2026    buffer_byte_length: usize,
2027    byte_offset: usize,
2028    byte_length: usize,
2029    bytes_filled: usize,
2030    minimum_fill: usize,
2031    element_size: usize,
2032    view_constructor: Constructor<'js>,
2033    reader_type: PullIntoDescriptorReaderType,
2034}
2035
2036impl<'js> Trace<'js> for PullIntoDescriptor<'js> {
2037    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
2038        self.buffer.trace(tracer);
2039        self.buffer_byte_length.trace(tracer);
2040        self.byte_offset.trace(tracer);
2041        self.byte_length.trace(tracer);
2042        self.bytes_filled.trace(tracer);
2043        self.minimum_fill.trace(tracer);
2044        self.element_size.trace(tracer);
2045        self.view_constructor.trace(tracer);
2046        self.reader_type.trace(tracer);
2047    }
2048}
2049
2050enum PullIntoDescriptorRefMut<'js, 'a> {
2051    Index(usize),
2052    Owned(&'a mut PullIntoDescriptor<'js>),
2053}
2054
2055#[derive(Trace, Clone, Copy)]
2056enum PullIntoDescriptorReaderType {
2057    Default,
2058    Byob,
2059    None,
2060}
2061
2062#[derive(JsLifetime)]
2063struct ReadableByteStreamQueueEntry<'js> {
2064    buffer: ArrayBuffer<'js>,
2065    byte_offset: usize,
2066    byte_length: usize,
2067}
2068
2069impl<'js> Trace<'js> for ReadableByteStreamQueueEntry<'js> {
2070    fn trace<'a>(&self, tracer: Tracer<'a, 'js>) {
2071        self.buffer.trace(tracer);
2072        self.byte_offset.trace(tracer);
2073        self.byte_length.trace(tracer)
2074    }
2075}
2076
2077fn transfer_array_buffer(buffer: ArrayBuffer<'_>) -> Result<ArrayBuffer<'_>> {
2078    buffer.get::<_, Function>("transfer")?.call((This(buffer),))
2079}
2080
2081fn copy_data_block_bytes(
2082    ctx: &Ctx<'_>,
2083    to_block: &ArrayBuffer,
2084    to_index: usize,
2085    from_block: &ArrayBuffer,
2086    from_index: usize,
2087    count: usize,
2088) -> Result<()> {
2089    let mut to_raw = to_block
2090        .as_raw()
2091        .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED)
2092        .or_throw(ctx)?;
2093    let to_slice = unsafe { to_raw.as_mut() };
2094    let from_raw = from_block
2095        .as_raw()
2096        .ok_or(ERROR_MSG_ARRAY_BUFFER_DETACHED)
2097        .or_throw(ctx)?;
2098    let from_slice = unsafe { from_raw.as_ref() };
2099
2100    to_slice[to_index..to_index + count]
2101        .copy_from_slice(&from_slice[from_index..from_index + count]);
2102    Ok(())
2103}
2104
2105/// Public API for enqueuing a `Uint8Array` (built from the caller-supplied
2106/// `ArrayBuffer`) into a byte stream controller from Rust code. Used by
2107/// byte-source streams created via `ReadableStream::from_byte_pull_algorithm`.
2108pub fn readable_byte_stream_controller_enqueue_bytes<'js>(
2109    ctx: Ctx<'js>,
2110    controller: ReadableByteStreamControllerClass<'js>,
2111    buffer: ArrayBuffer<'js>,
2112) -> Result<()> {
2113    readable_byte_stream_controller_enqueue_bytes_inner(ctx, controller, buffer, false)
2114}
2115
2116/// Zero-copy variant of [`readable_byte_stream_controller_enqueue_bytes`]:
2117/// the incoming `ArrayBuffer` is NOT transferred/detached before being
2118/// queued. The producer keeps the buffer alive through the stream's
2119/// `'js` queue entry, so consumers get a `Uint8Array` that views directly
2120/// into the producer's storage.
2121///
2122/// Only call this when the caller can guarantee the backing allocation
2123/// won't be mutated out from under readers (e.g. `Blob.stream()`, where
2124/// the blob's `ArrayBuffer` is never written after construction). For the
2125/// normal spec-compliant flow that detaches the source, use
2126/// [`readable_byte_stream_controller_enqueue_bytes`].
2127pub fn readable_byte_stream_controller_enqueue_bytes_borrowed<'js>(
2128    ctx: Ctx<'js>,
2129    controller: ReadableByteStreamControllerClass<'js>,
2130    buffer: ArrayBuffer<'js>,
2131) -> Result<()> {
2132    readable_byte_stream_controller_enqueue_bytes_inner(ctx, controller, buffer, true)
2133}
2134
2135fn readable_byte_stream_controller_enqueue_bytes_inner<'js>(
2136    ctx: Ctx<'js>,
2137    controller: ReadableByteStreamControllerClass<'js>,
2138    buffer: ArrayBuffer<'js>,
2139    skip_transfer: bool,
2140) -> Result<()> {
2141    let byte_length = buffer.len();
2142    if byte_length == 0 {
2143        return Ok(());
2144    }
2145    let view = rquickjs::TypedArray::<u8>::from_arraybuffer(buffer)?;
2146    let borrow = OwnedBorrowMut::from_class(controller);
2147    let chunk = ViewBytes::from_value(
2148        &ctx,
2149        &borrow.function_array_buffer_is_view,
2150        Some(&view.into_value()),
2151    )?;
2152    let objects = ReadableStreamObjects::from_byte_controller(borrow).refresh_reader();
2153    if skip_transfer {
2154        ReadableByteStreamController::readable_byte_stream_controller_enqueue_borrowed(
2155            &ctx, objects, chunk,
2156        )?;
2157    } else {
2158        ReadableByteStreamController::readable_byte_stream_controller_enqueue(
2159            &ctx, objects, chunk,
2160        )?;
2161    }
2162    Ok(())
2163}
2164
2165/// Public API for closing a byte stream controller from Rust code.
2166pub fn readable_byte_stream_controller_close_stream<'js>(
2167    ctx: Ctx<'js>,
2168    controller: ReadableByteStreamControllerClass<'js>,
2169) -> Result<()> {
2170    let borrow = OwnedBorrowMut::from_class(controller);
2171    let objects = ReadableStreamObjects::from_byte_controller(borrow).refresh_reader();
2172    ReadableByteStreamController::readable_byte_stream_controller_close(ctx, objects)?;
2173    Ok(())
2174}