Skip to main content

script/dom/stream/
readablebytestreamcontroller.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::cmp::min;
7use std::collections::VecDeque;
8use std::rc::Rc;
9
10use dom_struct::dom_struct;
11use js::context::JSContext;
12use js::jsapi::{Heap, Type};
13use js::jsval::UndefinedValue;
14use js::realm::CurrentRealm;
15use js::rust::{HandleObject, HandleValue as SafeHandleValue, HandleValue};
16use js::typedarray::{ArrayBufferU8, ArrayBufferViewU8};
17use script_bindings::cell::DomRefCell;
18use script_bindings::reflector::{Reflector, reflect_dom_object};
19
20use super::readablestreambyobreader::ReadIntoRequest;
21use super::readablestreamdefaultreader::ReadRequest;
22use super::underlyingsourcecontainer::{UnderlyingSourceContainer, UnderlyingSourceType};
23use crate::dom::bindings::buffer_source::{
24    Constructor, HeapBufferSource, byte_size, create_array_buffer_with_size,
25    create_buffer_source_with_constructor,
26};
27use crate::dom::bindings::codegen::Bindings::ReadableByteStreamControllerBinding::ReadableByteStreamControllerMethods;
28use crate::dom::bindings::codegen::UnionTypes::ReadableStreamDefaultControllerOrReadableByteStreamController as Controller;
29use crate::dom::bindings::error::{Error, ErrorToJsval, Fallible};
30use crate::dom::bindings::reflector::DomGlobal;
31use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
32use crate::dom::bindings::trace::RootedTraceableBox;
33use crate::dom::globalscope::GlobalScope;
34use crate::dom::promise::Promise;
35use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
36use crate::dom::stream::readablestream::ReadableStream;
37use crate::dom::stream::readablestreambyobrequest::ReadableStreamBYOBRequest;
38use crate::realms::enter_auto_realm;
39use crate::script_runtime::CanGc;
40
41/// <https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry>
42#[derive(JSTraceable, MallocSizeOf)]
43#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
44pub(crate) struct QueueEntry {
45    /// <https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-buffer>
46    #[ignore_malloc_size_of = "HeapBufferSource"]
47    buffer: HeapBufferSource<ArrayBufferU8>,
48    /// <https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-offset>
49    byte_offset: usize,
50    /// <https://streams.spec.whatwg.org/#readable-byte-stream-queue-entry-byte-length>
51    byte_length: usize,
52}
53
54impl js::gc::Rootable for QueueEntry {}
55
56impl QueueEntry {
57    pub(crate) fn new(
58        buffer: RootedTraceableBox<HeapBufferSource<ArrayBufferU8>>,
59        byte_offset: usize,
60        byte_length: usize,
61    ) -> QueueEntry {
62        QueueEntry {
63            buffer: *buffer.into_box(),
64            byte_offset,
65            byte_length,
66        }
67    }
68}
69
70#[derive(Debug, Eq, JSTraceable, MallocSizeOf, PartialEq)]
71pub(crate) enum ReaderType {
72    /// <https://streams.spec.whatwg.org/#readablestreambyobreader>
73    Byob,
74    /// <https://streams.spec.whatwg.org/#readablestreamdefaultreader>
75    Default,
76}
77
78/// <https://streams.spec.whatwg.org/#pull-into-descriptor>
79#[derive(Eq, JSTraceable, MallocSizeOf, PartialEq)]
80#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
81pub(crate) struct PullIntoDescriptor {
82    #[ignore_malloc_size_of = "HeapBufferSource"]
83    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-buffer>
84    buffer: HeapBufferSource<ArrayBufferU8>,
85    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-buffer-byte-length>
86    buffer_byte_length: u64,
87    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-byte-offset>
88    byte_offset: u64,
89    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-byte-length>
90    byte_length: u64,
91    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-bytes-filled>
92    bytes_filled: Cell<u64>,
93    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-minimum-fill>
94    minimum_fill: u64,
95    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-element-size>
96    element_size: u64,
97    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-view-constructor>
98    view_constructor: Constructor,
99    /// <https://streams.spec.whatwg.org/#pull-into-descriptor-reader-type>
100    reader_type: Option<ReaderType>,
101}
102
103impl js::gc::Rootable for PullIntoDescriptor {}
104
105/// The fulfillment handler for
106/// <https://streams.spec.whatwg.org/#dom-underlyingsource-start>
107#[derive(Clone, JSTraceable, MallocSizeOf)]
108#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
109struct StartAlgorithmFulfillmentHandler {
110    controller: Dom<ReadableByteStreamController>,
111}
112
113impl Callback for StartAlgorithmFulfillmentHandler {
114    /// Continuation of <https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller>
115    /// Upon fulfillment of startPromise,
116    fn callback(&self, cx: &mut CurrentRealm, _v: HandleValue) {
117        // Set controller.[[started]] to true.
118        self.controller.started.set(true);
119
120        // Assert: controller.[[pulling]] is false.
121        assert!(!self.controller.pulling.get());
122
123        // Assert: controller.[[pullAgain]] is false.
124        assert!(!self.controller.pull_again.get());
125
126        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
127        self.controller.call_pull_if_needed(cx);
128    }
129}
130
131/// The rejection handler for
132/// <https://streams.spec.whatwg.org/#dom-underlyingsource-start>
133#[derive(Clone, JSTraceable, MallocSizeOf)]
134#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
135struct StartAlgorithmRejectionHandler {
136    controller: Dom<ReadableByteStreamController>,
137}
138
139impl Callback for StartAlgorithmRejectionHandler {
140    /// Continuation of <https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller>
141    /// Upon rejection of startPromise with reason r,
142    fn callback(&self, cx: &mut CurrentRealm, v: HandleValue) {
143        // Perform ! ReadableByteStreamControllerError(controller, r).
144        self.controller.error(cx, v);
145    }
146}
147
148/// The fulfillment handler for
149/// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed>
150#[derive(Clone, JSTraceable, MallocSizeOf)]
151#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
152struct PullAlgorithmFulfillmentHandler {
153    controller: Dom<ReadableByteStreamController>,
154}
155
156impl Callback for PullAlgorithmFulfillmentHandler {
157    /// Continuation of <https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed>
158    /// Upon fulfillment of pullPromise
159    fn callback(&self, cx: &mut CurrentRealm, _v: HandleValue) {
160        // Set controller.[[pulling]] to false.
161        self.controller.pulling.set(false);
162
163        // If controller.[[pullAgain]] is true,
164        if self.controller.pull_again.get() {
165            // Set controller.[[pullAgain]] to false.
166            self.controller.pull_again.set(false);
167
168            // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
169            self.controller.call_pull_if_needed(cx);
170        }
171    }
172}
173
174/// The rejection handler for
175/// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed>
176#[derive(Clone, JSTraceable, MallocSizeOf)]
177#[cfg_attr(crown, crown::unrooted_must_root_lint::must_root)]
178struct PullAlgorithmRejectionHandler {
179    controller: Dom<ReadableByteStreamController>,
180}
181
182impl Callback for PullAlgorithmRejectionHandler {
183    /// Continuation of <https://streams.spec.whatwg.org/#readable-stream-byte-controller-call-pull-if-needed>
184    /// Upon rejection of pullPromise with reason e.
185    fn callback(&self, cx: &mut CurrentRealm, v: HandleValue) {
186        // Perform ! ReadableByteStreamControllerError(controller, e).
187        self.controller.error(cx, v);
188    }
189}
190
191/// <https://streams.spec.whatwg.org/#readablebytestreamcontroller>
192#[dom_struct]
193pub(crate) struct ReadableByteStreamController {
194    reflector_: Reflector,
195    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-autoallocatechunksize>
196    auto_allocate_chunk_size: Option<u64>,
197    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-stream>
198    stream: MutNullableDom<ReadableStream>,
199    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-strategyhwm>
200    strategy_hwm: f64,
201    /// A mutable reference to the underlying source is used to implement these two
202    /// internal slots:
203    ///
204    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-pullalgorithm>
205    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-cancelalgorithm>
206    underlying_source: MutNullableDom<UnderlyingSourceContainer>,
207    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-queue>
208    queue: DomRefCell<VecDeque<QueueEntry>>,
209    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-queuetotalsize>
210    queue_total_size: Cell<f64>,
211    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-byobrequest>
212    byob_request: MutNullableDom<ReadableStreamBYOBRequest>,
213    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-pendingpullintos>
214    pending_pull_intos: DomRefCell<Vec<PullIntoDescriptor>>,
215    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-closerequested>
216    close_requested: Cell<bool>,
217    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-started>
218    started: Cell<bool>,
219    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-pulling>
220    pulling: Cell<bool>,
221    /// <https://streams.spec.whatwg.org/#readablebytestreamcontroller-pullalgorithm>
222    pull_again: Cell<bool>,
223}
224
225impl ReadableByteStreamController {
226    fn new_inherited(
227        underlying_source_type: UnderlyingSourceType,
228        strategy_hwm: f64,
229        global: &GlobalScope,
230        can_gc: CanGc,
231    ) -> ReadableByteStreamController {
232        let underlying_source_container =
233            UnderlyingSourceContainer::new(global, underlying_source_type, can_gc);
234        let auto_allocate_chunk_size = underlying_source_container.auto_allocate_chunk_size();
235        ReadableByteStreamController {
236            reflector_: Reflector::new(),
237            byob_request: MutNullableDom::new(None),
238            stream: MutNullableDom::new(None),
239            underlying_source: MutNullableDom::new(Some(&*underlying_source_container)),
240            auto_allocate_chunk_size,
241            pending_pull_intos: DomRefCell::new(Vec::new()),
242            strategy_hwm,
243            close_requested: Default::default(),
244            queue: DomRefCell::new(Default::default()),
245            queue_total_size: Default::default(),
246            started: Default::default(),
247            pulling: Default::default(),
248            pull_again: Default::default(),
249        }
250    }
251
252    pub(crate) fn new(
253        underlying_source_type: UnderlyingSourceType,
254        strategy_hwm: f64,
255        global: &GlobalScope,
256        can_gc: CanGc,
257    ) -> DomRoot<ReadableByteStreamController> {
258        reflect_dom_object(
259            Box::new(ReadableByteStreamController::new_inherited(
260                underlying_source_type,
261                strategy_hwm,
262                global,
263                can_gc,
264            )),
265            global,
266            can_gc,
267        )
268    }
269
270    #[allow(dead_code)]
271    pub(crate) fn set_stream(&self, stream: &ReadableStream) {
272        self.stream.set(Some(stream))
273    }
274
275    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-pull-into>
276    pub(crate) fn perform_pull_into(
277        &self,
278        cx: &mut JSContext,
279        read_into_request: &ReadIntoRequest,
280        view: &HeapBufferSource<ArrayBufferViewU8>,
281        min: u64,
282    ) {
283        // Let stream be controller.[[stream]].
284        let stream = self.stream.get().unwrap();
285
286        // Let elementSize be 1.
287        let mut element_size = 1;
288
289        // Let ctor be %DataView%.
290        let mut ctor = Constructor::DataView;
291
292        // If view has a [[TypedArrayName]] internal slot (i.e., it is not a DataView),
293        if view.has_typed_array_name() {
294            // Set elementSize to the element size specified in the
295            // typed array constructors table for view.[[TypedArrayName]].
296            let view_typw = view.get_array_buffer_view_type();
297            element_size = byte_size(view_typw);
298
299            // Set ctor to the constructor specified in the typed array constructors table for view.[[TypedArrayName]].
300            ctor = Constructor::Name(view_typw);
301        }
302
303        // Let minimumFill be min × elementSize.
304        let minimum_fill = min * element_size;
305
306        // Assert: minimumFill ≥ 0 and minimumFill ≤ view.[[ByteLength]].
307        assert!(minimum_fill <= (view.byte_length() as u64));
308
309        // Assert: the remainder after dividing minimumFill by elementSize is 0.
310        assert_eq!(minimum_fill % element_size, 0);
311
312        // Let byteOffset be view.[[ByteOffset]].
313        let byte_offset = view.get_byte_offset();
314
315        // Let byteLength be view.[[ByteLength]].
316        let byte_length = view.byte_length();
317
318        // Let bufferResult be TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
319        match view
320            .get_array_buffer_view_buffer(cx.into())
321            .transfer_array_buffer(cx.into())
322        {
323            Ok(buffer) => {
324                // Let buffer be bufferResult.[[Value]].
325                // Let pullIntoDescriptor be a new pull-into descriptor with
326                // buffer   buffer
327                // buffer byte length   buffer.[[ArrayBufferByteLength]]
328                // byte offset  byteOffset
329                // byte length  byteLength
330                // bytes filled  0
331                // minimum fill minimumFill
332                // element size elementSize
333                // view constructor ctor
334                // reader type  "byob"
335                let buffer_byte_length = buffer.byte_length();
336                let pull_into_descriptor = RootedTraceableBox::new(PullIntoDescriptor {
337                    buffer: *buffer.into_box(),
338                    buffer_byte_length: buffer_byte_length as u64,
339                    byte_offset: byte_offset as u64,
340                    byte_length: byte_length as u64,
341                    bytes_filled: Cell::new(0),
342                    minimum_fill,
343                    element_size,
344                    view_constructor: ctor.clone(),
345                    reader_type: Some(ReaderType::Byob),
346                });
347
348                // If controller.[[pendingPullIntos]] is not empty,
349                {
350                    let mut pending_pull_intos = self.pending_pull_intos.borrow_mut();
351                    if !pending_pull_intos.is_empty() {
352                        // Append pullIntoDescriptor to controller.[[pendingPullIntos]].
353                        pending_pull_intos.push(*pull_into_descriptor.into_box());
354
355                        // Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
356                        stream.add_read_into_request(read_into_request);
357
358                        // Return.
359                        return;
360                    }
361                }
362
363                // If stream.[[state]] is "closed",
364                if stream.is_closed() {
365                    // Let emptyView be ! Construct(ctor, « pullIntoDescriptor’s buffer,
366                    // pullIntoDescriptor’s byte offset, 0 »).
367                    if let Ok(empty_view) = create_buffer_source_with_constructor(
368                        cx,
369                        &ctor,
370                        &pull_into_descriptor.buffer,
371                        pull_into_descriptor.byte_offset as usize,
372                        0,
373                    ) {
374                        // Perform readIntoRequest’s close steps, given emptyView.
375                        let result = RootedTraceableBox::new(Heap::default());
376                        rooted!(&in(cx) let mut view_value = UndefinedValue());
377                        empty_view.get_buffer_view_value(cx.into(), view_value.handle_mut());
378                        result.set(*view_value);
379
380                        read_into_request.close_steps(cx, Some(result));
381
382                        // Return.
383                        return;
384                    } else {
385                        return;
386                    }
387                }
388
389                // If controller.[[queueTotalSize]] > 0,
390                if self.queue_total_size.get() > 0.0 {
391                    // If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(
392                    // controller, pullIntoDescriptor) is true,
393                    if self.fill_pull_into_descriptor_from_queue(cx, &pull_into_descriptor) {
394                        // Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(
395                        // pullIntoDescriptor).
396                        if let Ok(filled_view) =
397                            self.convert_pull_into_descriptor(cx, &pull_into_descriptor)
398                        {
399                            // Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
400                            self.handle_queue_drain(cx);
401
402                            // Perform readIntoRequest’s chunk steps, given filledView.
403                            let result = RootedTraceableBox::new(Heap::default());
404                            rooted!(&in(cx) let mut view_value = UndefinedValue());
405                            filled_view.get_buffer_view_value(cx.into(), view_value.handle_mut());
406                            result.set(*view_value);
407                            read_into_request.chunk_steps(result, CanGc::from_cx(cx));
408
409                            // Return.
410                            return;
411                        } else {
412                            return;
413                        }
414                    }
415
416                    // If controller.[[closeRequested]] is true,
417                    if self.close_requested.get() {
418                        // Let e be a new TypeError exception.
419                        rooted!(&in(cx) let mut error = UndefinedValue());
420                        Error::Type(c"close requested".to_owned()).to_jsval(
421                            cx.into(),
422                            &self.global(),
423                            error.handle_mut(),
424                            CanGc::from_cx(cx),
425                        );
426
427                        // Perform ! ReadableByteStreamControllerError(controller, e).
428                        self.error(cx, error.handle());
429
430                        // Perform readIntoRequest’s error steps, given e.
431                        read_into_request.error_steps(error.handle(), CanGc::from_cx(cx));
432
433                        // Return.
434                        return;
435                    }
436                }
437
438                // Append pullIntoDescriptor to controller.[[pendingPullIntos]].
439                {
440                    self.pending_pull_intos
441                        .borrow_mut()
442                        .push(*pull_into_descriptor.into_box());
443                }
444                // Perform ! ReadableStreamAddReadIntoRequest(stream, readIntoRequest).
445                stream.add_read_into_request(read_into_request);
446
447                // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
448                self.call_pull_if_needed(cx);
449            },
450            Err(error) => {
451                // If bufferResult is an abrupt completion,
452
453                // Perform readIntoRequest’s error steps, given bufferResult.[[Value]].
454                rooted!(&in(cx) let mut rval = UndefinedValue());
455                error.to_jsval(
456                    cx.into(),
457                    &self.global(),
458                    rval.handle_mut(),
459                    CanGc::from_cx(cx),
460                );
461                read_into_request.error_steps(rval.handle(), CanGc::from_cx(cx));
462
463                // Return.
464            },
465        }
466    }
467
468    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond>
469    pub(crate) fn respond(&self, cx: &mut JSContext, bytes_written: u64) -> Fallible<()> {
470        {
471            // Assert: controller.[[pendingPullIntos]] is not empty.
472            let mut pending_pull_intos = self.pending_pull_intos.borrow_mut();
473            assert!(!pending_pull_intos.is_empty());
474
475            // Let firstDescriptor be controller.[[pendingPullIntos]][0].
476            let first_descriptor = pending_pull_intos.first_mut().unwrap();
477
478            // Let state be controller.[[stream]].[[state]].
479            let stream = self.stream.get().unwrap();
480
481            // If state is "closed",
482            if stream.is_closed() {
483                // If bytesWritten is not 0, throw a TypeError exception.
484                if bytes_written != 0 {
485                    return Err(Error::Type(
486                        c"bytesWritten not zero on closed stream".to_owned(),
487                    ));
488                }
489            } else {
490                // Assert: state is "readable".
491                assert!(stream.is_readable());
492
493                // If bytesWritten is 0, throw a TypeError exception.
494                if bytes_written == 0 {
495                    return Err(Error::Type(c"bytesWritten is 0".to_owned()));
496                }
497
498                // If firstDescriptor’s bytes filled + bytesWritten > firstDescriptor’s byte length,
499                // throw a RangeError exception.
500                if first_descriptor.bytes_filled.get() + bytes_written >
501                    first_descriptor.byte_length
502                {
503                    return Err(Error::Range(
504                        c"bytes filled + bytesWritten > byte length".to_owned(),
505                    ));
506                }
507            }
508
509            // Set firstDescriptor’s buffer to ! TransferArrayBuffer(firstDescriptor’s buffer).
510            first_descriptor.buffer = *first_descriptor
511                .buffer
512                .transfer_array_buffer(cx.into())
513                .expect("TransferArrayBuffer failed")
514                .into_box();
515        }
516
517        // Perform ? ReadableByteStreamControllerRespondInternal(controller, bytesWritten).
518        self.respond_internal(cx, bytes_written)
519    }
520
521    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-internal>
522    fn respond_internal(&self, cx: &mut JSContext, bytes_written: u64) -> Fallible<()> {
523        {
524            // Let firstDescriptor be controller.[[pendingPullIntos]][0].
525            let pending_pull_intos = self.pending_pull_intos.borrow();
526            let first_descriptor = pending_pull_intos.first().unwrap();
527
528            // Assert: ! CanTransferArrayBuffer(firstDescriptor’s buffer) is true
529            assert!(first_descriptor.buffer.can_transfer_array_buffer(cx.into()));
530        }
531
532        // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
533        self.invalidate_byob_request();
534
535        // Let state be controller.[[stream]].[[state]].
536        let stream = self.stream.get().unwrap();
537
538        // If state is "closed",
539        if stream.is_closed() {
540            // Assert: bytesWritten is 0.
541            assert_eq!(bytes_written, 0);
542
543            // Perform ! ReadableByteStreamControllerRespondInClosedState(controller, firstDescriptor).
544            self.respond_in_closed_state(cx)
545                .expect("respond_in_closed_state failed");
546        } else {
547            // Assert: state is "readable".
548            assert!(stream.is_readable());
549
550            // Assert: bytesWritten > 0.
551            assert!(bytes_written > 0);
552
553            // Perform ? ReadableByteStreamControllerRespondInReadableState(controller, bytesWritten, firstDescriptor).
554            self.respond_in_readable_state(cx, bytes_written)?;
555        }
556
557        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
558        self.call_pull_if_needed(cx);
559
560        Ok(())
561    }
562
563    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-closed-state>
564    fn respond_in_closed_state(&self, cx: &mut JSContext) -> Fallible<()> {
565        let pending_pull_intos = self.pending_pull_intos.borrow();
566        let first_descriptor = pending_pull_intos.first().unwrap();
567
568        // Assert: the remainder after dividing firstDescriptor’s bytes filled
569        // by firstDescriptor’s element size is 0.
570        assert_eq!(
571            first_descriptor.bytes_filled.get() % first_descriptor.element_size,
572            0
573        );
574
575        // If firstDescriptor’s reader type is "none",
576        // perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
577        let reader_type = first_descriptor.reader_type.is_none();
578
579        // needed to drop the borrow and avoid BorrowMutError
580        drop(pending_pull_intos);
581
582        if reader_type {
583            self.shift_pending_pull_into();
584        }
585
586        // Let stream be controller.[[stream]].
587        let stream = self.stream.get().unwrap();
588
589        // If ! ReadableStreamHasBYOBReader(stream) is true,
590        if stream.has_byob_reader() {
591            // Let filledPullIntos be a new empty list.
592            rooted!(&in(cx) let mut filled_pull_intos = Vec::new());
593
594            // While filledPullIntos’s size < ! ReadableStreamGetNumReadIntoRequests(stream),
595            while filled_pull_intos.len() < stream.get_num_read_into_requests() {
596                // Let pullIntoDescriptor be ! ReadableByteStreamControllerShiftPendingPullInto(controller).
597                // Append pullIntoDescriptor to filledPullIntos.
598                filled_pull_intos.push(self.shift_pending_pull_into());
599            }
600
601            // For each filledPullInto of filledPullIntos,
602            for filled_pull_into in &*filled_pull_intos {
603                // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).
604                self.commit_pull_into_descriptor(cx, filled_pull_into)
605                    .expect("commit_pull_into_descriptor failed");
606            }
607        }
608
609        Ok(())
610    }
611
612    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-in-readable-state>
613    fn respond_in_readable_state(&self, cx: &mut JSContext, bytes_written: u64) -> Fallible<()> {
614        let pending_pull_intos = self.pending_pull_intos.borrow();
615        let first_descriptor = pending_pull_intos.first().unwrap();
616
617        // Assert: pullIntoDescriptor’s bytes filled + bytesWritten ≤ pullIntoDescriptor’s byte length.
618        assert!(
619            first_descriptor.bytes_filled.get() + bytes_written <= first_descriptor.byte_length
620        );
621
622        // Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(
623        // controller, bytesWritten, pullIntoDescriptor).
624        self.fill_head_pull_into_descriptor(bytes_written, first_descriptor);
625
626        // If pullIntoDescriptor’s reader type is "none",
627        if first_descriptor.reader_type.is_none() {
628            // needed to drop the borrow and avoid BorrowMutError
629            drop(pending_pull_intos);
630
631            // Perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(controller, pullIntoDescriptor).
632            self.enqueue_detached_pull_into_to_queue(cx)?;
633
634            // Let filledPullIntos be the result of performing
635            // ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
636            rooted!(&in(cx) let filled_pull_intos = self.process_pull_into_descriptors_using_queue(cx));
637
638            // For each filledPullInto of filledPullIntos,
639            for filled_pull_into in &*filled_pull_intos {
640                // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]]
641                // , filledPullInto).
642                self.commit_pull_into_descriptor(cx, filled_pull_into)
643                    .expect("commit_pull_into_descriptor failed");
644            }
645
646            // Return.
647            return Ok(());
648        }
649
650        // If pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill, return.
651        if first_descriptor.bytes_filled.get() < first_descriptor.minimum_fill {
652            return Ok(());
653        }
654
655        // needed to drop the borrow and avoid BorrowMutError
656        drop(pending_pull_intos);
657
658        // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
659        rooted!(&in(cx) let pull_into_descriptor = self.shift_pending_pull_into());
660
661        // Let remainderSize be the remainder after dividing pullIntoDescriptor’s bytes
662        // filled by pullIntoDescriptor’s element size.
663        let remainder_size =
664            pull_into_descriptor.bytes_filled.get() % pull_into_descriptor.element_size;
665
666        // If remainderSize > 0,
667        if remainder_size > 0 {
668            // Let end be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
669            let end = pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled.get();
670
671            // Perform ? ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller,
672            // pullIntoDescriptor’s buffer, end − remainderSize, remainderSize).
673            self.enqueue_cloned_chunk_to_queue(
674                cx,
675                &pull_into_descriptor.buffer,
676                end - remainder_size,
677                remainder_size,
678            )?;
679        }
680
681        // Set pullIntoDescriptor’s bytes filled to pullIntoDescriptor’s bytes filled − remainderSize.
682        pull_into_descriptor
683            .bytes_filled
684            .set(pull_into_descriptor.bytes_filled.get() - remainder_size);
685
686        // Let filledPullIntos be the result of performing
687        // ! ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
688        rooted!(&in(cx) let filled_pull_intos = self.process_pull_into_descriptors_using_queue(cx));
689
690        // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], pullIntoDescriptor).
691        self.commit_pull_into_descriptor(cx, &pull_into_descriptor)
692            .expect("commit_pull_into_descriptor failed");
693
694        // For each filledPullInto of filledPullIntos,
695        for filled_pull_into in &*filled_pull_intos {
696            // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(controller.[[stream]], filledPullInto).
697            self.commit_pull_into_descriptor(cx, filled_pull_into)
698                .expect("commit_pull_into_descriptor failed");
699        }
700
701        Ok(())
702    }
703
704    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-respond-with-new-view>
705    pub(crate) fn respond_with_new_view(
706        &self,
707        cx: &mut JSContext,
708        view: &HeapBufferSource<ArrayBufferViewU8>,
709    ) -> Fallible<()> {
710        let view_byte_length;
711        {
712            // Assert: controller.[[pendingPullIntos]] is not empty.
713            let mut pending_pull_intos = self.pending_pull_intos.borrow_mut();
714            assert!(!pending_pull_intos.is_empty());
715
716            // Assert: ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is false.
717            assert!(!view.is_detached_buffer(cx.into()));
718
719            // Let firstDescriptor be controller.[[pendingPullIntos]][0].
720            let first_descriptor = pending_pull_intos.first_mut().unwrap();
721
722            // Let state be controller.[[stream]].[[state]].
723            let stream = self.stream.get().unwrap();
724
725            // If state is "closed",
726            if stream.is_closed() {
727                // If view.[[ByteLength]] is not 0, throw a TypeError exception.
728                if view.byte_length() != 0 {
729                    return Err(Error::Type(c"view byte length is not 0".to_owned()));
730                }
731            } else {
732                // Assert: state is "readable".
733                assert!(stream.is_readable());
734
735                // If view.[[ByteLength]] is 0, throw a TypeError exception.
736                if view.byte_length() == 0 {
737                    return Err(Error::Type(c"view byte length is 0".to_owned()));
738                }
739            }
740
741            // If firstDescriptor’s byte offset + firstDescriptor’ bytes filled is not view.[[ByteOffset]],
742            // throw a RangeError exception.
743            if first_descriptor.byte_offset + first_descriptor.bytes_filled.get() !=
744                (view.get_byte_offset() as u64)
745            {
746                return Err(Error::Range(
747                    c"firstDescriptor's byte offset + bytes filled is not view byte offset"
748                        .to_owned(),
749                ));
750            }
751
752            // If firstDescriptor’s buffer byte length is not view.[[ViewedArrayBuffer]].[[ByteLength]],
753            // throw a RangeError exception.
754            if first_descriptor.buffer_byte_length !=
755                (view.viewed_buffer_array_byte_length(cx.into()) as u64)
756            {
757                return Err(Error::Range(
758                c"firstDescriptor's buffer byte length is not view viewed buffer array byte length"
759                    .to_owned(),
760            ));
761            }
762
763            // If firstDescriptor’s bytes filled + view.[[ByteLength]] > firstDescriptor’s byte length,
764            // throw a RangeError exception.
765            if first_descriptor.bytes_filled.get() + (view.byte_length()) as u64 >
766                first_descriptor.byte_length
767            {
768                return Err(Error::Range(
769                    c"bytes filled + view byte length > byte length".to_owned(),
770                ));
771            }
772
773            // Let viewByteLength be view.[[ByteLength]].
774            view_byte_length = view.byte_length();
775
776            // Set firstDescriptor’s buffer to ? TransferArrayBuffer(view.[[ViewedArrayBuffer]]).
777            first_descriptor.buffer = *view
778                .get_array_buffer_view_buffer(cx.into())
779                .transfer_array_buffer(cx.into())?
780                .into_box();
781        }
782
783        // Perform ? ReadableByteStreamControllerRespondInternal(controller, viewByteLength).
784        self.respond_internal(cx, view_byte_length as u64)
785    }
786
787    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-get-desired-size>
788    pub(crate) fn get_desired_size(&self) -> Option<f64> {
789        // Let state be controller.[[stream]].[[state]].
790        let stream = self.stream.get()?;
791
792        // If state is "errored", return null.
793        if stream.is_errored() {
794            return None;
795        }
796
797        // If state is "closed", return 0.
798        if stream.is_closed() {
799            return Some(0.0);
800        }
801
802        // Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
803        Some(self.strategy_hwm - self.queue_total_size.get())
804    }
805
806    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollergetbyobrequest>
807    pub(crate) fn get_byob_request(
808        &self,
809        cx: &mut js::context::JSContext,
810    ) -> Fallible<Option<DomRoot<ReadableStreamBYOBRequest>>> {
811        // If controller.[[byobRequest]] is null and controller.[[pendingPullIntos]] is not empty,
812        let pending_pull_intos = self.pending_pull_intos.borrow();
813        if self.byob_request.get().is_none() && !pending_pull_intos.is_empty() {
814            // Let firstDescriptor be controller.[[pendingPullIntos]][0].
815            let first_descriptor = pending_pull_intos.first().unwrap();
816            // Let view be ! Construct(%Uint8Array%, « firstDescriptor’s buffer,
817            // firstDescriptor’s byte offset + firstDescriptor’s bytes filled,
818            // firstDescriptor’s byte length − firstDescriptor’s bytes filled »).
819
820            let byte_offset = first_descriptor.byte_offset + first_descriptor.bytes_filled.get();
821            let byte_length = first_descriptor.byte_length - first_descriptor.bytes_filled.get();
822
823            let view = create_buffer_source_with_constructor(
824                cx,
825                &Constructor::Name(Type::Uint8),
826                &first_descriptor.buffer,
827                byte_offset as usize,
828                byte_length as usize,
829            )
830            .expect("Construct Uint8Array failed");
831
832            // Let byobRequest be a new ReadableStreamBYOBRequest.
833            let byob_request = ReadableStreamBYOBRequest::new(&self.global(), CanGc::from_cx(cx));
834
835            // Set byobRequest.[[controller]] to controller.
836            byob_request.set_controller(Some(&DomRoot::from_ref(self)));
837
838            // Set byobRequest.[[view]] to view.
839            byob_request.set_view(Some(view));
840
841            // Set controller.[[byobRequest]] to byobRequest.
842            self.byob_request.set(Some(&byob_request));
843        }
844
845        // Return controller.[[byobRequest]].
846        Ok(self.byob_request.get())
847    }
848
849    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-close>
850    pub(crate) fn close(&self, cx: &mut JSContext) -> Fallible<()> {
851        // Let stream be controller.[[stream]].
852        let stream = self.stream.get().unwrap();
853
854        // If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
855        if self.close_requested.get() || !stream.is_readable() {
856            return Ok(());
857        }
858
859        // If controller.[[queueTotalSize]] > 0,
860        if self.queue_total_size.get() > 0.0 {
861            // Set controller.[[closeRequested]] to true.
862            self.close_requested.set(true);
863            // Return.
864            return Ok(());
865        }
866
867        // If controller.[[pendingPullIntos]] is not empty,
868        let pending_pull_intos = self.pending_pull_intos.borrow();
869        if !pending_pull_intos.is_empty() {
870            // Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
871            let first_pending_pull_into = pending_pull_intos.first().unwrap();
872
873            // If the remainder after dividing firstPendingPullInto’s bytes filled by
874            // firstPendingPullInto’s element size is not 0,
875            if !first_pending_pull_into
876                .bytes_filled
877                .get()
878                .is_multiple_of(first_pending_pull_into.element_size)
879            {
880                // needed to drop the borrow and avoid BorrowMutError
881                drop(pending_pull_intos);
882
883                // Let e be a new TypeError exception.
884                let e = Error::Type(
885                    c"remainder after dividing firstPendingPullInto's bytes
886                    filled by firstPendingPullInto's element size is not 0"
887                        .to_owned(),
888                );
889
890                // Perform ! ReadableByteStreamControllerError(controller, e).
891                rooted!(&in(cx) let mut error = UndefinedValue());
892                e.clone().to_jsval(
893                    cx.into(),
894                    &self.global(),
895                    error.handle_mut(),
896                    CanGc::from_cx(cx),
897                );
898                self.error(cx, error.handle());
899
900                // Throw e.
901                return Err(e);
902            }
903        }
904
905        // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
906        self.clear_algorithms();
907
908        // Perform ! ReadableStreamClose(stream).
909        stream.close(cx);
910        Ok(())
911    }
912
913    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-error>
914    pub(crate) fn error(&self, cx: &mut JSContext, e: SafeHandleValue) {
915        // Let stream be controller.[[stream]].
916        let stream = self.stream.get().unwrap();
917
918        // If stream.[[state]] is not "readable", return.
919        if !stream.is_readable() {
920            return;
921        }
922
923        // Perform ! ReadableByteStreamControllerClearPendingPullIntos(controller).
924        self.clear_pending_pull_intos();
925
926        // Perform ! ResetQueue(controller).
927        self.reset_queue();
928
929        // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
930        self.clear_algorithms();
931
932        // Perform ! ReadableStreamError(stream, e).
933        stream.error(cx, e);
934    }
935
936    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-algorithms>
937    fn clear_algorithms(&self) {
938        // Set controller.[[pullAlgorithm]] to undefined.
939        // Set controller.[[cancelAlgorithm]] to undefined.
940        self.underlying_source.set(None);
941    }
942
943    /// <https://streams.spec.whatwg.org/#reset-queue>
944    pub(crate) fn reset_queue(&self) {
945        // Assert: container has [[queue]] and [[queueTotalSize]] internal slots.
946
947        // Set container.[[queue]] to a new empty list.
948        self.queue.borrow_mut().clear();
949
950        // Set container.[[queueTotalSize]] to 0.
951        self.queue_total_size.set(0.0);
952    }
953
954    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-clear-pending-pull-intos>
955    pub(crate) fn clear_pending_pull_intos(&self) {
956        // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
957        self.invalidate_byob_request();
958
959        // Set controller.[[pendingPullIntos]] to a new empty list.
960        self.pending_pull_intos.borrow_mut().clear();
961    }
962
963    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-invalidate-byob-request>
964    pub(crate) fn invalidate_byob_request(&self) {
965        if let Some(byob_request) = self.byob_request.get() {
966            // Set controller.[[byobRequest]].[[controller]] to undefined.
967            byob_request.set_controller(None);
968
969            // Set controller.[[byobRequest]].[[view]] to null.
970            byob_request.set_view(None);
971
972            // Set controller.[[byobRequest]] to null.
973            self.byob_request.set(None);
974        }
975        // If controller.[[byobRequest]] is null, return.
976    }
977
978    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue>
979    pub(crate) fn enqueue(
980        &self,
981        cx: &mut JSContext,
982        chunk: RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>,
983    ) -> Fallible<()> {
984        // Let stream be controller.[[stream]].
985        let stream = self.stream.get().unwrap();
986
987        // If controller.[[closeRequested]] is true or stream.[[state]] is not "readable", return.
988        if self.close_requested.get() || !stream.is_readable() {
989            return Ok(());
990        }
991
992        // Let buffer be chunk.[[ViewedArrayBuffer]].
993        let buffer = chunk.get_array_buffer_view_buffer(cx.into());
994
995        // Let byteOffset be chunk.[[ByteOffset]].
996        let byte_offset = chunk.get_byte_offset();
997
998        // Let byteLength be chunk.[[ByteLength]].
999        let byte_length = chunk.byte_length();
1000
1001        // If ! IsDetachedBuffer(buffer) is true, throw a TypeError exception.
1002        if buffer.is_detached_buffer(cx.into()) {
1003            return Err(Error::Type(c"buffer is detached".to_owned()));
1004        }
1005
1006        // Let transferredBuffer be ? TransferArrayBuffer(buffer).
1007        let transferred_buffer = buffer.transfer_array_buffer(cx.into())?;
1008
1009        // If controller.[[pendingPullIntos]] is not empty,
1010        {
1011            let mut pending_pull_intos = self.pending_pull_intos.borrow_mut();
1012            if !pending_pull_intos.is_empty() {
1013                // Let firstPendingPullInto be controller.[[pendingPullIntos]][0].
1014                let first_descriptor = pending_pull_intos.first_mut().unwrap();
1015                // If ! IsDetachedBuffer(firstPendingPullInto’s buffer) is true, throw a TypeError exception.
1016                if first_descriptor.buffer.is_detached_buffer(cx.into()) {
1017                    return Err(Error::Type(c"buffer is detached".to_owned()));
1018                }
1019
1020                // Perform ! ReadableByteStreamControllerInvalidateBYOBRequest(controller).
1021                self.invalidate_byob_request();
1022
1023                // Set firstPendingPullInto’s buffer to ! TransferArrayBuffer(firstPendingPullInto’s buffer).
1024                first_descriptor.buffer = *first_descriptor
1025                    .buffer
1026                    .transfer_array_buffer(cx.into())
1027                    .expect("TransferArrayBuffer failed")
1028                    .into_box();
1029
1030                // If firstPendingPullInto’s reader type is "none",
1031                if first_descriptor.reader_type.is_none() {
1032                    // needed to drop the borrow and avoid BorrowMutError
1033                    drop(pending_pull_intos);
1034
1035                    // perform ? ReadableByteStreamControllerEnqueueDetachedPullIntoToQueue(
1036                    // controller, firstPendingPullInto).
1037                    self.enqueue_detached_pull_into_to_queue(cx)?;
1038                }
1039            }
1040        }
1041
1042        // If ! ReadableStreamHasDefaultReader(stream) is true,
1043        if stream.has_default_reader() {
1044            // Perform ! ReadableByteStreamControllerProcessReadRequestsUsingQueue(controller).
1045            self.process_read_requests_using_queue(cx)
1046                .expect("process_read_requests_using_queue failed");
1047
1048            // If ! ReadableStreamGetNumReadRequests(stream) is 0,
1049            if stream.get_num_read_requests() == 0 {
1050                // Assert: controller.[[pendingPullIntos]] is empty.
1051                {
1052                    assert!(self.pending_pull_intos.borrow().is_empty());
1053                }
1054
1055                // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(
1056                // controller, transferredBuffer, byteOffset, byteLength).
1057                self.enqueue_chunk_to_queue(transferred_buffer, byte_offset, byte_length);
1058            } else {
1059                // Assert: controller.[[queue]] is empty.
1060                assert!(self.queue.borrow().is_empty());
1061
1062                // If controller.[[pendingPullIntos]] is not empty,
1063
1064                let pending_pull_intos = self.pending_pull_intos.borrow();
1065                if !pending_pull_intos.is_empty() {
1066                    // Assert: controller.[[pendingPullIntos]][0]'s reader type is "default".
1067                    assert!(matches!(
1068                        pending_pull_intos.first().unwrap().reader_type,
1069                        Some(ReaderType::Default)
1070                    ));
1071
1072                    // needed to drop the borrow and avoid BorrowMutError
1073                    drop(pending_pull_intos);
1074
1075                    // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1076                    self.shift_pending_pull_into();
1077                }
1078
1079                // Let transferredView be ! Construct(%Uint8Array%, « transferredBuffer, byteOffset, byteLength »).
1080                let transferred_view = create_buffer_source_with_constructor(
1081                    cx,
1082                    &Constructor::Name(Type::Uint8),
1083                    &transferred_buffer,
1084                    byte_offset,
1085                    byte_length,
1086                )
1087                .expect("Construct Uint8Array failed");
1088
1089                // Perform ! ReadableStreamFulfillReadRequest(stream, transferredView, false).
1090                rooted!(&in(cx) let mut view_value = UndefinedValue());
1091                transferred_view.get_buffer_view_value(cx.into(), view_value.handle_mut());
1092                stream.fulfill_read_request(cx, view_value.handle(), false);
1093            }
1094            // Otherwise, if ! ReadableStreamHasBYOBReader(stream) is true,
1095        } else if stream.has_byob_reader() {
1096            // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue(
1097            // controller, transferredBuffer, byteOffset, byteLength).
1098            self.enqueue_chunk_to_queue(transferred_buffer, byte_offset, byte_length);
1099
1100            // Let filledPullIntos be the result of performing !
1101            // ReadableByteStreamControllerProcessPullIntoDescriptorsUsingQueue(controller).
1102            rooted!(&in(cx) let filled_pull_intos = self.process_pull_into_descriptors_using_queue(cx));
1103
1104            // For each filledPullInto of filledPullIntos,
1105            // Perform ! ReadableByteStreamControllerCommitPullIntoDescriptor(stream, filledPullInto).
1106            for filled_pull_into in &*filled_pull_intos {
1107                self.commit_pull_into_descriptor(cx, filled_pull_into)
1108                    .expect("commit_pull_into_descriptor failed");
1109            }
1110        } else {
1111            // Assert: ! IsReadableStreamLocked(stream) is false.
1112            assert!(!stream.is_locked());
1113
1114            // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue
1115            // (controller, transferredBuffer, byteOffset, byteLength).
1116            self.enqueue_chunk_to_queue(transferred_buffer, byte_offset, byte_length);
1117        }
1118
1119        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
1120        self.call_pull_if_needed(cx);
1121
1122        Ok(())
1123    }
1124
1125    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-commit-pull-into-descriptor>
1126    fn commit_pull_into_descriptor(
1127        &self,
1128        cx: &mut JSContext,
1129        pull_into_descriptor: &PullIntoDescriptor,
1130    ) -> Fallible<()> {
1131        // Assert: stream.[[state]] is not "errored".
1132        let stream = self.stream.get().unwrap();
1133        assert!(!stream.is_errored());
1134
1135        // Assert: pullIntoDescriptor.reader type is not "none".
1136        assert!(pull_into_descriptor.reader_type.is_some());
1137
1138        // Let done be false.
1139        let mut done = false;
1140
1141        // If stream.[[state]] is "closed",
1142        if stream.is_closed() {
1143            // Assert: the remainder after dividing pullIntoDescriptor’s bytes filled
1144            // by pullIntoDescriptor’s element size is 0.
1145            assert!(
1146                pull_into_descriptor
1147                    .bytes_filled
1148                    .get()
1149                    .is_multiple_of(pull_into_descriptor.element_size)
1150            );
1151
1152            // Set done to true.
1153            done = true;
1154        }
1155
1156        // Let filledView be ! ReadableByteStreamControllerConvertPullIntoDescriptor(pullIntoDescriptor).
1157        let filled_view = self
1158            .convert_pull_into_descriptor(cx, pull_into_descriptor)
1159            .expect("convert_pull_into_descriptor failed");
1160
1161        rooted!(&in(cx) let mut view_value = UndefinedValue());
1162        filled_view.get_buffer_view_value(cx.into(), view_value.handle_mut());
1163
1164        // If pullIntoDescriptor’s reader type is "default",
1165        if matches!(pull_into_descriptor.reader_type, Some(ReaderType::Default)) {
1166            // Perform ! ReadableStreamFulfillReadRequest(stream, filledView, done).
1167
1168            stream.fulfill_read_request(cx, view_value.handle(), done);
1169        } else {
1170            // Assert: pullIntoDescriptor’s reader type is "byob".
1171            assert!(matches!(
1172                pull_into_descriptor.reader_type,
1173                Some(ReaderType::Byob)
1174            ));
1175
1176            // Perform ! ReadableStreamFulfillReadIntoRequest(stream, filledView, done).
1177            stream.fulfill_read_into_request(cx, view_value.handle(), done);
1178        }
1179        Ok(())
1180    }
1181
1182    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-convert-pull-into-descriptor>
1183    pub(crate) fn convert_pull_into_descriptor(
1184        &self,
1185        cx: &mut js::context::JSContext,
1186        pull_into_descriptor: &PullIntoDescriptor,
1187    ) -> Fallible<RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>> {
1188        // Let bytesFilled be pullIntoDescriptor’s bytes filled.
1189        let bytes_filled = pull_into_descriptor.bytes_filled.get();
1190
1191        // Let elementSize be pullIntoDescriptor’s element size.
1192        let element_size = pull_into_descriptor.element_size;
1193
1194        // Assert: bytesFilled ≤ pullIntoDescriptor’s byte length.
1195        assert!(bytes_filled <= pull_into_descriptor.byte_length);
1196
1197        // Assert: the remainder after dividing bytesFilled by elementSize is 0.
1198        assert!(bytes_filled.is_multiple_of(element_size));
1199
1200        // Let buffer be ! TransferArrayBuffer(pullIntoDescriptor’s buffer).
1201        let buffer = pull_into_descriptor
1202            .buffer
1203            .transfer_array_buffer(cx.into())
1204            .expect("TransferArrayBuffer failed");
1205
1206        // Return ! Construct(pullIntoDescriptor’s view constructor,
1207        // « buffer, pullIntoDescriptor’s byte offset, bytesFilled ÷ elementSize »).
1208        Ok(create_buffer_source_with_constructor(
1209            cx,
1210            &pull_into_descriptor.view_constructor,
1211            &buffer,
1212            pull_into_descriptor.byte_offset as usize,
1213            (bytes_filled / element_size) as usize,
1214        )
1215        .expect("Construct view failed"))
1216    }
1217
1218    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-process-pull-into-descriptors-using-queue>
1219    pub(crate) fn process_pull_into_descriptors_using_queue(
1220        &self,
1221        cx: &mut js::context::JSContext,
1222    ) -> Vec<PullIntoDescriptor> {
1223        // Assert: controller.[[closeRequested]] is false.
1224        assert!(!self.close_requested.get());
1225
1226        // Let filledPullIntos be a new empty list.
1227        rooted!(&in(cx) let mut filled_pull_intos = Vec::new());
1228
1229        // While controller.[[pendingPullIntos]] is not empty,
1230        loop {
1231            // If controller.[[queueTotalSize]] is 0, then break.
1232            if self.queue_total_size.get() == 0.0 {
1233                break;
1234            }
1235
1236            // Let pullIntoDescriptor be controller.[[pendingPullIntos]][0].
1237            let fill_pull_result = {
1238                let pending_pull_intos = self.pending_pull_intos.borrow();
1239                let Some(pull_into_descriptor) = pending_pull_intos.first() else {
1240                    break;
1241                };
1242                self.fill_pull_into_descriptor_from_queue(cx, pull_into_descriptor)
1243            };
1244
1245            // If ! ReadableByteStreamControllerFillPullIntoDescriptorFromQueue(controller, pullIntoDescriptor) is true,
1246            if fill_pull_result {
1247                // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1248                // Append pullIntoDescriptor to filledPullIntos.
1249                filled_pull_intos.push(self.shift_pending_pull_into());
1250            }
1251        }
1252
1253        // Return filledPullIntos.
1254        filled_pull_intos.take()
1255    }
1256
1257    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-pull-into-descriptor-from-queue>
1258    pub(crate) fn fill_pull_into_descriptor_from_queue(
1259        &self,
1260        cx: &mut js::context::JSContext,
1261        pull_into_descriptor: &PullIntoDescriptor,
1262    ) -> bool {
1263        // Let maxBytesToCopy be min(controller.[[queueTotalSize]],
1264        // pullIntoDescriptor’s byte length − pullIntoDescriptor’s bytes filled).
1265        let max_bytes_to_copy = min(
1266            self.queue_total_size.get() as usize,
1267            (pull_into_descriptor.byte_length - pull_into_descriptor.bytes_filled.get()) as usize,
1268        );
1269
1270        // Let maxBytesFilled be pullIntoDescriptor’s bytes filled + maxBytesToCopy.
1271        let max_bytes_filled = pull_into_descriptor.bytes_filled.get() as usize + max_bytes_to_copy;
1272
1273        // Let totalBytesToCopyRemaining be maxBytesToCopy.
1274        let mut total_bytes_to_copy_remaining = max_bytes_to_copy;
1275
1276        // Let ready be false.
1277        let mut ready = false;
1278
1279        // Assert: ! IsDetachedBuffer(pullIntoDescriptor’s buffer) is false.
1280        assert!(!pull_into_descriptor.buffer.is_detached_buffer(cx.into()));
1281
1282        // Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.
1283        assert!(pull_into_descriptor.bytes_filled.get() < pull_into_descriptor.minimum_fill);
1284
1285        // Let remainderBytes be the remainder after dividing maxBytesFilled by pullIntoDescriptor’s element size.
1286        let remainder_bytes = max_bytes_filled % pull_into_descriptor.element_size as usize;
1287
1288        // Let maxAlignedBytes be maxBytesFilled − remainderBytes.
1289        let max_aligned_bytes = max_bytes_filled - remainder_bytes;
1290
1291        // If maxAlignedBytes ≥ pullIntoDescriptor’s minimum fill,
1292        if max_aligned_bytes >= pull_into_descriptor.minimum_fill as usize {
1293            // Set totalBytesToCopyRemaining to maxAlignedBytes − pullIntoDescriptor’s bytes filled.
1294            total_bytes_to_copy_remaining =
1295                max_aligned_bytes - (pull_into_descriptor.bytes_filled.get() as usize);
1296
1297            // Set ready to true.
1298            ready = true;
1299        }
1300
1301        // Let queue be controller.[[queue]].
1302        let mut queue = self.queue.borrow_mut();
1303
1304        // While totalBytesToCopyRemaining > 0,
1305        while total_bytes_to_copy_remaining > 0 {
1306            // Let headOfQueue be queue[0].
1307            let head_of_queue = queue.front_mut().unwrap();
1308
1309            // Let bytesToCopy be min(totalBytesToCopyRemaining, headOfQueue’s byte length).
1310            let bytes_to_copy = total_bytes_to_copy_remaining.min(head_of_queue.byte_length);
1311
1312            // Let destStart be pullIntoDescriptor’s byte offset + pullIntoDescriptor’s bytes filled.
1313            let dest_start =
1314                pull_into_descriptor.byte_offset + pull_into_descriptor.bytes_filled.get();
1315
1316            // Let descriptorBuffer be pullIntoDescriptor’s buffer.
1317            let descriptor_buffer = &pull_into_descriptor.buffer;
1318
1319            // Let queueBuffer be headOfQueue’s buffer.
1320            let queue_buffer = &head_of_queue.buffer;
1321
1322            // Let queueByteOffset be headOfQueue’s byte offset.
1323            let queue_byte_offset = head_of_queue.byte_offset;
1324
1325            // Assert: ! CanCopyDataBlockBytes(descriptorBuffer, destStart,
1326            // queueBuffer, queueByteOffset, bytesToCopy) is true.
1327            assert!(descriptor_buffer.can_copy_data_block_bytes(
1328                cx.into(),
1329                dest_start as usize,
1330                queue_buffer,
1331                queue_byte_offset,
1332                bytes_to_copy
1333            ));
1334
1335            // Perform ! CopyDataBlockBytes(descriptorBuffer.[[ArrayBufferData]], destStart,
1336            // queueBuffer.[[ArrayBufferData]], queueByteOffset, bytesToCopy).
1337            descriptor_buffer.copy_data_block_bytes(
1338                cx.into(),
1339                dest_start as usize,
1340                queue_buffer,
1341                queue_byte_offset,
1342                bytes_to_copy,
1343            );
1344
1345            // If headOfQueue’s byte length is bytesToCopy,
1346            if head_of_queue.byte_length == bytes_to_copy {
1347                // Remove queue[0].
1348                queue.pop_front().unwrap();
1349            } else {
1350                // Set headOfQueue’s byte offset to headOfQueue’s byte offset + bytesToCopy.
1351                head_of_queue.byte_offset += bytes_to_copy;
1352
1353                // Set headOfQueue’s byte length to headOfQueue’s byte length − bytesToCopy.
1354                head_of_queue.byte_length -= bytes_to_copy;
1355            }
1356
1357            // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − bytesToCopy.
1358            self.queue_total_size
1359                .set(self.queue_total_size.get() - (bytes_to_copy as f64));
1360
1361            // Perform ! ReadableByteStreamControllerFillHeadPullIntoDescriptor(
1362            // controller, bytesToCopy, pullIntoDescriptor).
1363            self.fill_head_pull_into_descriptor(bytes_to_copy as u64, pull_into_descriptor);
1364
1365            // Set totalBytesToCopyRemaining to totalBytesToCopyRemaining − bytesToCopy.
1366            total_bytes_to_copy_remaining -= bytes_to_copy;
1367        }
1368
1369        // If ready is false,
1370        if !ready {
1371            // Assert: controller.[[queueTotalSize]] is 0.
1372            assert!(self.queue_total_size.get() == 0.0);
1373
1374            // Assert: pullIntoDescriptor’s bytes filled > 0.
1375            assert!(pull_into_descriptor.bytes_filled.get() > 0);
1376
1377            // Assert: pullIntoDescriptor’s bytes filled < pullIntoDescriptor’s minimum fill.
1378            assert!(pull_into_descriptor.bytes_filled.get() < pull_into_descriptor.minimum_fill);
1379        }
1380
1381        // Return ready.
1382        ready
1383    }
1384
1385    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-fill-head-pull-into-descriptor>
1386    pub(crate) fn fill_head_pull_into_descriptor(
1387        &self,
1388        bytes_copied: u64,
1389        pull_into_descriptor: &PullIntoDescriptor,
1390    ) {
1391        // Assert: either controller.[[pendingPullIntos]] is empty,
1392        // or controller.[[pendingPullIntos]][0] is pullIntoDescriptor.
1393        {
1394            let pending_pull_intos = self.pending_pull_intos.borrow();
1395            assert!(
1396                pending_pull_intos.is_empty() ||
1397                    pending_pull_intos.first().unwrap() == pull_into_descriptor
1398            );
1399        }
1400
1401        // Assert: controller.[[byobRequest]] is null.
1402        assert!(self.byob_request.get().is_none());
1403
1404        // Set pullIntoDescriptor’s bytes filled to bytes filled + size.
1405        pull_into_descriptor
1406            .bytes_filled
1407            .set(pull_into_descriptor.bytes_filled.get() + bytes_copied);
1408    }
1409
1410    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueuedetachedpullintotoqueue>
1411    pub(crate) fn enqueue_detached_pull_into_to_queue(&self, cx: &mut JSContext) -> Fallible<()> {
1412        // first_descriptor: &PullIntoDescriptor,
1413        let pending_pull_intos = self.pending_pull_intos.borrow();
1414        let first_descriptor = pending_pull_intos.first().unwrap();
1415
1416        // Assert: pullIntoDescriptor’s reader type is "none".
1417        assert!(first_descriptor.reader_type.is_none());
1418
1419        // If pullIntoDescriptor’s bytes filled > 0, perform ?
1420        // ReadableByteStreamControllerEnqueueClonedChunkToQueue(controller,
1421        // pullIntoDescriptor’s buffer, pullIntoDescriptor’s byte offset, pullIntoDescriptor’s bytes filled).
1422
1423        if first_descriptor.bytes_filled.get() > 0 {
1424            self.enqueue_cloned_chunk_to_queue(
1425                cx,
1426                &first_descriptor.buffer,
1427                first_descriptor.byte_offset,
1428                first_descriptor.bytes_filled.get(),
1429            )?;
1430        }
1431
1432        // needed to drop the borrow and avoid BorrowMutError
1433        drop(pending_pull_intos);
1434
1435        // Perform ! ReadableByteStreamControllerShiftPendingPullInto(controller).
1436        self.shift_pending_pull_into();
1437
1438        Ok(())
1439    }
1440
1441    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerenqueueclonedchunktoqueue>
1442    pub(crate) fn enqueue_cloned_chunk_to_queue(
1443        &self,
1444        cx: &mut JSContext,
1445        buffer: &HeapBufferSource<ArrayBufferU8>,
1446        byte_offset: u64,
1447        byte_length: u64,
1448    ) -> Fallible<()> {
1449        // Let cloneResult be CloneArrayBuffer(buffer, byteOffset, byteLength, %ArrayBuffer%).
1450        if let Ok(clone_result) =
1451            buffer.clone_array_buffer(cx, byte_offset as usize, byte_length as usize)
1452        {
1453            // Perform ! ReadableByteStreamControllerEnqueueChunkToQueue
1454            // (controller, cloneResult.[[Value]], 0, byteLength).
1455            self.enqueue_chunk_to_queue(clone_result, 0, byte_length as usize);
1456
1457            Ok(())
1458        } else {
1459            // If cloneResult is an abrupt completion,
1460
1461            // Perform ! ReadableByteStreamControllerError(controller, cloneResult.[[Value]]).
1462            rooted!(&in(cx) let mut rval = UndefinedValue());
1463            let error = Error::Type(c"can not clone array buffer".to_owned());
1464            error.clone().to_jsval(
1465                cx.into(),
1466                &self.global(),
1467                rval.handle_mut(),
1468                CanGc::from_cx(cx),
1469            );
1470            self.error(cx, rval.handle());
1471
1472            // Return cloneResult.
1473            Err(error)
1474        }
1475    }
1476
1477    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-enqueue-chunk-to-queue>
1478    pub(crate) fn enqueue_chunk_to_queue(
1479        &self,
1480        buffer: RootedTraceableBox<HeapBufferSource<ArrayBufferU8>>,
1481        byte_offset: usize,
1482        byte_length: usize,
1483    ) {
1484        // Let entry be a new ReadableByteStreamQueueEntry object.
1485        // Append entry to controller.[[queue]].
1486        self.queue
1487            .borrow_mut()
1488            .push_back(QueueEntry::new(buffer, byte_offset, byte_length));
1489
1490        // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] + byteLength.
1491        self.queue_total_size
1492            .set(self.queue_total_size.get() + byte_length as f64);
1493    }
1494
1495    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-shift-pending-pull-into>
1496    pub(crate) fn shift_pending_pull_into(&self) -> PullIntoDescriptor {
1497        // Assert: controller.[[byobRequest]] is null.
1498        assert!(self.byob_request.get().is_none());
1499
1500        // Let descriptor be controller.[[pendingPullIntos]][0].
1501        // Remove descriptor from controller.[[pendingPullIntos]].
1502        // Return descriptor.
1503        self.pending_pull_intos.borrow_mut().remove(0)
1504    }
1505
1506    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerprocessreadrequestsusingqueue>
1507    pub(crate) fn process_read_requests_using_queue(&self, cx: &mut JSContext) -> Fallible<()> {
1508        // Let reader be controller.[[stream]].[[reader]].
1509        // Assert: reader implements ReadableStreamDefaultReader.
1510        let reader = self.stream.get().unwrap().get_default_reader();
1511
1512        // Step 3
1513        reader.process_read_requests(cx, DomRoot::from_ref(self))
1514    }
1515
1516    /// <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontrollerfillreadrequestfromqueue>
1517    pub(crate) fn fill_read_request_from_queue(
1518        &self,
1519        cx: &mut JSContext,
1520        read_request: &ReadRequest,
1521    ) -> Fallible<()> {
1522        // Assert: controller.[[queueTotalSize]] > 0.
1523        assert!(self.queue_total_size.get() > 0.0);
1524        // Also assert that the queue has a non-zero length;
1525        assert!(!self.queue.borrow().is_empty());
1526
1527        // Let entry be controller.[[queue]][0].
1528        // Remove entry from controller.[[queue]].
1529        rooted!(&in(cx) let entry = self.remove_entry());
1530
1531        // Set controller.[[queueTotalSize]] to controller.[[queueTotalSize]] − entry’s byte length.
1532        self.queue_total_size
1533            .set(self.queue_total_size.get() - entry.byte_length as f64);
1534
1535        // Perform ! ReadableByteStreamControllerHandleQueueDrain(controller).
1536        self.handle_queue_drain(cx);
1537
1538        // Let view be ! Construct(%Uint8Array%, « entry’s buffer, entry’s byte offset, entry’s byte length »).
1539        let view = create_buffer_source_with_constructor(
1540            cx,
1541            &Constructor::Name(Type::Uint8),
1542            &entry.buffer,
1543            entry.byte_offset,
1544            entry.byte_length,
1545        )
1546        .expect("Construct Uint8Array failed");
1547
1548        // Perform readRequest’s chunk steps, given view.
1549        let result = RootedTraceableBox::new(Heap::default());
1550        rooted!(&in(cx) let mut view_value = UndefinedValue());
1551        view.get_buffer_view_value(cx.into(), view_value.handle_mut());
1552        result.set(*view_value);
1553
1554        read_request.chunk_steps(cx, result, &self.global());
1555
1556        Ok(())
1557    }
1558
1559    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-handle-queue-drain>
1560    pub(crate) fn handle_queue_drain(&self, cx: &mut JSContext) {
1561        // Assert: controller.[[stream]].[[state]] is "readable".
1562        assert!(self.stream.get().unwrap().is_readable());
1563
1564        // If controller.[[queueTotalSize]] is 0 and controller.[[closeRequested]] is true,
1565        if self.queue_total_size.get() == 0.0 && self.close_requested.get() {
1566            // Perform ! ReadableByteStreamControllerClearAlgorithms(controller).
1567            self.clear_algorithms();
1568
1569            // Perform ! ReadableStreamClose(controller.[[stream]]).
1570            self.stream.get().unwrap().close(cx);
1571        } else {
1572            // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
1573            self.call_pull_if_needed(cx);
1574        }
1575    }
1576
1577    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-call-pull-if-needed>
1578    fn call_pull_if_needed(&self, cx: &mut JSContext) {
1579        // Let shouldPull be ! ReadableByteStreamControllerShouldCallPull(controller).
1580        let should_pull = self.should_call_pull();
1581        // If shouldPull is false, return.
1582        if !should_pull {
1583            return;
1584        }
1585
1586        // If controller.[[pulling]] is true,
1587        if self.pulling.get() {
1588            // Set controller.[[pullAgain]] to true.
1589            self.pull_again.set(true);
1590
1591            // Return.
1592            return;
1593        }
1594
1595        // Assert: controller.[[pullAgain]] is false.
1596        assert!(!self.pull_again.get());
1597
1598        // Set controller.[[pulling]] to true.
1599        self.pulling.set(true);
1600
1601        // Let pullPromise be the result of performing controller.[[pullAlgorithm]].
1602        // Continues into the resolve and reject handling of the native handler.
1603        let global = self.global();
1604        let rooted_controller = DomRoot::from_ref(self);
1605        let controller = Controller::ReadableByteStreamController(rooted_controller.clone());
1606
1607        if let Some(underlying_source) = self.underlying_source.get() {
1608            let handler = PromiseNativeHandler::new(
1609                &global,
1610                Some(Box::new(PullAlgorithmFulfillmentHandler {
1611                    controller: Dom::from_ref(&rooted_controller),
1612                })),
1613                Some(Box::new(PullAlgorithmRejectionHandler {
1614                    controller: Dom::from_ref(&rooted_controller),
1615                })),
1616                CanGc::from_cx(cx),
1617            );
1618
1619            let mut realm = enter_auto_realm(cx, &*global);
1620            let cx = &mut realm.current_realm();
1621
1622            let result = underlying_source
1623                .call_pull_algorithm(cx, controller)
1624                .unwrap_or_else(|| {
1625                    let promise = Promise::new_resolved(&global, cx.into(), (), CanGc::from_cx(cx));
1626                    Ok(promise)
1627                });
1628            let promise = result.unwrap_or_else(|error| {
1629                rooted!(&in(cx) let mut rval = UndefinedValue());
1630                // TODO: check if `self.global()` is the right globalscope.
1631                error.to_jsval(cx.into(), &global, rval.handle_mut(), CanGc::from_cx(cx));
1632                Promise::new_rejected(&global, cx.into(), rval.handle(), CanGc::from_cx(cx))
1633            });
1634            promise.append_native_handler(cx, &handler);
1635        }
1636    }
1637
1638    /// <https://streams.spec.whatwg.org/#readable-byte-stream-controller-should-call-pull>
1639    fn should_call_pull(&self) -> bool {
1640        // Let stream be controller.[[stream]].
1641        // Note: the spec does not assert that stream is not undefined here,
1642        // so we return false if it is.
1643        let stream = self.stream.get().unwrap();
1644
1645        // If stream.[[state]] is not "readable", return false.
1646        if !stream.is_readable() {
1647            return false;
1648        }
1649
1650        // If controller.[[closeRequested]] is true, return false.
1651        if self.close_requested.get() {
1652            return false;
1653        }
1654
1655        // If controller.[[started]] is false, return false.
1656        if !self.started.get() {
1657            return false;
1658        }
1659
1660        // If ! ReadableStreamHasDefaultReader(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0
1661        // , return true.
1662        if stream.has_default_reader() && stream.get_num_read_requests() > 0 {
1663            return true;
1664        }
1665
1666        // If ! ReadableStreamHasBYOBReader(stream) is true and ! ReadableStreamGetNumReadIntoRequests(stream) > 0
1667        // , return true.
1668        if stream.has_byob_reader() && stream.get_num_read_into_requests() > 0 {
1669            return true;
1670        }
1671
1672        // Let desiredSize be ! ReadableByteStreamControllerGetDesiredSize(controller).
1673        let desired_size = self.get_desired_size();
1674
1675        // Assert: desiredSize is not null.
1676        assert!(desired_size.is_some());
1677
1678        // If desiredSize > 0, return true.
1679        if desired_size.unwrap() > 0. {
1680            return true;
1681        }
1682
1683        // Return false.
1684        false
1685    }
1686    /// <https://streams.spec.whatwg.org/#set-up-readable-byte-stream-controller>
1687    pub(crate) fn setup(
1688        &self,
1689        cx: &mut JSContext,
1690        global: &GlobalScope,
1691        stream: DomRoot<ReadableStream>,
1692    ) -> Fallible<()> {
1693        // Assert: stream.[[controller]] is undefined.
1694        stream.assert_no_controller();
1695
1696        // If autoAllocateChunkSize is not undefined,
1697        if self.auto_allocate_chunk_size.is_some() {
1698            // Assert: ! IsInteger(autoAllocateChunkSize) is true. Implicit
1699            // Assert: autoAllocateChunkSize is positive. (Implicit by type.)
1700        }
1701
1702        // Set controller.[[stream]] to stream.
1703        self.stream.set(Some(&stream));
1704
1705        // Set controller.[[pullAgain]] and controller.[[pulling]] to false.
1706        self.pull_again.set(false);
1707        self.pulling.set(false);
1708
1709        // Set controller.[[byobRequest]] to null.
1710        self.byob_request.set(None);
1711
1712        // Perform ! ResetQueue(controller).
1713        self.reset_queue();
1714
1715        // Set controller.[[closeRequested]] and controller.[[started]] to false.
1716        self.close_requested.set(false);
1717        self.started.set(false);
1718
1719        // Set controller.[[strategyHWM]] to highWaterMark.
1720        // Set controller.[[pullAlgorithm]] to pullAlgorithm.
1721        // Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
1722        // Set controller.[[autoAllocateChunkSize]] to autoAllocateChunkSize.
1723        // Set controller.[[pendingPullIntos]] to a new empty list.
1724        // Note: the above steps are done in `new`.
1725
1726        // Set stream.[[controller]] to controller.
1727        let rooted_byte_controller = DomRoot::from_ref(self);
1728        stream.set_byte_controller(&rooted_byte_controller);
1729
1730        if let Some(underlying_source) = rooted_byte_controller.underlying_source.get() {
1731            // Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
1732            let start_result = underlying_source
1733                .call_start_algorithm(
1734                    cx,
1735                    Controller::ReadableByteStreamController(rooted_byte_controller.clone()),
1736                )
1737                .unwrap_or_else(|| {
1738                    Ok(Promise::new_resolved(
1739                        global,
1740                        cx.into(),
1741                        (),
1742                        CanGc::from_cx(cx),
1743                    ))
1744                });
1745
1746            // Let startPromise be a promise resolved with startResult.
1747            let start_promise = start_result?;
1748
1749            // Upon fulfillment of startPromise, Upon rejection of startPromise with reason r,
1750            let handler = PromiseNativeHandler::new(
1751                global,
1752                Some(Box::new(StartAlgorithmFulfillmentHandler {
1753                    controller: Dom::from_ref(&rooted_byte_controller),
1754                })),
1755                Some(Box::new(StartAlgorithmRejectionHandler {
1756                    controller: Dom::from_ref(&rooted_byte_controller),
1757                })),
1758                CanGc::from_cx(cx),
1759            );
1760            let mut realm = enter_auto_realm(cx, global);
1761            let cx = &mut realm.current_realm();
1762            start_promise.append_native_handler(cx, &handler);
1763        };
1764
1765        Ok(())
1766    }
1767
1768    // <https://streams.spec.whatwg.org/#abstract-opdef-readablebytestreamcontroller-releasesteps
1769    pub(crate) fn perform_release_steps(&self) -> Fallible<()> {
1770        // If this.[[pendingPullIntos]] is not empty,
1771        let mut pending_pull_intos = self.pending_pull_intos.borrow_mut();
1772        if !pending_pull_intos.is_empty() {
1773            // Let firstPendingPullInto be this.[[pendingPullIntos]][0].
1774            let mut first_pending_pull_into = RootedTraceableBox::new(pending_pull_intos.remove(0));
1775
1776            // Set firstPendingPullInto’s reader type to "none".
1777            first_pending_pull_into.reader_type = None;
1778
1779            // Set this.[[pendingPullIntos]] to the list « firstPendingPullInto »
1780            pending_pull_intos.clear();
1781            pending_pull_intos.push(*first_pending_pull_into.into_box());
1782        }
1783        Ok(())
1784    }
1785
1786    /// <https://streams.spec.whatwg.org/#rbs-controller-private-cancel>
1787    pub(crate) fn perform_cancel_steps(
1788        &self,
1789        cx: &mut JSContext,
1790        global: &GlobalScope,
1791        reason: SafeHandleValue,
1792    ) -> Rc<Promise> {
1793        // Perform ! ReadableByteStreamControllerClearPendingPullIntos(this).
1794        self.clear_pending_pull_intos();
1795
1796        // Perform ! ResetQueue(this).
1797        self.reset_queue();
1798
1799        let underlying_source = self
1800            .underlying_source
1801            .get()
1802            .expect("Controller should have a source when the cancel steps are called into.");
1803
1804        // Let result be the result of performing this.[[cancelAlgorithm]], passing in reason.
1805        let result = underlying_source
1806            .call_cancel_algorithm(cx, global, reason)
1807            .unwrap_or_else(|| {
1808                let promise = Promise::new2(cx, global);
1809                promise.resolve_native(&(), CanGc::from_cx(cx));
1810                Ok(promise)
1811            });
1812
1813        let promise = result.unwrap_or_else(|error| {
1814            rooted!(&in(cx) let mut rval = UndefinedValue());
1815            error.to_jsval(cx.into(), global, rval.handle_mut(), CanGc::from_cx(cx));
1816            let promise = Promise::new2(cx, global);
1817            promise.reject_native(&rval.handle(), CanGc::from_cx(cx));
1818            promise
1819        });
1820
1821        // Perform ! ReadableByteStreamControllerClearAlgorithms(this).
1822        self.clear_algorithms();
1823
1824        // Return result(the promise).
1825        promise
1826    }
1827
1828    /// <https://streams.spec.whatwg.org/#rbs-controller-private-pull>
1829    pub(crate) fn perform_pull_steps(&self, cx: &mut JSContext, read_request: &ReadRequest) {
1830        // Let stream be this.[[stream]].
1831        let stream = self.stream.get().unwrap();
1832
1833        // Assert: ! ReadableStreamHasDefaultReader(stream) is true.
1834        assert!(stream.has_default_reader());
1835
1836        // If this.[[queueTotalSize]] > 0,
1837        if self.queue_total_size.get() > 0.0 {
1838            // Assert: ! ReadableStreamGetNumReadRequests(stream) is 0.
1839            assert_eq!(stream.get_num_read_requests(), 0);
1840
1841            // Perform ! ReadableByteStreamControllerFillReadRequestFromQueue(this, readRequest).
1842            let _ = self.fill_read_request_from_queue(cx, read_request);
1843
1844            // Return.
1845            return;
1846        }
1847
1848        // Let autoAllocateChunkSize be this.[[autoAllocateChunkSize]].
1849        let auto_allocate_chunk_size = self.auto_allocate_chunk_size;
1850
1851        // If autoAllocateChunkSize is not undefined,
1852        if let Some(auto_allocate_chunk_size) = auto_allocate_chunk_size {
1853            // create_array_buffer_with_size
1854            // Let buffer be Construct(%ArrayBuffer%, « autoAllocateChunkSize »).
1855            match create_array_buffer_with_size(cx, auto_allocate_chunk_size as usize) {
1856                Ok(buffer) => {
1857                    // Let pullIntoDescriptor be a new pull-into descriptor with
1858                    // buffer buffer.[[Value]]
1859                    // buffer byte length autoAllocateChunkSize
1860                    // byte offset  0
1861                    // byte length  autoAllocateChunkSize
1862                    // bytes filled  0
1863                    // minimum fill 1
1864                    // element size 1
1865                    // view constructor %Uint8Array%
1866                    // reader type  "default"
1867
1868                    // Append pullIntoDescriptor to this.[[pendingPullIntos]].
1869                    self.pending_pull_intos
1870                        .borrow_mut()
1871                        .push(PullIntoDescriptor {
1872                            buffer: *buffer.into_box(),
1873                            buffer_byte_length: auto_allocate_chunk_size,
1874                            byte_length: auto_allocate_chunk_size,
1875                            byte_offset: 0,
1876                            bytes_filled: Cell::new(0),
1877                            minimum_fill: 1,
1878                            element_size: 1,
1879                            view_constructor: Constructor::Name(Type::Uint8),
1880                            reader_type: Some(ReaderType::Default),
1881                        });
1882                },
1883                Err(error) => {
1884                    // If buffer is an abrupt completion,
1885                    // Perform readRequest’s error steps, given buffer.[[Value]].
1886
1887                    rooted!(&in(cx) let mut rval = UndefinedValue());
1888                    error.to_jsval(
1889                        cx.into(),
1890                        &self.global(),
1891                        rval.handle_mut(),
1892                        CanGc::from_cx(cx),
1893                    );
1894                    read_request.error_steps(cx, rval.handle());
1895
1896                    // Return.
1897                    return;
1898                },
1899            }
1900        }
1901
1902        // Perform ! ReadableStreamAddReadRequest(stream, readRequest).
1903        stream.add_read_request(read_request);
1904
1905        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(this).
1906        self.call_pull_if_needed(cx);
1907    }
1908
1909    /// Setting the JS object after the heap has settled down.
1910    pub(crate) fn set_underlying_source_this_object(&self, this_object: HandleObject) {
1911        if let Some(underlying_source) = self.underlying_source.get() {
1912            underlying_source.set_underlying_source_this_object(this_object);
1913        }
1914    }
1915
1916    pub(crate) fn remove_entry(&self) -> QueueEntry {
1917        self.queue
1918            .borrow_mut()
1919            .pop_front()
1920            .expect("Reader must have read request when remove is called into.")
1921    }
1922
1923    pub(crate) fn get_queue_total_size(&self) -> f64 {
1924        self.queue_total_size.get()
1925    }
1926
1927    pub(crate) fn get_pending_pull_intos_size(&self) -> usize {
1928        self.pending_pull_intos.borrow().len()
1929    }
1930}
1931
1932impl ReadableByteStreamControllerMethods<crate::DomTypeHolder> for ReadableByteStreamController {
1933    /// <https://streams.spec.whatwg.org/#rbs-controller-byob-request>
1934    fn GetByobRequest(
1935        &self,
1936        cx: &mut js::context::JSContext,
1937    ) -> Fallible<Option<DomRoot<ReadableStreamBYOBRequest>>> {
1938        // Return ! ReadableByteStreamControllerGetBYOBRequest(this).
1939        self.get_byob_request(cx)
1940    }
1941
1942    /// <https://streams.spec.whatwg.org/#rbs-controller-desired-size>
1943    fn GetDesiredSize(&self) -> Option<f64> {
1944        // Return ! ReadableByteStreamControllerGetDesiredSize(this).
1945        self.get_desired_size()
1946    }
1947
1948    /// <https://streams.spec.whatwg.org/#rbs-controller-close>
1949    fn Close(&self, cx: &mut JSContext) -> Fallible<()> {
1950        // If this.[[closeRequested]] is true, throw a TypeError exception.
1951        if self.close_requested.get() {
1952            return Err(Error::Type(c"closeRequested is true".to_owned()));
1953        }
1954
1955        // If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.
1956        if !self.stream.get().unwrap().is_readable() {
1957            return Err(Error::Type(c"stream is not readable".to_owned()));
1958        }
1959
1960        // Perform ? ReadableByteStreamControllerClose(this).
1961        self.close(cx)
1962    }
1963
1964    /// <https://streams.spec.whatwg.org/#rbs-controller-enqueue>
1965    fn Enqueue(
1966        &self,
1967        cx: &mut JSContext,
1968        chunk: js::gc::CustomAutoRooterGuard<js::typedarray::ArrayBufferView>,
1969    ) -> Fallible<()> {
1970        let chunk = HeapBufferSource::<ArrayBufferViewU8>::from_view(chunk);
1971
1972        // If chunk.[[ByteLength]] is 0, throw a TypeError exception.
1973        if chunk.byte_length() == 0 {
1974            return Err(Error::Type(c"chunk.ByteLength is 0".to_owned()));
1975        }
1976
1977        // If chunk.[[ViewedArrayBuffer]].[[ByteLength]] is 0, throw a TypeError exception.
1978        if chunk.viewed_buffer_array_byte_length(cx.into()) == 0 {
1979            return Err(Error::Type(
1980                c"chunk.ViewedArrayBuffer.ByteLength is 0".to_owned(),
1981            ));
1982        }
1983
1984        // If this.[[closeRequested]] is true, throw a TypeError exception.
1985        if self.close_requested.get() {
1986            return Err(Error::Type(c"closeRequested is true".to_owned()));
1987        }
1988
1989        // If this.[[stream]].[[state]] is not "readable", throw a TypeError exception.
1990        if !self.stream.get().unwrap().is_readable() {
1991            return Err(Error::Type(c"stream is not readable".to_owned()));
1992        }
1993
1994        // Return ? ReadableByteStreamControllerEnqueue(this, chunk).
1995        self.enqueue(cx, chunk)
1996    }
1997
1998    /// <https://streams.spec.whatwg.org/#rbs-controller-error>
1999    fn Error(&self, cx: &mut JSContext, e: SafeHandleValue) -> Fallible<()> {
2000        // Perform ! ReadableByteStreamControllerError(this, e).
2001        self.error(cx, e);
2002        Ok(())
2003    }
2004}