Skip to main content

quickjs_jit_stdlib/llrt/llrt_stream_web/readable/stream/
algorithms.rs

1// Vendored from LLRT d9fd873e793c (modules/llrt_stream_web/src/readable/stream/algorithms.rs); module paths and
2// feature names adapted by scripts/import-stdlib.py.
3use std::{cell::RefCell, rc::Rc};
4
5use crate::utils::option::{Null, Undefined};
6use crate::utils::primordials::Primordial;
7use rquickjs::{
8    class::Trace, prelude::This, Class, Ctx, Function, JsLifetime, Object, Promise, Result, Value,
9};
10
11use crate::stream_web::{
12    readable::controller::ReadableStreamControllerClass,
13    transform::{
14        controller::TransformStreamDefaultControllerClass,
15        stream::{self as transform_stream, TransformStreamClass},
16    },
17    utils::promise::{promise_resolved_with, PromisePrimordials},
18};
19
20use super::tee::TeeState;
21
22#[derive(Clone)]
23pub enum StartAlgorithm<'js> {
24    ReturnUndefined,
25    Function {
26        f: Function<'js>,
27        underlying_source: Null<Undefined<Object<'js>>>,
28    },
29}
30
31impl<'js> StartAlgorithm<'js> {
32    pub(crate) fn call(
33        &self,
34        ctx: Ctx<'js>,
35        controller: ReadableStreamControllerClass<'js>,
36    ) -> Result<Value<'js>> {
37        match self {
38            StartAlgorithm::ReturnUndefined => Ok(Value::new_undefined(ctx.clone())),
39            StartAlgorithm::Function {
40                f,
41                underlying_source,
42            } => f.call::<_, Value>((This(underlying_source.clone()), controller)),
43        }
44    }
45}
46
47type PullRustFn<'js> =
48    Box<dyn Fn(Ctx<'js>, ReadableStreamControllerClass<'js>) -> Result<Promise<'js>> + 'js>;
49
50#[allow(private_interfaces)]
51#[derive(Clone)]
52pub enum PullAlgorithm<'js> {
53    ReturnPromiseUndefined,
54    Function {
55        f: Function<'js>,
56        underlying_source: Null<Undefined<Object<'js>>>,
57    },
58    RustFunction(Rc<PullRustFn<'js>>),
59    Tee(Class<'js, TeeState<'js>>),
60    Transform(TransformStreamClass<'js>),
61}
62
63impl<'js> Trace<'js> for PullAlgorithm<'js> {
64    fn trace<'a>(&self, tracer: rquickjs::class::Tracer<'a, 'js>) {
65        match self {
66            Self::ReturnPromiseUndefined => {}
67            Self::Function {
68                f,
69                underlying_source,
70            } => {
71                f.trace(tracer);
72                underlying_source.trace(tracer);
73            }
74            Self::RustFunction(_) => {}
75            Self::Tee(state) => state.trace(tracer),
76            Self::Transform(stream) => stream.trace(tracer),
77        }
78    }
79}
80
81unsafe impl<'js> JsLifetime<'js> for PullAlgorithm<'js> {
82    type Changed<'to> = PullAlgorithm<'to>;
83}
84
85impl<'js> PullAlgorithm<'js> {
86    pub fn from_fn(
87        f: impl Fn(Ctx<'js>, ReadableStreamControllerClass<'js>) -> Result<Promise<'js>> + 'js,
88    ) -> Self {
89        Self::RustFunction(Rc::new(Box::new(f)))
90    }
91
92    /// Wrap a one-shot pull closure. Subsequent invocations after the first
93    /// resolve with `undefined` without calling `f` again — useful for
94    /// streams that enqueue their whole payload in one go and then close.
95    pub fn from_fn_once(
96        f: impl FnOnce(Ctx<'js>, ReadableStreamControllerClass<'js>) -> Result<Promise<'js>> + 'js,
97    ) -> Self {
98        type OnceSlot<'js> = Rc<
99            RefCell<
100                Option<
101                    Box<
102                        dyn FnOnce(
103                                Ctx<'js>,
104                                ReadableStreamControllerClass<'js>,
105                            ) -> Result<Promise<'js>>
106                            + 'js,
107                    >,
108                >,
109            >,
110        >;
111        let slot: OnceSlot<'js> = Rc::new(RefCell::new(Some(Box::new(f))));
112        Self::from_fn(move |ctx, ctrl| {
113            if let Some(f) = slot.borrow_mut().take() {
114                f(ctx, ctrl)
115            } else {
116                Ok(PromisePrimordials::get(&ctx)?
117                    .promise_resolved_with_undefined
118                    .clone())
119            }
120        })
121    }
122
123    pub(super) fn from_tee_state(state: Class<'js, TeeState<'js>>) -> Self {
124        Self::Tee(state)
125    }
126
127    pub(crate) fn call(
128        &self,
129        ctx: Ctx<'js>,
130        promise_primordials: &PromisePrimordials<'js>,
131        controller: ReadableStreamControllerClass<'js>,
132    ) -> Result<Promise<'js>> {
133        match self {
134            PullAlgorithm::ReturnPromiseUndefined => {
135                Ok(promise_primordials.promise_resolved_with_undefined.clone())
136            }
137            PullAlgorithm::Function {
138                f,
139                underlying_source,
140            } => promise_resolved_with(
141                &ctx,
142                promise_primordials,
143                f.call::<_, Value>((This(underlying_source.clone()), controller)),
144            ),
145            PullAlgorithm::RustFunction(f) => f(ctx, controller),
146            PullAlgorithm::Tee(state) => {
147                crate::stream_web::readable::stream::tee::tee_pull_algorithm(ctx, state.clone())
148            }
149            PullAlgorithm::Transform(stream) => {
150                transform_stream::source_pull_algorithm(ctx, stream)
151            }
152        }
153    }
154}
155
156type CancelRustFn<'js> = Box<dyn FnOnce(Value<'js>) -> Result<Promise<'js>> + 'js>;
157
158#[allow(private_interfaces)]
159pub enum CancelAlgorithm<'js> {
160    ReturnPromiseUndefined,
161    Function {
162        f: Function<'js>,
163        underlying_source: Null<Undefined<Object<'js>>>,
164    },
165    RustFunction(Rc<RefCell<Option<CancelRustFn<'js>>>>),
166    Tee1(Class<'js, TeeState<'js>>),
167    Tee2(Class<'js, TeeState<'js>>),
168    Transform {
169        stream: TransformStreamClass<'js>,
170        controller: TransformStreamDefaultControllerClass<'js>,
171    },
172}
173
174impl<'js> Clone for CancelAlgorithm<'js> {
175    fn clone(&self) -> Self {
176        match self {
177            Self::ReturnPromiseUndefined => Self::ReturnPromiseUndefined,
178            Self::Function {
179                f,
180                underlying_source,
181            } => Self::Function {
182                f: f.clone(),
183                underlying_source: underlying_source.clone(),
184            },
185            Self::RustFunction(rc) => Self::RustFunction(rc.clone()),
186            Self::Tee1(state) => Self::Tee1(state.clone()),
187            Self::Tee2(state) => Self::Tee2(state.clone()),
188            Self::Transform { stream, controller } => Self::Transform {
189                stream: stream.clone(),
190                controller: controller.clone(),
191            },
192        }
193    }
194}
195
196impl<'js> Trace<'js> for CancelAlgorithm<'js> {
197    fn trace<'a>(&self, tracer: rquickjs::class::Tracer<'a, 'js>) {
198        match self {
199            Self::ReturnPromiseUndefined => {}
200            Self::Function {
201                f,
202                underlying_source,
203            } => {
204                f.trace(tracer);
205                underlying_source.trace(tracer);
206            }
207            Self::RustFunction(_) => {}
208            Self::Tee1(state) | Self::Tee2(state) => state.trace(tracer),
209            Self::Transform { stream, controller } => {
210                stream.trace(tracer);
211                controller.trace(tracer);
212            }
213        }
214    }
215}
216
217unsafe impl<'js> JsLifetime<'js> for CancelAlgorithm<'js> {
218    type Changed<'to> = CancelAlgorithm<'to>;
219}
220
221impl<'js> CancelAlgorithm<'js> {
222    pub fn from_fn(f: impl FnOnce(Value<'js>) -> Result<Promise<'js>> + 'js) -> Self {
223        Self::RustFunction(Rc::new(RefCell::new(Some(Box::new(f)))))
224    }
225
226    pub(super) fn from_tee_state_1(state: Class<'js, TeeState<'js>>) -> Self {
227        Self::Tee1(state)
228    }
229
230    pub(super) fn from_tee_state_2(state: Class<'js, TeeState<'js>>) -> Self {
231        Self::Tee2(state)
232    }
233
234    pub(crate) fn call(
235        &self,
236        ctx: Ctx<'js>,
237        promise_primordials: &PromisePrimordials<'js>,
238        reason: Value<'js>,
239    ) -> Result<Promise<'js>> {
240        match self {
241            CancelAlgorithm::ReturnPromiseUndefined => {
242                Ok(promise_primordials.promise_resolved_with_undefined.clone())
243            }
244            CancelAlgorithm::Function {
245                f,
246                underlying_source,
247            } => {
248                let result: Result<Value> = f.call((This(underlying_source.clone()), reason));
249                promise_resolved_with(&ctx, promise_primordials, result)
250            }
251            CancelAlgorithm::RustFunction(f) => {
252                let f = f
253                    .borrow_mut()
254                    .take()
255                    .expect("cancel algorithm must only be called once");
256                f(reason)
257            }
258            CancelAlgorithm::Tee1(state) => {
259                crate::stream_web::readable::stream::tee::tee_cancel_algorithm(
260                    ctx,
261                    state.clone(),
262                    reason,
263                    0,
264                )
265            }
266            CancelAlgorithm::Tee2(state) => {
267                crate::stream_web::readable::stream::tee::tee_cancel_algorithm(
268                    ctx,
269                    state.clone(),
270                    reason,
271                    1,
272                )
273            }
274            CancelAlgorithm::Transform { stream, controller } => {
275                transform_stream::source_cancel_algorithm(ctx, stream, controller, reason)
276            }
277        }
278    }
279}