Skip to main content

script/dom/stream/
readablestreambyobrequest.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 dom_struct::dom_struct;
6use js::context::JSContext;
7use js::gc::CustomAutoRooterGuard;
8use js::typedarray::{ArrayBufferView, ArrayBufferViewU8};
9use script_bindings::cell::DomRefCell;
10use script_bindings::reflector::{Reflector, reflect_dom_object};
11use script_bindings::trace::RootedTraceableBox;
12
13use crate::dom::bindings::buffer_source::HeapBufferSource;
14use crate::dom::bindings::codegen::Bindings::ReadableStreamBYOBRequestBinding::ReadableStreamBYOBRequestMethods;
15use crate::dom::bindings::error::{Error, Fallible};
16use crate::dom::bindings::root::{DomRoot, MutNullableDom};
17use crate::dom::stream::readablebytestreamcontroller::ReadableByteStreamController;
18use crate::dom::types::GlobalScope;
19use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
20
21/// <https://streams.spec.whatwg.org/#readablestreambyobrequest>
22#[dom_struct]
23pub(crate) struct ReadableStreamBYOBRequest {
24    reflector_: Reflector,
25    controller: MutNullableDom<ReadableByteStreamController>,
26    #[ignore_malloc_size_of = "mozjs"]
27    view: DomRefCell<HeapBufferSource<ArrayBufferViewU8>>,
28}
29
30impl ReadableStreamBYOBRequest {
31    fn new_inherited() -> ReadableStreamBYOBRequest {
32        ReadableStreamBYOBRequest {
33            reflector_: Reflector::new(),
34            controller: MutNullableDom::new(None),
35            view: DomRefCell::new(HeapBufferSource::<ArrayBufferViewU8>::default()),
36        }
37    }
38
39    pub(crate) fn new(global: &GlobalScope, can_gc: CanGc) -> DomRoot<ReadableStreamBYOBRequest> {
40        reflect_dom_object(Box::new(Self::new_inherited()), global, can_gc)
41    }
42
43    pub(crate) fn set_controller(&self, controller: Option<&ReadableByteStreamController>) {
44        self.controller.set(controller);
45    }
46
47    pub(crate) fn set_view(
48        &self,
49        view: Option<RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>>>,
50    ) {
51        match view {
52            Some(view) => {
53                *self.view.borrow_mut() = *view.into_box();
54            },
55            None => {
56                *self.view.borrow_mut() = HeapBufferSource::<ArrayBufferViewU8>::default();
57            },
58        }
59    }
60
61    pub(crate) fn get_view(&self) -> RootedTraceableBox<HeapBufferSource<ArrayBufferViewU8>> {
62        RootedTraceableBox::new(self.view.borrow().clone())
63    }
64}
65
66impl ReadableStreamBYOBRequestMethods<crate::DomTypeHolder> for ReadableStreamBYOBRequest {
67    /// <https://streams.spec.whatwg.org/#rs-byob-request-view>
68    fn GetView(
69        &self,
70        _cx: SafeJSContext,
71    ) -> Option<RootedTraceableBox<js::typedarray::HeapArrayBufferView>> {
72        // Return this.[[view]].
73        self.view.borrow().typed_array_to_option()
74    }
75
76    /// <https://streams.spec.whatwg.org/#rs-byob-request-respond>
77    fn Respond(&self, cx: &mut JSContext, bytes_written: u64) -> Fallible<()> {
78        // If this.[[controller]] is undefined, throw a TypeError exception.
79        let controller = if let Some(controller) = self.controller.get() {
80            controller
81        } else {
82            return Err(Error::Type(c"controller is undefined".to_owned()));
83        };
84
85        {
86            let view = self.view.borrow();
87            // If ! IsDetachedBuffer(this.[[view]].[[ArrayBuffer]]) is true, throw a TypeError exception.
88            if view
89                .get_array_buffer_view_buffer(cx.into())
90                .is_detached_buffer(cx.into())
91            {
92                return Err(Error::Type(c"buffer is detached".to_owned()));
93            }
94
95            // Assert: this.[[view]].[[ByteLength]] > 0.
96            assert!(view.byte_length() > 0);
97
98            // Assert: this.[[view]].[[ViewedArrayBuffer]].[[ByteLength]] > 0.
99            assert!(view.viewed_buffer_array_byte_length(cx.into()) > 0);
100        }
101
102        // Perform ? ReadableByteStreamControllerRespond(this.[[controller]], bytesWritten).
103        controller.respond(cx, bytes_written)
104    }
105
106    /// <https://streams.spec.whatwg.org/#rs-byob-request-respond-with-new-view>
107    fn RespondWithNewView(
108        &self,
109        cx: &mut JSContext,
110        view: CustomAutoRooterGuard<ArrayBufferView>,
111    ) -> Fallible<()> {
112        let view = HeapBufferSource::<ArrayBufferViewU8>::from_view(view);
113
114        // If this.[[controller]] is undefined, throw a TypeError exception.
115        let controller = if let Some(controller) = self.controller.get() {
116            controller
117        } else {
118            return Err(Error::Type(c"controller is undefined".to_owned()));
119        };
120
121        // If ! IsDetachedBuffer(view.[[ViewedArrayBuffer]]) is true, throw a TypeError exception.
122        if view.is_detached_buffer(cx.into()) {
123            return Err(Error::Type(c"buffer is detached".to_owned()));
124        }
125
126        // Return ? ReadableByteStreamControllerRespondWithNewView(this.[[controller]], view).
127        controller.respond_with_new_view(cx, &view)
128    }
129}