1use 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
12pub enum NativePullResult<'js> {
15 Ready(Value<'js>),
17 Eof,
19 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
25pub 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 #[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 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 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 underlying_source_dict
131 .cancel
132 .map(|f| CancelAlgorithm::Function {
133 f,
134 underlying_source,
135 })
136 .unwrap_or(CancelAlgorithm::ReturnPromiseUndefined),
137 );
138
139 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 stream: stream_class.clone(),
170
171 container: QueueWithSizes::new(),
173
174 started: false,
176 close_requested: false,
177 pull_again: false,
178 pulling: false,
179
180 strategy_size_algorithm: Some(size_algorithm),
182 strategy_hwm: high_water_mark,
183
184 pull_algorithm: Some(pull_algorithm),
186 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 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 (start_result, objects_class) =
208 Self::start_algorithm(ctx.clone(), objects, start_algorithm)?;
209
210 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 Ok(_) => {
222 objects.controller.started = true;
224 Self::readable_stream_default_controller_call_pull_if_needed(
226 ctx.clone(),
227 objects,
228 )?;
229 }
230 Err(r) => {
232 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 (should_pull, mut objects) =
252 ReadableStreamDefaultController::readable_stream_default_controller_should_call_pull(
253 objects,
254 );
255
256 if !should_pull {
258 return Ok(objects);
259 }
260
261 if objects.controller.pulling {
263 objects.controller.pull_again = true;
265
266 return Ok(objects);
268 }
269
270 objects.controller.pulling = true;
272
273 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 Ok(_) => {
284 objects.controller.pulling = false;
286 if objects.controller.pull_again {
288 objects.controller.pull_again = false;
290 Self::readable_stream_default_controller_call_pull_if_needed(
292 ctx.clone(),
293 objects,
294 )?;
295 };
296 Ok(Value::new_undefined(ctx))
297 }
298 Err(e) => {
300 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 mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
314 e: Value<'js>,
315 ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
316 if !matches!(objects.stream.state, ReadableStreamState::Readable) {
318 return Ok(objects);
319 };
320
321 objects.controller.container.reset_queue();
323
324 objects
326 .controller
327 .readable_stream_default_controller_clear_algorithms();
328
329 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 if !objects
341 .controller
342 .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
343 {
344 return (false, objects);
345 }
346
347 if !objects.controller.started {
349 return (false, objects);
350 }
351
352 {
353 let mut ret = false;
354 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 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 desired_size > 0.0 {
382 return (true, objects);
383 }
384
385 (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 match stream.state {
402 ReadableStreamState::Readable if !self.close_requested => true,
404 _ => 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 match stream.state {
415 ReadableStreamState::Errored(_) => Null(None),
417 ReadableStreamState::Closed => Null(Some(0.0)),
419 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 mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
430 ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
431 if !objects
433 .controller
434 .readable_stream_default_controller_can_close_or_enqueue(&objects.stream)
435 {
436 return Ok(objects);
437 }
438
439 objects.controller.close_requested = true;
441
442 if objects.controller.container.queue.is_empty() {
444 objects
446 .controller
447 .readable_stream_default_controller_clear_algorithms();
448 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 mut objects: ReadableStreamDefaultControllerObjects<'js, R>,
461 chunk: Value<'js>,
462 ) -> Result<ReadableStreamDefaultControllerObjects<'js, R>> {
463 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 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, 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 Err(Error::Exception) => {
500 let err = ctx.catch();
501 Self::readable_stream_default_controller_error(objects, err.clone())?;
503
504 return Err(ctx.throw(err));
505 }
506 Ok(chunk_size) => {
508 let enqueue_result = objects
510 .controller
511 .container
512 .enqueue_value_with_size(&ctx, chunk, chunk_size);
513
514 match enqueue_result {
515 Err(Error::Exception) => {
517 let err = ctx.catch();
518 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 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 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 #[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 fn close(ctx: Ctx<'js>, controller: This<OwnedBorrowMut<'js, Self>>) -> Result<()> {
643 let objects = ReadableStreamObjects::from_default_controller(controller.0);
644
645 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 Self::readable_stream_default_controller_close(ctx, objects)?;
658 Ok(())
659 }
660
661 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 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 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 !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 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 Self::readable_stream_default_controller_enqueue(
719 ctx.clone(),
720 objects,
721 transferred_chunk.clone(),
722 )
723 },
724 )?;
725
726 Ok(())
727 }
728
729 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 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 !objects.controller.container.queue.is_empty() {
788 let chunk = objects.controller.container.dequeue_value();
790 if objects.controller.close_requested && objects.controller.container.queue.is_empty() {
792 objects
794 .controller
795 .readable_stream_default_controller_clear_algorithms();
796 objects = ReadableStream::readable_stream_close(ctx.clone(), objects)?;
798 } else {
799 objects =
801 ReadableStreamDefaultController::readable_stream_default_controller_call_pull_if_needed(
802 ctx.clone(),
803 objects,
804 )?;
805 }
806
807 read_request.chunk_steps_typed(objects, chunk)
809 } else {
810 objects
813 .stream
814 .readable_stream_add_read_request(&mut objects.reader, read_request);
815 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 objects.controller.container.reset_queue();
831
832 let (result, objects_class) =
834 ReadableStreamDefaultController::cancel_algorithm(ctx.clone(), objects, reason)?;
835
836 objects = ReadableStreamObjects::from_class(objects_class);
837 objects
839 .controller
840 .readable_stream_default_controller_clear_algorithms();
841
842 Ok((result, objects))
844 }
845
846 fn release_steps(&mut self) {}
847}
848
849pub 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
909pub 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
928pub 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
955fn 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 let is_chunk = chunk == v;
979 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}