script/dom/encoding/
textencoder.rs1use std::ptr;
6
7use dom_struct::dom_struct;
8use js::context::JSContext;
9use js::gc::CustomAutoRooterGuard;
10use js::jsapi::JSObject;
11use js::rust::HandleObject;
12use js::typedarray;
13use js::typedarray::HeapUint8Array;
14use script_bindings::reflector::{Reflector, reflect_dom_object_with_proto_and_cx};
15use script_bindings::trace::RootedTraceableBox;
16
17use crate::dom::bindings::buffer_source::create_buffer_source;
18use crate::dom::bindings::codegen::Bindings::TextEncoderBinding::{
19 TextEncoderEncodeIntoResult, TextEncoderMethods,
20};
21use crate::dom::bindings::error::Fallible;
22use crate::dom::bindings::root::DomRoot;
23use crate::dom::bindings::str::{DOMString, USVString};
24use crate::dom::globalscope::GlobalScope;
25
26#[dom_struct]
28pub(crate) struct TextEncoder {
29 reflector_: Reflector,
30}
31
32impl TextEncoder {
33 fn new_inherited() -> TextEncoder {
34 TextEncoder {
35 reflector_: Reflector::new(),
36 }
37 }
38
39 fn new(
40 cx: &mut JSContext,
41 global: &GlobalScope,
42 proto: Option<HandleObject>,
43 ) -> DomRoot<TextEncoder> {
44 reflect_dom_object_with_proto_and_cx(
45 Box::new(TextEncoder::new_inherited()),
46 global,
47 proto,
48 cx,
49 )
50 }
51}
52
53impl TextEncoderMethods<crate::DomTypeHolder> for TextEncoder {
54 fn Constructor(
56 cx: &mut JSContext,
57 global: &GlobalScope,
58 proto: Option<HandleObject>,
59 ) -> Fallible<DomRoot<TextEncoder>> {
60 Ok(TextEncoder::new(cx, global, proto))
61 }
62
63 fn Encoding(&self) -> DOMString {
65 DOMString::from("utf-8")
66 }
67
68 fn Encode(&self, cx: &mut JSContext, input: USVString) -> RootedTraceableBox<HeapUint8Array> {
70 let encoded = input.0.as_bytes();
71
72 rooted!(&in(cx) let mut js_object = ptr::null_mut::<JSObject>());
73 create_buffer_source(cx, encoded, js_object.handle_mut())
74 .expect("Converting input to uint8 array should never fail")
75 }
76
77 #[expect(unsafe_code)]
79 fn EncodeInto(
80 &self,
81 source: USVString,
82 mut destination: CustomAutoRooterGuard<typedarray::Uint8Array>,
83 ) -> TextEncoderEncodeIntoResult {
84 let available = destination.len();
85
86 if available == 0 {
88 return TextEncoderEncodeIntoResult {
89 read: Some(0),
90 written: Some(0),
91 };
92 }
93
94 let mut read = 0;
95 let mut written = 0;
96
97 let dest = unsafe { destination.as_mut_slice() };
98
99 for result in source.0.chars() {
103 let utf8_len = result.len_utf8();
104 if available - written >= utf8_len {
105 read += if result > '\u{FFFF}' { 2 } else { 1 };
108
109 let target = &mut dest[written..written + utf8_len];
111 result.encode_utf8(target);
112
113 written += utf8_len;
115 } else {
116 break;
119 }
120 }
121
122 TextEncoderEncodeIntoResult {
123 read: Some(read),
124 written: Some(written as _),
125 }
126 }
127}