1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */

use crate::dom::bindings::codegen::Bindings::TextDecoderBinding;
use crate::dom::bindings::codegen::Bindings::TextDecoderBinding::{
    TextDecodeOptions, TextDecoderMethods,
};
use crate::dom::bindings::codegen::UnionTypes::ArrayBufferViewOrArrayBuffer;
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{reflect_dom_object, Reflector};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::str::{DOMString, USVString};
use crate::dom::globalscope::GlobalScope;
use dom_struct::dom_struct;
use encoding_rs::{Decoder, DecoderResult, Encoding};
use std::borrow::ToOwned;
use std::cell::{Cell, RefCell};

#[dom_struct]
#[allow(non_snake_case)]
pub struct TextDecoder {
    reflector_: Reflector,
    encoding: &'static Encoding,
    fatal: bool,
    ignoreBOM: bool,
    #[ignore_malloc_size_of = "defined in encoding_rs"]
    decoder: RefCell<Decoder>,
    in_stream: RefCell<Vec<u8>>,
    do_not_flush: Cell<bool>,
}

#[allow(non_snake_case)]
impl TextDecoder {
    fn new_inherited(encoding: &'static Encoding, fatal: bool, ignoreBOM: bool) -> TextDecoder {
        TextDecoder {
            reflector_: Reflector::new(),
            encoding: encoding,
            fatal: fatal,
            ignoreBOM: ignoreBOM,
            decoder: RefCell::new(if ignoreBOM {
                encoding.new_decoder()
            } else {
                encoding.new_decoder_without_bom_handling()
            }),
            in_stream: RefCell::new(Vec::new()),
            do_not_flush: Cell::new(false),
        }
    }

    fn make_range_error() -> Fallible<DomRoot<TextDecoder>> {
        Err(Error::Range(
            "The given encoding is not supported.".to_owned(),
        ))
    }

    pub fn new(
        global: &GlobalScope,
        encoding: &'static Encoding,
        fatal: bool,
        ignoreBOM: bool,
    ) -> DomRoot<TextDecoder> {
        reflect_dom_object(
            Box::new(TextDecoder::new_inherited(encoding, fatal, ignoreBOM)),
            global,
        )
    }

    /// <https://encoding.spec.whatwg.org/#dom-textdecoder>
    pub fn Constructor(
        global: &GlobalScope,
        label: DOMString,
        options: &TextDecoderBinding::TextDecoderOptions,
    ) -> Fallible<DomRoot<TextDecoder>> {
        let encoding = match Encoding::for_label_no_replacement(label.as_bytes()) {
            None => return TextDecoder::make_range_error(),
            Some(enc) => enc,
        };
        Ok(TextDecoder::new(
            global,
            encoding,
            options.fatal,
            options.ignoreBOM,
        ))
    }
}

impl TextDecoderMethods for TextDecoder {
    // https://encoding.spec.whatwg.org/#dom-textdecoder-encoding
    fn Encoding(&self) -> DOMString {
        DOMString::from(self.encoding.name().to_ascii_lowercase())
    }

    // https://encoding.spec.whatwg.org/#dom-textdecoder-fatal
    fn Fatal(&self) -> bool {
        self.fatal
    }

    // https://encoding.spec.whatwg.org/#dom-textdecoder-ignorebom
    fn IgnoreBOM(&self) -> bool {
        self.ignoreBOM
    }

    // https://encoding.spec.whatwg.org/#dom-textdecoder-decode
    fn Decode(
        &self,
        input: Option<ArrayBufferViewOrArrayBuffer>,
        options: &TextDecodeOptions,
    ) -> Fallible<USVString> {
        // Step 1.
        if !self.do_not_flush.get() {
            if self.ignoreBOM {
                self.decoder
                    .replace(self.encoding.new_decoder_without_bom_handling());
            } else {
                self.decoder.replace(self.encoding.new_decoder());
            }
            self.in_stream.replace(Vec::new());
        }

        // Step 2.
        self.do_not_flush.set(options.stream);

        // Step 3.
        match input {
            Some(ArrayBufferViewOrArrayBuffer::ArrayBufferView(ref a)) => {
                self.in_stream.borrow_mut().extend_from_slice(&a.to_vec());
            },
            Some(ArrayBufferViewOrArrayBuffer::ArrayBuffer(ref a)) => {
                self.in_stream.borrow_mut().extend_from_slice(&a.to_vec());
            },
            None => {},
        };

        let mut decoder = self.decoder.borrow_mut();
        let (remaining, s) = {
            let mut in_stream = self.in_stream.borrow_mut();

            let (remaining, s) = if self.fatal {
                // Step 4.
                let mut out_stream = String::with_capacity(
                    decoder
                        .max_utf8_buffer_length_without_replacement(in_stream.len())
                        .unwrap(),
                );
                // Step 5: Implemented by encoding_rs::Decoder.
                match decoder.decode_to_string_without_replacement(
                    &in_stream,
                    &mut out_stream,
                    !options.stream,
                ) {
                    (DecoderResult::InputEmpty, read) => (in_stream.split_off(read), out_stream),
                    // Step 5.3.3.
                    _ => return Err(Error::Type("Decoding failed".to_owned())),
                }
            } else {
                // Step 4.
                let mut out_stream =
                    String::with_capacity(decoder.max_utf8_buffer_length(in_stream.len()).unwrap());
                // Step 5: Implemented by encoding_rs::Decoder.
                let (_result, read, _replaced) =
                    decoder.decode_to_string(&in_stream, &mut out_stream, !options.stream);
                (in_stream.split_off(read), out_stream)
            };
            (remaining, s)
        };
        self.in_stream.replace(remaining);
        Ok(USVString(s))
    }
}