script/dom/
textencoderstream.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 https://mozilla.org/MPL/2.0/. */
4
5use std::cell::Cell;
6use std::num::{NonZero, NonZeroU16};
7use std::ptr::{self, NonNull};
8
9use dom_struct::dom_struct;
10use js::conversions::latin1_to_string;
11use js::jsapi::{
12    JS_DeprecatedStringHasLatin1Chars, JS_GetTwoByteStringCharsAndLength, JS_IsExceptionPending,
13    JSObject, JSType, ToPrimitive,
14};
15use js::jsval::UndefinedValue;
16use js::rust::{
17    HandleObject as SafeHandleObject, HandleValue as SafeHandleValue,
18    MutableHandleValue as SafeMutableHandleValue, ToString,
19};
20use js::typedarray::Uint8Array;
21use script_bindings::conversions::SafeToJSValConvertible;
22
23use crate::dom::bindings::buffer_source::create_buffer_source;
24use crate::dom::bindings::codegen::Bindings::TextEncoderStreamBinding::TextEncoderStreamMethods;
25use crate::dom::bindings::error::{Error, Fallible, throw_dom_exception};
26use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
27use crate::dom::bindings::root::{Dom, DomRoot};
28use crate::dom::bindings::str::DOMString;
29use crate::dom::transformstreamdefaultcontroller::TransformerType;
30use crate::dom::types::{GlobalScope, TransformStream, TransformStreamDefaultController};
31use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
32use crate::{DomTypeHolder, DomTypes};
33
34/// String converted from an input JS Value
35enum ConvertedInput<'a> {
36    String(String),
37    CodeUnits(&'a [u16]),
38}
39
40/// Converts a JS value to primitive type so that it can be used with
41/// `ToString`.
42///
43/// Set `rval` to `chunk` if `chunk` is a primitive JS value. Otherwise, convert
44/// `chunk` into a primitive JS value and then set `rval` to the converted
45/// primitive. This follows the `ToString` procedure with the exception that it
46/// does not convert the value to string.
47///
48/// See below for the `ToString` procedure in spec:
49/// <https://tc39.es/ecma262/multipage/abstract-operations.html#sec-tostring>
50#[allow(unsafe_code)]
51fn jsval_to_primitive(
52    cx: SafeJSContext,
53    global: &GlobalScope,
54    chunk: SafeHandleValue,
55    mut rval: SafeMutableHandleValue,
56    can_gc: CanGc,
57) -> Fallible<()> {
58    // Step 1. If argument is a String, return argument.
59    // Step 2. If argument is a Symbol, throw a TypeError exception.
60    // Step 3. If argument is undefined, return "undefined".
61    // Step 4. If argument is null, return "null".
62    // Step 5. If argument is true, return "true".
63    // Step 6. If argument is false, return "false".
64    // Step 7. If argument is a Number, return Number::toString(argument, 10).
65    // Step 8. If argument is a BigInt, return BigInt::toString(argument, 10).
66    if chunk.is_primitive() {
67        rval.set(chunk.get());
68
69        return Ok(());
70    }
71
72    // Step 9. Assert: argument is an Object.
73    assert!(chunk.is_object());
74
75    // Step 10. Let primValue be ? ToPrimitive(argument, string).
76    rooted!(in(*cx) let obj = chunk.to_object());
77    let is_success =
78        unsafe { ToPrimitive(*cx, obj.handle().into(), JSType::JSTYPE_STRING, rval.into()) };
79    log::debug!("ToPrimitive is_success={:?}", is_success);
80    if !is_success {
81        unsafe {
82            if !JS_IsExceptionPending(*cx) {
83                throw_dom_exception(
84                    cx,
85                    global,
86                    Error::Type("Cannot convert JSObject to primitive".to_owned()),
87                    can_gc,
88                );
89            }
90        }
91        return Err(Error::JSFailed);
92    }
93
94    Ok(())
95}
96
97/// <https://encoding.spec.whatwg.org/#textencoderstream-encoder>
98#[derive(Default, JSTraceable, MallocSizeOf)]
99pub(crate) struct Encoder {
100    /// <https://encoding.spec.whatwg.org/#textencoderstream-pending-high-surrogate>
101    leading_surrogate: Cell<Option<NonZeroU16>>,
102}
103
104impl Encoder {
105    fn encode(&self, maybe_ill_formed: ConvertedInput<'_>) -> String {
106        match maybe_ill_formed {
107            ConvertedInput::String(s) => {
108                // Rust String is already UTF-8 encoded and cannot contain
109                // surrogate
110                if !s.is_empty() && self.leading_surrogate.take().is_some() {
111                    let mut output = String::with_capacity(1 + s.len());
112                    output.push('\u{FFFD}');
113                    output.push_str(&s);
114                    return output;
115                }
116
117                s
118            },
119            ConvertedInput::CodeUnits(code_units) => self.encode_from_code_units(code_units),
120        }
121    }
122
123    /// Encode an input slice of code unit into unicode scalar values
124    #[allow(unsafe_code)]
125    fn encode_from_code_units(&self, input: &[u16]) -> String {
126        // <https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk>
127        //
128        // Step 3. Let output be the I/O queue of bytes « end-of-queue ».
129        let mut output = String::with_capacity(input.len());
130        // Step 4. While true:
131        // Step 4.1 Let item be the result of reading from input.
132        for result in char::decode_utf16(input.iter().cloned()) {
133            // Step 4.3 Let result be the result of executing the convert code unit
134            //      to scalar value algorithm with encoder, item and input.
135
136            // <https://encoding.spec.whatwg.org/#convert-code-unit-to-scalar-value>
137            match result {
138                Ok(c) => {
139                    // Step 1. If encoder’s leading surrogate is non-null:
140                    // Step 1.1 Let leadingSurrogate be encoder’s leading surrogate.
141                    // Step 1.2 Set encoder’s leading surrogate to null.
142                    if self.leading_surrogate.take().is_some() {
143                        // Step 1.5 Return U+FFFD (�).
144                        output.push('\u{FFFD}');
145                    }
146
147                    // Step 1.4 Restore item to input.
148                    // Note: pushing item to output is equivalent to restoring item to input
149                    //      and rerun the convert-code-unit-to-scalar-value algo
150                    output.push(c);
151                },
152                Err(error) => {
153                    let unpaired_surrogate = error.unpaired_surrogate();
154                    match code_point_type(unpaired_surrogate) {
155                        CodePointType::LeadingSurrogate => {
156                            // Step 1.1 If encoder’s leading surrogate is non-null:
157                            // Step 1.2 Set encoder’s leading surrogate to null.
158                            if self.leading_surrogate.take().is_some() {
159                                output.push('\u{FFFD}');
160                            }
161
162                            // Step 1.4 Restore item to input.
163                            // Note: Replacing encoder's leading_surrogate is equivalent
164                            //      to restore item back to input and rerun the convert-
165                            //      code-unit-to-scalar-value algo.
166                            // Step 2. If item is a leading surrogate, then set encoder’s
167                            //      leading surrogate to item and return continue.
168                            self.leading_surrogate
169                                .replace(NonZero::new(unpaired_surrogate));
170                        },
171                        CodePointType::TrailingSurrogate => match self.leading_surrogate.take() {
172                            // Step 1.1 If encoder’s leading surrogate is non-null:
173                            // Step 1.2 Set encoder’s leading surrogate to null.
174                            Some(leading_surrogate) => {
175                                // Step 1.3 If item is a trailing surrogate, then return a scalar
176                                //      value from surrogates given leadingSurrogate and item.
177                                let c = char::decode_utf16([
178                                    leading_surrogate.get(),
179                                    unpaired_surrogate,
180                                ])
181                                .next()
182                                .expect("A pair of surrogate is supplied")
183                                .expect("Decoding a pair of surrogate cannot fail");
184                                output.push(c);
185                            },
186                            // Step 3. If item is a trailing surrogate, then return U+FFFD (�).
187                            None => output.push('\u{FFFD}'),
188                        },
189                        CodePointType::ScalarValue => unreachable!("Scalar Value won't fail"),
190                    }
191                },
192            }
193        }
194
195        output
196    }
197}
198
199enum CodePointType {
200    ScalarValue,
201    LeadingSurrogate,
202    TrailingSurrogate,
203}
204
205fn code_point_type(value: u16) -> CodePointType {
206    match value {
207        0xD800..=0xDBFF => CodePointType::LeadingSurrogate,
208        0xDC00..=0xDFFF => CodePointType::TrailingSurrogate,
209        _ => CodePointType::ScalarValue,
210    }
211}
212
213/// <https://encoding.spec.whatwg.org/#encode-and-enqueue-a-chunk>
214#[allow(unsafe_code)]
215pub(crate) fn encode_and_enqueue_a_chunk(
216    cx: SafeJSContext,
217    global: &GlobalScope,
218    chunk: SafeHandleValue,
219    encoder: &Encoder,
220    controller: &TransformStreamDefaultController,
221    can_gc: CanGc,
222) -> Fallible<()> {
223    // Step 1. Let input be the result of converting chunk to a DOMString.
224    // Step 2. Convert input to an I/O queue of code units.
225    rooted!(in(*cx) let mut rval = UndefinedValue());
226    jsval_to_primitive(cx, global, chunk, rval.handle_mut(), can_gc)?;
227
228    assert!(!rval.is_object());
229    rooted!(in(*cx) let jsstr = unsafe { ToString(*cx, rval.handle()) });
230    if jsstr.is_null() {
231        unsafe {
232            if !JS_IsExceptionPending(*cx) {
233                throw_dom_exception(
234                    cx,
235                    global,
236                    Error::Type("Cannot convert JS primitive to string".to_owned()),
237                    can_gc,
238                );
239            }
240        }
241
242        return Err(Error::JSFailed);
243    }
244
245    let input = unsafe {
246        if JS_DeprecatedStringHasLatin1Chars(*jsstr) {
247            let s = NonNull::new(*jsstr).expect("jsstr cannot be null");
248            ConvertedInput::String(latin1_to_string(*cx, s))
249        } else {
250            let mut len = 0;
251            let data = JS_GetTwoByteStringCharsAndLength(*cx, std::ptr::null(), *jsstr, &mut len);
252            let maybe_ill_formed_code_units = std::slice::from_raw_parts(data, len);
253            ConvertedInput::CodeUnits(maybe_ill_formed_code_units)
254        }
255    };
256
257    // Step 3. Let output be the I/O queue of bytes « end-of-queue ».
258    // Step 4. While true:
259    // Step 4.1 Let item be the result of reading from input.
260    // Step 4.3 Let result be the result of executing the convert code unit
261    //      to scalar value algorithm with encoder, item and input.
262    // Step 4.4 If result is not continue, then process an item with result,
263    //      encoder’s encoder, input, output, and "fatal".
264    let output = encoder.encode(input);
265
266    // Step 4.2 If item is end-of-queue:
267    // Step 4.2.1 Convert output into a byte sequence.
268    let output = output.as_bytes();
269    // Step 4.2.2 If output is not empty:
270    if output.is_empty() {
271        // Step 4.2.3
272        return Ok(());
273    }
274
275    // Step 4.2.2.1 Let chunk be the result of creating a Uint8Array object
276    //      given output and encoder’s relevant realm.
277    rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
278    let chunk: Uint8Array = create_buffer_source(cx, output, js_object.handle_mut(), can_gc)
279        .map_err(|_| Error::Type("Cannot convert byte sequence to Uint8Array".to_owned()))?;
280    rooted!(in(*cx) let mut rval = UndefinedValue());
281    chunk.safe_to_jsval(cx, rval.handle_mut());
282    // Step 4.2.2.2 Enqueue chunk into encoder’s transform.
283    controller.enqueue(cx, global, rval.handle(), can_gc)?;
284    Ok(())
285}
286
287/// <https://encoding.spec.whatwg.org/#encode-and-flush>
288#[allow(unsafe_code)]
289pub(crate) fn encode_and_flush(
290    cx: SafeJSContext,
291    global: &GlobalScope,
292    encoder: &Encoder,
293    controller: &TransformStreamDefaultController,
294    can_gc: CanGc,
295) -> Fallible<()> {
296    // Step 1. If encoder’s leading surrogate is non-null:
297    if encoder.leading_surrogate.get().is_some() {
298        // Step 1.1 Let chunk be the result of creating a Uint8Array object
299        //      given « 0xEF, 0xBF, 0xBD » and encoder’s relevant realm.
300        rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
301        let chunk: Uint8Array =
302            create_buffer_source(cx, &[0xEF_u8, 0xBF, 0xBD], js_object.handle_mut(), can_gc)
303                .map_err(|_| {
304                    Error::Type("Cannot convert byte sequence to Uint8Array".to_owned())
305                })?;
306        rooted!(in(*cx) let mut rval = UndefinedValue());
307        chunk.safe_to_jsval(cx, rval.handle_mut());
308        // Step 1.2 Enqueue chunk into encoder’s transform.
309        return controller.enqueue(cx, global, rval.handle(), can_gc);
310    }
311
312    Ok(())
313}
314
315/// <https://encoding.spec.whatwg.org/#textencoderstream>
316#[dom_struct]
317pub(crate) struct TextEncoderStream {
318    reflector_: Reflector,
319
320    /// <https://streams.spec.whatwg.org/#generictransformstream>
321    transform: Dom<TransformStream>,
322}
323
324impl TextEncoderStream {
325    fn new_inherited(transform: &TransformStream) -> TextEncoderStream {
326        Self {
327            reflector_: Reflector::new(),
328            transform: Dom::from_ref(transform),
329        }
330    }
331
332    /// <https://encoding.spec.whatwg.org/#dom-textencoderstream>
333    fn new_with_proto(
334        cx: SafeJSContext,
335        global: &GlobalScope,
336        proto: Option<SafeHandleObject>,
337        can_gc: CanGc,
338    ) -> Fallible<DomRoot<TextEncoderStream>> {
339        // Step 1. Set this’s encoder to an instance of the UTF-8 encoder.
340        let encoder = Encoder::default();
341
342        // Step 2. Let transformAlgorithm be an algorithm which takes a chunk argument
343        //      and runs the encode and enqueue a chunk algorithm with this and chunk.
344        // Step 3. Let flushAlgorithm be an algorithm which runs the encode and flush
345        //      algorithm with this.
346        let transformer_type = TransformerType::Encoder(encoder);
347
348        // Step 4. Let transformStream be a new TransformStream.
349        let transform = TransformStream::new_with_proto(global, None, can_gc);
350        // Step 5. Set up transformStream with transformAlgorithm set to transformAlgorithm
351        //      and flushAlgorithm set to flushAlgorithm.
352        transform.set_up(cx, global, transformer_type, can_gc)?;
353
354        // Step 6. Set this’s transform to transformStream.
355        Ok(reflect_dom_object_with_proto(
356            Box::new(TextEncoderStream::new_inherited(&transform)),
357            global,
358            proto,
359            can_gc,
360        ))
361    }
362}
363
364#[allow(non_snake_case)]
365impl TextEncoderStreamMethods<DomTypeHolder> for TextEncoderStream {
366    /// <https://encoding.spec.whatwg.org/#dom-textencoderstream>
367    fn Constructor(
368        global: &<DomTypeHolder as DomTypes>::GlobalScope,
369        proto: Option<SafeHandleObject>,
370        can_gc: CanGc,
371    ) -> Fallible<DomRoot<<DomTypeHolder as DomTypes>::TextEncoderStream>> {
372        TextEncoderStream::new_with_proto(GlobalScope::get_cx(), global, proto, can_gc)
373    }
374
375    /// <https://encoding.spec.whatwg.org/#dom-textencoder-encoding>
376    fn Encoding(&self) -> DOMString {
377        // Returns "utf-8".
378        DOMString::from("utf-8")
379    }
380
381    /// <https://streams.spec.whatwg.org/#dom-generictransformstream-readable>
382    fn Readable(&self) -> DomRoot<<DomTypeHolder as DomTypes>::ReadableStream> {
383        self.transform.get_readable()
384    }
385
386    /// <https://streams.spec.whatwg.org/#dom-generictransformstream-writable>
387    fn Writable(&self) -> DomRoot<<DomTypeHolder as DomTypes>::WritableStream> {
388        self.transform.get_writable()
389    }
390}