Skip to main content

quickjs_jit_stdlib/llrt/llrt_stream_web/readable/
default_controller.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_stream_web/src/readable/default_controller.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3use crate::utils::option::{Null, Undefined};
4use rquickjs::{
5    class::{OwnedBorrow, OwnedBorrowMut, Trace},
6    methods,
7    prelude::{Opt, This},
8    Class, Ctx, Error, Exception, JsLifetime, Object, Promise, Result, Value,
9};
10use std::{future, pin::Pin, rc::Rc};
11
12/// Native async pull: returns Ok(Some(chunk)) or Ok(None) for EOF.
13/// Result of a native pull: data ready, EOF, or need async.
14pub enum NativePullResult<'js> {
15    /// Data chunk ready synchronously
16    Ready(Value<'js>),
17    /// EOF — no more data
18    Eof,
19    /// Need async — returns a future for the pending case
20    Pending(Pin<Box<dyn future::Future<Output = Result<Option<Value<'js>>>> + 'js>>),
21}
22
23pub type NativePullFn<'js> = dyn Fn(&Ctx<'js>) -> Result<NativePullResult<'js>> + 'js;
24
25/// Wrapper satisfying JsLifetime/Trace.
26pub struct NativePull<'js>(pub Rc<NativePullFn<'js>>);
27impl<'js> Clone for NativePull<'js> {
28    fn clone(&self) -> Self {
29        Self(self.0.clone())
30    }
31}
32unsafe impl<'js> JsLifetime<'js> for NativePull<'js> {
33    type Changed<'to> = NativePull<'to>;
34}
35impl<'js> Trace<'js> for NativePull<'js> {
36    fn trace<'a>(&self, _: rquickjs::class::Tracer<'a, 'js>) {}
37}
38
39use crate::stream_web::{
40    queuing_strategy::{SizeAlgorithm, SizeValue},
41    readable::{
42        byte_controller::ReadableByteStreamControllerOwned,
43        controller::{
44            ReadableStreamController, ReadableStreamControllerClass, ReadableStreamControllerOwned,
45        },
46        default_reader::{ReadableStreamDefaultReaderOrUndefined, ReadableStreamReadRequest},
47        objects::{
48            ReadableStreamClassObjects, ReadableStreamDefaultControllerObjects,
49            ReadableStreamDefaultReaderObjects, ReadableStreamObjects,
50        },
51        reader::ReadableStreamReader,
52        stream::{
53            algorithms::{CancelAlgorithm, PullAlgorithm, StartAlgorithm},
54            source::UnderlyingSource,
55            ReadableStream, ReadableStreamClass, ReadableStreamOwned, ReadableStreamState,
56        },
57    },
58    utils::{
59        class_from_owned_borrow_mut,
60        promise::{promise_resolved_with, upon_promise},
61        queue::QueueWithSizes,
62        UnwrapOrUndefined,
63    },
64};
65
66#[derive(JsLifetime, Trace)]
67#[rquickjs::class]
68pub struct ReadableStreamDefaultController<'js> {
69    cancel_algorithm: Option<CancelAlgorithm<'js>>,
70    pub(super) close_requested: bool,
71    pull_again: bool,
72    pull_algorithm: Option<PullAlgorithm<'js>>,
73    pub(crate) pulling: bool,
74    pub(crate) container: QueueWithSizes<'js>,
75    started: bool,
76    strategy_hwm: f64,
77    strategy_size_algorithm: Option<SizeAlgorithm<'js>>,
78    pub(super) stream: ReadableStreamClass<'js>,
79    pub native_pull: Option<NativePull<'js>>,
80    /// Whether this stream was created with `{type: 'owning'}`. Owning streams
81    /// accept a non-empty `transfer` array in `controller.enqueue` and
82    /// structurally transfer each buffer before queueing; non-owning streams
83    /// throw when a non-empty `transfer` list is provided.
84    #[qjs(skip_trace)]
85    pub(super) is_owning_type: bool,
86}
87
88impl<'js> Drop for ReadableStreamDefaultController<'js> {
89    fn drop(&mut self) {
90        self.native_pull = None;
91    }
92}
93
94pub type ReadableStreamDefaultControllerClass<'js> =
95    Class<'js, ReadableStreamDefaultController<'js>>;
96pub(super) type ReadableStreamDefaultControllerOwned<'js> =
97    OwnedBorrowMut<'js, ReadableStreamDefaultController<'js>>;
98
99impl<'js> ReadableStreamDefaultController<'js> {
100    pub(super) fn set_up_readable_stream_default_controller_from_underlying_source(
101        ctx: Ctx<'js>,
102        stream: ReadableStreamOwned<'js>,
103        underlying_source: Null<Undefined<Object<'js>>>,
104        underlying_source_dict: UnderlyingSource<'js>,
105        high_water_mark: f64,
106        size_algorithm: SizeAlgorithm<'js>,
107        is_owning_type: bool,
108    ) -> Result<()> {
109        let (start_algorithm, pull_algorithm, cancel_algorithm) = (
110            // If underlyingSourceDict["start"] exists, then set startAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["start"] with argument list
111            // « controller » and callback this value underlyingSource.
112            underlying_source_dict
113                .start
114                .map(|f| StartAlgorithm::Function {
115                    f,
116                    underlying_source: underlying_source.clone(),
117                })
118                .unwrap_or(StartAlgorithm::ReturnUndefined),
119            // If underlyingSourceDict["pull"] exists, then set pullAlgorithm to an algorithm which returns the result of invoking underlyingSourceDict["pull"] with argument list
120            // « controller » and callback this value underlyingSource.
121            underlying_source_dict
122                .pull
123                .map(|f| PullAlgorithm::Function {
124                    f,
125                    underlying_source: underlying_source.clone(),
126                })
127                .unwrap_or(PullAlgorithm::ReturnPromiseUndefined),
128            // 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
129            // « reason » and callback this value underlyingSource.
130            underlying_source_dict
131                .cancel
132                .map(|f| CancelAlgorithm::Function {
133                    f,
134                    underlying_source,
135                })
136                .unwrap_or(CancelAlgorithm::ReturnPromiseUndefined),
137        );
138
139        // Perform ? SetUpReadableStreamDefaultController(stream, controller, startAlgorithm, pullAlgorithm, cancelAlgorithm, highWaterMark, sizeAlgorithm).
140        Self::set_up_readable_stream_default_controller(
141            ctx.clone(),
142            stream,
143            start_algorithm,
144            pull_algorithm,
145            cancel_algorithm,
146            high_water_mark,
147            size_algorithm,
148            is_owning_type,
149        )?;
150
151        Ok(())
152    }
153
154    #[allow(clippy::too_many_arguments)]
155    pub(super) fn set_up_readable_stream_default_controller(
156        ctx: Ctx<'js>,
157        stream: ReadableStreamOwned<'js>,
158        start_algorithm: StartAlgorithm<'js>,
159        pull_algorithm: PullAlgorithm<'js>,
160        cancel_algorithm: CancelAlgorithm<'js>,
161        high_water_mark: f64,
162        size_algorithm: SizeAlgorithm<'js>,
163        is_owning_type: bool,
164    ) -> Result<Class<'js, Self>> {
165        let (stream_class, mut stream) = class_from_owned_borrow_mut(stream);
166
167        let controller = ReadableStreamDefaultController {
168            // Set controller.[[stream]] to stream.
169            stream: stream_class.clone(),
170
171            // Perform ! ResetQueue(controller).
172            container: QueueWithSizes::new(),
173
174            // Set controller.[[started]], controller.[[closeRequested]], controller.[[pullAgain]], and controller.[[pulling]] to false.
175            started: false,
176            close_requested: false,
177            pull_again: false,
178            pulling: false,
179
180            // Set controller.[[strategySizeAlgorithm]] to sizeAlgorithm and controller.[[strategyHWM]] to highWaterMark.
181            strategy_size_algorithm: Some(size_algorithm),
182            strategy_hwm: high_water_mark,
183
184            // Set controller.[[pullAlgorithm]] to pullAlgorithm.
185            pull_algorithm: Some(pull_algorithm),
186            // Set controller.[[cancelAlgorithm]] to cancelAlgorithm.
187            cancel_algorithm: Some(cancel_algorithm),
188            native_pull: None,
189            is_owning_type,
190        };
191
192        let controller_class = Class::instance(ctx.clone(), controller)?;
193
194        // Set stream.[[controller]] to controller.
195        stream.controller = ReadableStreamControllerClass::ReadableStreamDefaultController(
196            controller_class.clone(),
197        );
198
199        let objects = ReadableStreamObjects::new_default(
200            stream,
201            OwnedBorrowMut::from_class(controller_class),
202        );
203
204        let promise_primordials = objects.stream.promise_primordials.clone();
205
206        // Let startResult be the result of performing startAlgorithm. (This might throw an exception.)
207        let (start_result, objects_class) =
208            Self::start_algorithm(ctx.clone(), objects, start_algorithm)?;
209
210        // Let startPromise be a promise resolved with startResult.
211        let start_promise = promise_resolved_with(&ctx, &promise_primordials, Ok(start_result))?;
212
213        let _ = upon_promise(ctx.clone(), start_promise, {
214            let objects_class = objects_class.clone();
215            Box::new(move |ctx, result| {
216                let mut objects =
217                    ReadableStreamObjects::from_class_no_reader(objects_class).refresh_reader();
218
219                match result {
220                    // Upon fulfillment of startPromise,
221                    Ok(_) => {
222                        // Set controller.[[started]] to true.
223                        objects.controller.started = true;
224                        // Perform ! ReadableByteStreamControllerCallPullIfNeeded(controller).
225                        Self::readable_stream_default_controller_call_pull_if_needed(
226                            ctx.clone(),
227                            objects,
228                        )?;
229                    }
230                    // Upon rejection of startPromise with reason r,
231                    Err(r) => {
232                        // Perform ! ReadableByteStreamControllerError(controller, r).
233                        Self::readable_stream_default_controller_error(objects, r)?;
234                    }
235                }
236                Ok(Value::new_undefined(ctx))
237            })
238        })?;
239
240        Ok(objects_class.controller)
241    }
242
243    fn readable_stream_default_controller_call_pull_if_needed<
244        R: ReadableStreamDefaultReaderOrUndefined<'js>,
245    >(
246        ctx: Ctx<'js>,
247        objects: ReadableStreamDefaultControllerObjects<'js, R>,
248    ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
249        // Let shouldPull be ! ReadableStreamDefaultControllerShouldCallPull(controller).
250
251        let (should_pull, mut objects) =
252            ReadableStreamDefaultController::readable_stream_default_controller_should_call_pull(
253                objects,
254            );
255
256        // If shouldPull is false, return.
257        if !should_pull {
258            return Ok(objects);
259        }
260
261        // If controller.[[pulling]] is true,
262        if objects.controller.pulling {
263            // Set controller.[[pullAgain]] to true.
264            objects.controller.pull_again = true;
265
266            // Return.
267            return Ok(objects);
268        }
269
270        // Set controller.[[pulling]] to true.
271        objects.controller.pulling = true;
272
273        // Let pullPromise be the result of performing controller.[[pullAlgorithm]].
274        let (pull_promise, objects_class) = Self::pull_algorithm(ctx.clone(), objects)?;
275
276        upon_promise(ctx.clone(), pull_promise, {
277            let objects_class = objects_class.clone();
278            Box::new(move |ctx, result| {
279                let mut objects =
280                    ReadableStreamObjects::from_class_no_reader(objects_class).refresh_reader();
281                match result {
282                    // Upon fulfillment of pullPromise,
283                    Ok(_) => {
284                        // Set controller.[[pulling]] to false.
285                        objects.controller.pulling = false;
286                        // If controller.[[pullAgain]] is true,
287                        if objects.controller.pull_again {
288                            // Set controller.[[pullAgain]] to false.
289                            objects.controller.pull_again = false;
290                            // Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
291                            Self::readable_stream_default_controller_call_pull_if_needed(
292                                ctx.clone(),
293                                objects,
294                            )?;
295                        };
296                        Ok(Value::new_undefined(ctx))
297                    }
298                    // Upon rejection of pullPromise with reason e,
299                    Err(e) => {
300                        // Perform ! ReadableStreamDefaultControllerError(controller, e).
301                        Self::readable_stream_default_controller_error(objects, e)?;
302                        Ok(Value::new_undefined(ctx))
303                    }
304                }
305            })
306        })?;
307
308        Ok(ReadableStreamObjects::from_class(objects_class))
309    }
310
311    pub(super) fn readable_stream_default_controller_error<R: ReadableStreamReader<'js>>(
312        // Let stream be controller.[[stream]].
313        mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
314        e: Value<'js>,
315    ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
316        // If stream.[[state]] is not "readable", return.
317        if !matches!(objects.stream.state, ReadableStreamState::Readable) {
318            return Ok(objects);
319        };
320
321        // Perform ! ResetQueue(controller).
322        objects.controller.container.reset_queue();
323
324        // Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
325        objects
326            .controller
327            .readable_stream_default_controller_clear_algorithms();
328
329        // Perform ! ReadableStreamError(stream, e).
330        ReadableStream::readable_stream_error(objects, e)
331    }
332
333    fn readable_stream_default_controller_should_call_pull<
334        R: ReadableStreamDefaultReaderOrUndefined<'js>,
335    >(
336        mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
337    ) -> (bool, ReadableStreamDefaultControllerObjects<'js, R>) {
338        // Let stream be controller.[[stream]].
339        // If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return false.
340        if !objects
341            .controller
342            .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
343        {
344            return (false, objects);
345        }
346
347        // If controller.[[started]] is false, return false.
348        if !objects.controller.started {
349            return (false, objects);
350        }
351
352        {
353            let mut ret = false;
354            // If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, return true.
355            objects = objects
356                .with_some_reader(
357                    |objects| {
358                        if ReadableStream::readable_stream_get_num_read_requests(&objects.reader)
359                            > 0
360                        {
361                            ret = true
362                        }
363                        Ok(objects)
364                    },
365                    Ok,
366                )
367                .unwrap();
368            if ret {
369                return (true, objects);
370            }
371        }
372
373        // Let desiredSize be ! ReadableStreamDefaultControllerGetDesiredSize(controller).
374        let desired_size = objects.controller
375            .readable_stream_default_controller_get_desired_size(&objects.stream)
376            .0
377            .expect(
378            "desiredSize should not be null during ReadableStreamDefaultControllerShouldCallPull",
379        );
380        // If desiredSize > 0, return true.
381        if desired_size > 0.0 {
382            return (true, objects);
383        }
384
385        // Return false.
386        (false, objects)
387    }
388
389    fn readable_stream_default_controller_clear_algorithms(&mut self) {
390        self.pull_algorithm = None;
391        self.cancel_algorithm = None;
392        self.strategy_size_algorithm = None;
393        self.native_pull = None;
394    }
395
396    fn readable_stream_default_controller_can_close_or_enqueue(
397        &self,
398        stream: &ReadableStream<'js>,
399    ) -> bool {
400        // Let state be controller.[[stream]].[[state]].
401        match stream.state {
402            // If controller.[[closeRequested]] is false and state is "readable", return true.
403            ReadableStreamState::Readable if !self.close_requested => true,
404            // Otherwise, return false.
405            _ => false,
406        }
407    }
408
409    pub(crate) fn readable_stream_default_controller_get_desired_size(
410        &self,
411        stream: &ReadableStream<'js>,
412    ) -> Null<f64> {
413        // Let state be controller.[[stream]].[[state]].
414        match stream.state {
415            // If state is "errored", return null.
416            ReadableStreamState::Errored(_) => Null(None),
417            // If state is "closed", return 0.
418            ReadableStreamState::Closed => Null(Some(0.0)),
419            // Return controller.[[strategyHWM]] − controller.[[queueTotalSize]].
420            ReadableStreamState::Readable => {
421                Null(Some(self.strategy_hwm - self.container.queue_total_size))
422            }
423        }
424    }
425
426    pub(super) fn readable_stream_default_controller_close<R: ReadableStreamReader<'js>>(
427        ctx: Ctx<'js>,
428        // Let stream be controller.[[stream]].
429        mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
430    ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
431        // If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
432        if !objects
433            .controller
434            .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
435        {
436            return Ok(objects);
437        }
438
439        // Set controller.[[closeRequested]] to true.
440        objects.controller.close_requested = true;
441
442        // If controller.[[queue]] is empty,
443        if objects.controller.container.queue.is_empty() {
444            // Perform ! ReadableStreamDefaultControllerClearAlgorithms(controller).
445            objects
446                .controller
447                .readable_stream_default_controller_clear_algorithms();
448            // Perform ! ReadableStreamClose(stream).
449            objects = ReadableStream::readable_stream_close(ctx, objects)?;
450        }
451
452        Ok(objects)
453    }
454
455    pub(super) fn readable_stream_default_controller_enqueue<
456        R: ReadableStreamDefaultReaderOrUndefined<'js>,
457    >(
458        ctx: Ctx<'js>,
459        // Let stream be controller.[[stream]].
460        mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
461        chunk: Value<'js>,
462    ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
463        // If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(controller) is false, return.
464        if !objects
465            .controller
466            .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
467        {
468            return Ok(objects);
469        }
470
471        let mut els = true;
472        // If ! IsReadableStreamLocked(stream) is true and ! ReadableStreamGetNumReadRequests(stream) > 0, perform ! ReadableStreamFulfillReadRequest(stream, chunk, false).
473        objects = objects.with_some_reader(
474            |objects| {
475                if ReadableStream::readable_stream_get_num_read_requests(&objects.reader) > 0 {
476                    els = false;
477                    ReadableStream::readable_stream_fulfill_read_request(
478                        &ctx,
479                        objects,
480                        chunk.clone(),
481                        false,
482                    )
483                } else {
484                    Ok(objects)
485                }
486            },
487            Ok,
488        )?;
489
490        if els {
491            // Let result be the result of performing controller.[[strategySizeAlgorithm]], passing in chunk, and interpreting the result as a completion record.
492            let (result, objects_class) =
493                Self::strategy_size_algorithm(ctx.clone(), objects, chunk.clone());
494
495            objects = ReadableStreamObjects::from_class(objects_class);
496
497            match result {
498                // If result is an abrupt completion,
499                Err(Error::Exception) => {
500                    let err = ctx.catch();
501                    // Perform ! ReadableStreamDefaultControllerError(controller, result.[[Value]]).
502                    Self::readable_stream_default_controller_error(objects, err.clone())?;
503
504                    return Err(ctx.throw(err));
505                }
506                // Let chunkSize be result.[[Value]].
507                Ok(chunk_size) => {
508                    // Let enqueueResult be EnqueueValueWithSize(controller, chunk, chunkSize).
509                    let enqueue_result = objects
510                        .controller
511                        .container
512                        .enqueue_value_with_size(&ctx, chunk, chunk_size);
513
514                    match enqueue_result {
515                        // If enqueueResult is an abrupt completion,
516                        Err(Error::Exception) => {
517                            let err = ctx.catch();
518                            // Perform ! ReadableStreamDefaultControllerError(controller, enqueueResult.[[Value]]).
519                            Self::readable_stream_default_controller_error(objects, err.clone())?;
520                            return Err(ctx.throw(err));
521                        }
522                        Err(err) => return Err(err),
523                        Ok(()) => {}
524                    }
525                }
526                Err(err) => return Err(err),
527            }
528        }
529
530        // Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(controller).
531        Self::readable_stream_default_controller_call_pull_if_needed(ctx, objects)
532    }
533
534    fn start_algorithm<R: ReadableStreamReader<'js>>(
535        ctx: Ctx<'js>,
536        objects: ReadableStreamDefaultControllerObjects<'js, R>,
537        start_algorithm: StartAlgorithm<'js>,
538    ) -> Result<(
539        Value<'js>,
540        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
541    )> {
542        let objects_class = objects.into_inner();
543
544        Ok((
545            start_algorithm.call(
546                ctx,
547                ReadableStreamControllerClass::ReadableStreamDefaultController(
548                    objects_class.controller.clone(),
549                ),
550            )?,
551            objects_class,
552        ))
553    }
554
555    fn pull_algorithm<R: ReadableStreamReader<'js>>(
556        ctx: Ctx<'js>,
557        objects: ReadableStreamDefaultControllerObjects<'js, R>,
558    ) -> Result<(
559        Promise<'js>,
560        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
561    )> {
562        let pull_algorithm = objects
563            .controller
564            .pull_algorithm
565            .clone()
566            .expect("pull algorithm used after ReadableStreamDefaultControllerClearAlgorithms");
567        let promise_primordials = objects.stream.promise_primordials.clone();
568        let objects_class = objects.into_inner();
569
570        Ok((
571            pull_algorithm.call(
572                ctx,
573                &promise_primordials,
574                ReadableStreamControllerClass::ReadableStreamDefaultController(
575                    objects_class.controller.clone(),
576                ),
577            )?,
578            objects_class,
579        ))
580    }
581
582    fn strategy_size_algorithm<R: ReadableStreamReader<'js>>(
583        ctx: Ctx<'js>,
584        objects: ReadableStreamDefaultControllerObjects<'js, R>,
585        chunk: Value<'js>,
586    ) -> (
587        Result<SizeValue<'js>>,
588        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
589    ) {
590        let strategy_size_algorithm = objects
591            .controller
592            .strategy_size_algorithm
593            .clone()
594            .expect("size algorithm used after ReadableStreamDefaultControllerClearAlgorithms");
595        let objects_class = objects.into_inner();
596
597        (strategy_size_algorithm.call(ctx, chunk), objects_class)
598    }
599
600    pub(super) fn cancel_algorithm<R: ReadableStreamReader<'js>>(
601        ctx: Ctx<'js>,
602        objects: ReadableStreamDefaultControllerObjects<'js, R>,
603        reason: Value<'js>,
604    ) -> Result<(
605        Promise<'js>,
606        ReadableStreamClassObjects<'js, OwnedBorrowMut<'js, Self>, R>,
607    )> {
608        let cancel_algorithm =
609            objects.controller.cancel_algorithm.clone().expect(
610                "cancel algorithm used after ReadableStreamDefaultControllerClearAlgorithms",
611            );
612        let promise_primordials = objects.stream.promise_primordials.clone();
613        let objects_class = objects.into_inner();
614
615        Ok((
616            cancel_algorithm.call(ctx, &promise_primordials, reason)?,
617            objects_class,
618        ))
619    }
620}
621
622#[methods(rename_all = "camelCase")]
623impl<'js> ReadableStreamDefaultController<'js> {
624    // this is required by web platform tests for unclear reasons
625    fn constructor() -> Self {
626        unimplemented!()
627    }
628
629    #[qjs(constructor)]
630    fn new(ctx: Ctx<'js>) -> Result<Class<'js, Self>> {
631        Err(Exception::throw_type(&ctx, "Illegal constructor"))
632    }
633
634    // readonly attribute unrestricted double? desiredSize;
635    #[qjs(get)]
636    fn desired_size(&self) -> Null<f64> {
637        let stream = OwnedBorrow::from_class(self.stream.clone());
638        self.readable_stream_default_controller_get_desired_size(&stream)
639    }
640
641    // undefined close();
642    fn close(ctx: Ctx<'js>, controller: This<OwnedBorrowMut<'js, Self>>) -> Result<()> {
643        let objects = ReadableStreamObjects::from_default_controller(controller.0);
644
645        // If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.
646        if !objects
647            .controller
648            .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
649        {
650            return Err(Exception::throw_type(
651                &ctx,
652                "The stream is not in a state that permits close",
653            ));
654        }
655
656        // Perform ! ReadableStreamDefaultControllerClose(this).
657        Self::readable_stream_default_controller_close(ctx, objects)?;
658        Ok(())
659    }
660
661    // undefined enqueue(optional any chunk, optional ReadableStreamEnqueueOptions options = {});
662    fn enqueue(
663        ctx: Ctx<'js>,
664        controller: This<OwnedBorrowMut<'js, Self>>,
665        chunk: Opt<Value<'js>>,
666        options: Opt<Value<'js>>,
667    ) -> Result<()> {
668        // Handle the `transfer` option per the `type: 'owning'` ReadableStream
669        // proposal (WPT `streams/readable-streams/owning-type`). The option
670        // is only meaningful on owning-type streams; any other stream throws
671        // `TypeError` if the caller passes a non-empty transfer list.
672        //
673        // WebIDL getter semantics apply: property access must propagate.
674        let mut transfer_list: Option<rquickjs::Array<'js>> = None;
675        if let Some(opts) = options.0.as_ref().and_then(|v| v.as_object()) {
676            transfer_list = opts.get::<_, Option<rquickjs::Array<'js>>>("transfer")?;
677        }
678        let has_transfer_items = transfer_list.as_ref().is_some_and(|arr| !arr.is_empty());
679        if has_transfer_items && !controller.is_owning_type {
680            return Err(Exception::throw_type(&ctx, "transfer list is not empty"));
681        }
682        // Detach each buffer in the transfer list (owning-type streams). Uses
683        // JS `ArrayBuffer.prototype.transfer()` which returns a new buffer
684        // with the same bytes and detaches the original. We re-bind the
685        // chunk to the new buffer if it was the same reference.
686        let chunk_value = chunk.0.clone().unwrap_or_undefined(&ctx);
687        let transferred_chunk = if has_transfer_items && controller.is_owning_type {
688            transfer_owning_chunk(&ctx, chunk_value.clone(), &transfer_list.unwrap())?
689        } else {
690            chunk_value
691        };
692
693        let objects = ReadableStreamObjects::from_default_controller(controller.0);
694
695        // If ! ReadableStreamDefaultControllerCanCloseOrEnqueue(this) is false, throw a TypeError exception.
696        if !objects
697            .controller
698            .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
699        {
700            return Err(Exception::throw_type(
701                &ctx,
702                "The stream is not in a state that permits enqueue",
703            ));
704        }
705
706        objects.with_reader(
707            |objects| {
708                // Perform ? ReadableStreamDefaultControllerEnqueue(this, chunk).
709                Self::readable_stream_default_controller_enqueue(
710                    ctx.clone(),
711                    objects,
712                    transferred_chunk.clone(),
713                )
714            },
715            |_| panic!("Default controller must not have byob reader"),
716            |objects| {
717                // Perform ? ReadableStreamDefaultControllerEnqueue(this, chunk).
718                Self::readable_stream_default_controller_enqueue(
719                    ctx.clone(),
720                    objects,
721                    transferred_chunk.clone(),
722                )
723            },
724        )?;
725
726        Ok(())
727    }
728
729    // undefined error(optional any e);
730    fn error(
731        ctx: Ctx<'js>,
732        controller: This<OwnedBorrowMut<'js, Self>>,
733        e: Opt<Value<'js>>,
734    ) -> Result<()> {
735        let objects = ReadableStreamObjects::from_default_controller(controller.0);
736
737        // Perform ! ReadableStreamDefaultControllerError(this, e).
738        Self::readable_stream_default_controller_error(objects, e.0.unwrap_or_undefined(&ctx))?;
739        Ok(())
740    }
741}
742
743impl<'js> ReadableStreamController<'js> for ReadableStreamDefaultControllerOwned<'js> {
744    type Class = ReadableStreamDefaultControllerClass<'js>;
745
746    fn with_controller<C, O>(
747        self,
748        ctx: C,
749        default: impl FnOnce(
750            C,
751            ReadableStreamDefaultControllerOwned<'js>,
752        ) -> Result<(O, ReadableStreamDefaultControllerOwned<'js>)>,
753        _: impl FnOnce(
754            C,
755            ReadableByteStreamControllerOwned<'js>,
756        ) -> Result<(O, ReadableByteStreamControllerOwned<'js>)>,
757    ) -> Result<(O, Self)> {
758        let (ctx, reader) = default(ctx, self)?;
759        Ok((ctx, reader))
760    }
761
762    fn into_inner(self) -> Self::Class {
763        OwnedBorrowMut::into_inner(self)
764    }
765
766    fn from_class(class: Self::Class) -> Self {
767        OwnedBorrowMut::from_class(class)
768    }
769
770    fn into_erased(self) -> ReadableStreamControllerOwned<'js> {
771        ReadableStreamControllerOwned::ReadableStreamDefaultController(self)
772    }
773
774    fn try_from_erased(erased: ReadableStreamControllerOwned<'js>) -> Option<Self> {
775        match erased {
776            ReadableStreamControllerOwned::ReadableStreamDefaultController(r) => Some(r),
777            ReadableStreamControllerOwned::ReadableStreamByteController(_) => None,
778        }
779    }
780
781    fn pull_steps(
782        ctx: &Ctx<'js>,
783        mut objects: ReadableStreamDefaultReaderObjects<'js, Self>,
784        read_request: impl ReadableStreamReadRequest<'js> + 'js,
785    ) -> Result<ReadableStreamDefaultReaderObjects<'js, Self>> {
786        // If this.[[queue]] is not empty,
787        if !objects.controller.container.queue.is_empty() {
788            // Let chunk be ! DequeueValue(this).
789            let chunk = objects.controller.container.dequeue_value();
790            // If this.[[closeRequested]] is true and this.[[queue]] is empty,
791            if objects.controller.close_requested && objects.controller.container.queue.is_empty() {
792                // Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).
793                objects
794                    .controller
795                    .readable_stream_default_controller_clear_algorithms();
796                // Perform ! ReadableStreamClose(stream).
797                objects = ReadableStream::readable_stream_close(ctx.clone(), objects)?;
798            } else {
799                // Otherwise, perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).
800                objects =
801                    ReadableStreamDefaultController::readable_stream_default_controller_call_pull_if_needed(
802                        ctx.clone(),
803                        objects,
804                    )?;
805            }
806
807            // Perform readRequest’s chunk steps, given chunk.
808            read_request.chunk_steps_typed(objects, chunk)
809        } else {
810            // Otherwise,
811            // Perform ! ReadableStreamAddReadRequest(stream, readRequest).
812            objects
813                .stream
814                .readable_stream_add_read_request(&mut objects.reader, read_request);
815            // Perform ! ReadableStreamDefaultControllerCallPullIfNeeded(this).
816
817            ReadableStreamDefaultController::readable_stream_default_controller_call_pull_if_needed(
818                ctx.clone(),
819                objects,
820            )
821        }
822    }
823
824    fn cancel_steps<R: ReadableStreamReader<'js>>(
825        ctx: &Ctx<'js>,
826        mut objects: ReadableStreamObjects<'js, Self, R>,
827        reason: Value<'js>,
828    ) -> Result<(Promise<'js>, ReadableStreamObjects<'js, Self, R>)> {
829        // Perform ! ResetQueue(this).
830        objects.controller.container.reset_queue();
831
832        // Let result be the result of performing this.[[cancelAlgorithm]], passing reason.
833        let (result, objects_class) =
834            ReadableStreamDefaultController::cancel_algorithm(ctx.clone(), objects, reason)?;
835
836        objects = ReadableStreamObjects::from_class(objects_class);
837        // Perform ! ReadableStreamDefaultControllerClearAlgorithms(this).
838        objects
839            .controller
840            .readable_stream_default_controller_clear_algorithms();
841
842        // Return result.
843        Ok((result, objects))
844    }
845
846    fn release_steps(&mut self) {}
847}
848
849/// Internal enqueue operation for data produced by Rust code.
850pub fn readable_stream_default_controller_enqueue_value<'js>(
851    ctx: Ctx<'js>,
852    controller: ReadableStreamDefaultControllerClass<'js>,
853    chunk: Value<'js>,
854) -> Result<()> {
855    readable_stream_default_controller_enqueue_value_impl(ctx, controller, chunk, false)
856}
857
858pub(crate) fn readable_stream_default_controller_enqueue_value_strict<'js>(
859    ctx: Ctx<'js>,
860    controller: ReadableStreamDefaultControllerClass<'js>,
861    chunk: Value<'js>,
862) -> Result<()> {
863    readable_stream_default_controller_enqueue_value_impl(ctx, controller, chunk, true)
864}
865
866fn readable_stream_default_controller_enqueue_value_impl<'js>(
867    ctx: Ctx<'js>,
868    controller: ReadableStreamDefaultControllerClass<'js>,
869    chunk: Value<'js>,
870    throw_if_unavailable: bool,
871) -> Result<()> {
872    let objects =
873        ReadableStreamObjects::from_default_controller(OwnedBorrowMut::from_class(controller));
874
875    if !objects
876        .controller
877        .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
878    {
879        if throw_if_unavailable {
880            return Err(Exception::throw_type(
881                &ctx,
882                "The stream is not in a state that permits enqueue",
883            ));
884        }
885        return Ok(());
886    }
887
888    objects.with_reader(
889        |objects| {
890            ReadableStreamDefaultController::readable_stream_default_controller_enqueue(
891                ctx.clone(),
892                objects,
893                chunk.clone(),
894            )
895        },
896        |_| panic!("Default controller must not have byob reader"),
897        |objects| {
898            ReadableStreamDefaultController::readable_stream_default_controller_enqueue(
899                ctx.clone(),
900                objects,
901                chunk.clone(),
902            )
903        },
904    )?;
905
906    Ok(())
907}
908
909/// Public API for closing a default controller from Rust code
910pub fn readable_stream_default_controller_close_stream<'js>(
911    ctx: Ctx<'js>,
912    controller: ReadableStreamDefaultControllerClass<'js>,
913) -> Result<()> {
914    let objects =
915        ReadableStreamObjects::from_default_controller(OwnedBorrowMut::from_class(controller));
916
917    if !objects
918        .controller
919        .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
920    {
921        return Ok(());
922    }
923
924    ReadableStreamDefaultController::readable_stream_default_controller_close(ctx, objects)?;
925    Ok(())
926}
927
928/// Public API for erroring a default controller from Rust code
929pub fn readable_stream_default_controller_error_stream<'js>(
930    controller: ReadableStreamDefaultControllerClass<'js>,
931    error: Value<'js>,
932) -> Result<()> {
933    let objects =
934        ReadableStreamObjects::from_default_controller(OwnedBorrowMut::from_class(controller));
935
936    objects.with_reader(
937        |objects| {
938            ReadableStreamDefaultController::readable_stream_default_controller_error(
939                objects,
940                error.clone(),
941            )
942        },
943        |_| panic!("Default controller must not have byob reader"),
944        |objects| {
945            ReadableStreamDefaultController::readable_stream_default_controller_error(
946                objects,
947                error.clone(),
948            )
949        },
950    )?;
951
952    Ok(())
953}
954
955/// Structurally transfer each `ArrayBuffer` in `transfer_list` (detaches the
956/// original) and, if `chunk` references the same buffer, rebind it to the
957/// transferred copy. Called for `controller.enqueue(chunk, { transfer })` on
958/// `type: 'owning'` ReadableStreams.
959fn transfer_owning_chunk<'js>(
960    ctx: &Ctx<'js>,
961    chunk: Value<'js>,
962    transfer_list: &rquickjs::Array<'js>,
963) -> Result<Value<'js>> {
964    use rquickjs::ArrayBuffer;
965    let mut chunk_replacement: Option<Value<'js>> = None;
966    for v in transfer_list.iter::<Value<'js>>() {
967        let v = v?;
968        let Some(ab) = ArrayBuffer::from_value(v.clone()) else {
969            return Err(rquickjs::Exception::throw_type(
970                ctx,
971                "transfer list item is not an ArrayBuffer",
972            ));
973        };
974        // JS object identity: if this transfer-list entry IS the chunk
975        // itself, record that we need to replace the chunk with the
976        // transferred copy. Compare before calling transfer() (which
977        // detaches the buffer).
978        let is_chunk = chunk == v;
979        // Use JS `ArrayBuffer.prototype.transfer()` which returns a new
980        // buffer of the same byteLength and detaches the original.
981        let transfer_fn: rquickjs::Function<'js> = ab.as_object().get("transfer")?;
982        let new_buf: Value<'js> = transfer_fn.call((rquickjs::function::This(ab.clone()),))?;
983        if is_chunk && chunk_replacement.is_none() {
984            chunk_replacement = Some(new_buf);
985        }
986    }
987    Ok(chunk_replacement.unwrap_or(chunk))
988}