runtime/globals/encoding/
encoder.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use encoding_rs::{Encoder, UTF_8};
8use ion::class::Reflector;
9use ion::function::Opt;
10use ion::typedarray::{Uint8Array, Uint8ArrayWrapper};
11use ion::{ToValue, js_class};
12
13#[derive(ToValue)]
14pub struct EncodeResult {
15	read: u64,
16	written: u64,
17}
18
19#[js_class]
20pub struct TextEncoder {
21	reflector: Reflector,
22	#[trace(no_trace)]
23	encoder: Encoder,
24}
25
26#[js_class]
27impl TextEncoder {
28	#[ion(constructor)]
29	pub fn constructor() -> TextEncoder {
30		TextEncoder {
31			reflector: Reflector::default(),
32			encoder: UTF_8.new_encoder(),
33		}
34	}
35
36	pub fn encode(&mut self, Opt(input): Opt<String>) -> Uint8ArrayWrapper {
37		let input = input.unwrap_or_default();
38		let buf_len = self.encoder.max_buffer_length_from_utf8_if_no_unmappables(input.len()).unwrap();
39		let mut buf = Vec::with_capacity(buf_len);
40		let (_, _, _) = self.encoder.encode_from_utf8_to_vec(&input, &mut buf, true);
41		Uint8ArrayWrapper::from(buf)
42	}
43
44	#[ion(name = "encodeInto")]
45	pub fn encode_into(&mut self, input: String, destination: Uint8Array) -> EncodeResult {
46		let (_, read, written, _) = self.encoder.encode_from_utf8(&input, unsafe { destination.as_mut_slice() }, true);
47		EncodeResult {
48			read: read as u64,
49			written: written as u64,
50		}
51	}
52
53	#[ion(get)]
54	pub fn get_encoding(&self) -> String {
55		String::from(self.encoder.encoding().name())
56	}
57}