script/dom/
textdecoder.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::borrow::ToOwned;
6use std::cell::Cell;
7
8use dom_struct::dom_struct;
9use encoding_rs::Encoding;
10use js::rust::HandleObject;
11
12use crate::dom::bindings::codegen::Bindings::TextDecoderBinding;
13use crate::dom::bindings::codegen::Bindings::TextDecoderBinding::{
14    TextDecodeOptions, TextDecoderMethods,
15};
16use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer;
17use crate::dom::bindings::error::{Error, Fallible};
18use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
19use crate::dom::bindings::root::DomRoot;
20use crate::dom::bindings::str::{DOMString, USVString};
21use crate::dom::globalscope::GlobalScope;
22use crate::dom::textdecodercommon::TextDecoderCommon;
23use crate::script_runtime::CanGc;
24
25/// <https://encoding.spec.whatwg.org/#textdecoder>
26#[dom_struct]
27pub(crate) struct TextDecoder {
28    reflector_: Reflector,
29
30    /// <https://encoding.spec.whatwg.org/#textdecodercommon>
31    decoder: TextDecoderCommon,
32
33    /// <https://encoding.spec.whatwg.org/#textdecoder-do-not-flush-flag>
34    do_not_flush: Cell<bool>,
35}
36
37#[expect(non_snake_case)]
38impl TextDecoder {
39    fn new_inherited(encoding: &'static Encoding, fatal: bool, ignoreBOM: bool) -> TextDecoder {
40        let decoder = TextDecoderCommon::new_inherited(encoding, fatal, ignoreBOM);
41        TextDecoder {
42            reflector_: Reflector::new(),
43            decoder,
44            do_not_flush: Cell::new(false),
45        }
46    }
47
48    fn make_range_error() -> Fallible<DomRoot<TextDecoder>> {
49        Err(Error::Range(
50            "The given encoding is not supported.".to_owned(),
51        ))
52    }
53
54    fn new(
55        global: &GlobalScope,
56        proto: Option<HandleObject>,
57        encoding: &'static Encoding,
58        fatal: bool,
59        ignoreBOM: bool,
60        can_gc: CanGc,
61    ) -> DomRoot<TextDecoder> {
62        reflect_dom_object_with_proto(
63            Box::new(TextDecoder::new_inherited(encoding, fatal, ignoreBOM)),
64            global,
65            proto,
66            can_gc,
67        )
68    }
69}
70
71impl TextDecoderMethods<crate::DomTypeHolder> for TextDecoder {
72    /// <https://encoding.spec.whatwg.org/#dom-textdecoder>
73    fn Constructor(
74        global: &GlobalScope,
75        proto: Option<HandleObject>,
76        can_gc: CanGc,
77        label: DOMString,
78        options: &TextDecoderBinding::TextDecoderOptions,
79    ) -> Fallible<DomRoot<TextDecoder>> {
80        let encoding = match Encoding::for_label_no_replacement(&label.as_bytes()) {
81            None => return TextDecoder::make_range_error(),
82            Some(enc) => enc,
83        };
84        Ok(TextDecoder::new(
85            global,
86            proto,
87            encoding,
88            options.fatal,
89            options.ignoreBOM,
90            can_gc,
91        ))
92    }
93
94    /// <https://encoding.spec.whatwg.org/#dom-textdecoder-encoding>
95    fn Encoding(&self) -> DOMString {
96        DOMString::from(self.decoder.encoding().name().to_ascii_lowercase())
97    }
98
99    /// <https://encoding.spec.whatwg.org/#dom-textdecoder-fatal>
100    fn Fatal(&self) -> bool {
101        self.decoder.fatal()
102    }
103
104    /// <https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom>
105    fn IgnoreBOM(&self) -> bool {
106        self.decoder.ignore_bom()
107    }
108
109    /// <https://encoding.spec.whatwg.org/#dom-textdecoder-decode>
110    fn Decode(
111        &self,
112        input: Option<ArrayBufferViewOrArrayBuffer>,
113        options: &TextDecodeOptions,
114    ) -> Fallible<USVString> {
115        // Step 1. If this’s do not flush is false, then set this’s decoder to a new
116        // instance of this’s encoding’s decoder, this’s I/O queue to the I/O queue
117        // of bytes « end-of-queue », and this’s BOM seen to false.
118        if !self.do_not_flush.get() {
119            if self.decoder.ignore_bom() {
120                self.decoder
121                    .decoder()
122                    .replace(self.decoder.encoding().new_decoder_without_bom_handling());
123            } else {
124                self.decoder
125                    .decoder()
126                    .replace(self.decoder.encoding().new_decoder_with_bom_removal());
127            }
128            self.decoder.io_queue().replace(Vec::new());
129        }
130
131        // Step 2. Set this’s do not flush to options["stream"].
132        self.do_not_flush.set(options.stream);
133
134        // Step 3. If input is given, then push a copy of input to this’s I/O queue.
135        // Step 4. Let output be the I/O queue of scalar values « end-of-queue ».
136        // Step 5. While true:
137        // Step 5.1 Let item be the result of reading from this’s I/O queue.
138        // Step 5.2 If item is end-of-queue and this’s do not flush is true,
139        //      then return the result of running serialize I/O queue with this and output.
140        // Step 5.3 Otherwise:
141        // Step 5.3.1 Let result be the result of processing an item with item, this’s decoder,
142        //      this’s I/O queue, output, and this’s error mode.
143        // Step 5.3.2 If result is finished, then return the result of running serialize I/O
144        //      queue with this and output.
145        self.decoder
146            .decode(input.as_ref(), !options.stream)
147            .map(USVString)
148    }
149}