1use std::ptr;
6use std::rc::Rc;
7
8use base::id::{BlobId, BlobIndex};
9use constellation_traits::{BlobData, BlobImpl};
10use dom_struct::dom_struct;
11use encoding_rs::UTF_8;
12use js::jsapi::JSObject;
13use js::rust::HandleObject;
14use js::typedarray::{ArrayBufferU8, Uint8};
15use net_traits::filemanager_thread::RelativePos;
16use rustc_hash::FxHashMap;
17use uuid::Uuid;
18
19use crate::dom::bindings::buffer_source::create_buffer_source;
20use crate::dom::bindings::codegen::Bindings::BlobBinding;
21use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
22use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlobOrString;
23use crate::dom::bindings::error::{Error, Fallible};
24use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object_with_proto};
25use crate::dom::bindings::root::DomRoot;
26use crate::dom::bindings::serializable::Serializable;
27use crate::dom::bindings::str::DOMString;
28use crate::dom::bindings::structuredclone::StructuredData;
29use crate::dom::globalscope::GlobalScope;
30use crate::dom::promise::Promise;
31use crate::dom::readablestream::ReadableStream;
32use crate::realms::{AlreadyInRealm, InRealm};
33use crate::script_runtime::CanGc;
34
35#[dom_struct]
37pub(crate) struct Blob {
38 reflector_: Reflector,
39 #[no_trace]
40 blob_id: BlobId,
41}
42
43impl Blob {
44 pub(crate) fn new(global: &GlobalScope, blob_impl: BlobImpl, can_gc: CanGc) -> DomRoot<Blob> {
45 Self::new_with_proto(global, None, blob_impl, can_gc)
46 }
47
48 fn new_with_proto(
49 global: &GlobalScope,
50 proto: Option<HandleObject>,
51 blob_impl: BlobImpl,
52 can_gc: CanGc,
53 ) -> DomRoot<Blob> {
54 let dom_blob = reflect_dom_object_with_proto(
55 Box::new(Blob::new_inherited(&blob_impl)),
56 global,
57 proto,
58 can_gc,
59 );
60 global.track_blob(&dom_blob, blob_impl);
61 dom_blob
62 }
63
64 #[cfg_attr(crown, allow(crown::unrooted_must_root))]
65 pub(crate) fn new_inherited(blob_impl: &BlobImpl) -> Blob {
66 Blob {
67 reflector_: Reflector::new(),
68 blob_id: blob_impl.blob_id(),
69 }
70 }
71
72 pub(crate) fn get_bytes(&self) -> Result<Vec<u8>, ()> {
74 self.global().get_blob_bytes(&self.blob_id)
75 }
76
77 pub(crate) fn type_string(&self) -> String {
79 self.global().get_blob_type_string(&self.blob_id)
80 }
81
82 pub(crate) fn get_blob_url_id(&self) -> Uuid {
85 self.global().get_blob_url_id(&self.blob_id)
86 }
87
88 pub(crate) fn get_stream(&self, can_gc: CanGc) -> Fallible<DomRoot<ReadableStream>> {
90 self.global().get_blob_stream(&self.blob_id, can_gc)
91 }
92}
93
94impl Serializable for Blob {
95 type Index = BlobIndex;
96 type Data = BlobImpl;
97
98 fn serialize(&self) -> Result<(BlobId, BlobImpl), ()> {
100 let blob_id = self.blob_id;
101
102 let blob_impl = self.global().serialize_blob(&blob_id);
104
105 let new_blob_id = blob_impl.blob_id();
107
108 Ok((new_blob_id, blob_impl))
109 }
110
111 fn deserialize(
113 owner: &GlobalScope,
114 serialized: BlobImpl,
115 can_gc: CanGc,
116 ) -> Result<DomRoot<Self>, ()> {
117 let deserialized_blob = Blob::new(owner, serialized, can_gc);
118 Ok(deserialized_blob)
119 }
120
121 fn serialized_storage<'a>(
122 reader: StructuredData<'a, '_>,
123 ) -> &'a mut Option<FxHashMap<BlobId, Self::Data>> {
124 match reader {
125 StructuredData::Reader(r) => &mut r.blob_impls,
126 StructuredData::Writer(w) => &mut w.blobs,
127 }
128 }
129}
130
131#[expect(unsafe_code)]
134pub(crate) fn blob_parts_to_bytes(
135 mut blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>,
136) -> Result<Vec<u8>, ()> {
137 let mut ret = vec![];
138 for blobpart in &mut blobparts {
139 match blobpart {
140 ArrayBufferOrArrayBufferViewOrBlobOrString::String(s) => {
141 ret.extend_from_slice(&s.as_bytes());
142 },
143 ArrayBufferOrArrayBufferViewOrBlobOrString::Blob(b) => {
144 let bytes = b.get_bytes().unwrap_or(vec![]);
145 ret.extend(bytes);
146 },
147 ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBuffer(a) => unsafe {
148 let bytes = a.as_slice();
149 ret.extend(bytes);
150 },
151 ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBufferView(a) => unsafe {
152 let bytes = a.as_slice();
153 ret.extend(bytes);
154 },
155 }
156 }
157
158 Ok(ret)
159}
160
161impl BlobMethods<crate::DomTypeHolder> for Blob {
162 #[expect(non_snake_case)]
164 fn Constructor(
165 global: &GlobalScope,
166 proto: Option<HandleObject>,
167 can_gc: CanGc,
168 blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>,
169 blobPropertyBag: &BlobBinding::BlobPropertyBag,
170 ) -> Fallible<DomRoot<Blob>> {
171 let bytes: Vec<u8> = match blobParts {
172 None => Vec::new(),
173 Some(blobparts) => match blob_parts_to_bytes(blobparts) {
174 Ok(bytes) => bytes,
175 Err(_) => return Err(Error::InvalidCharacter(None)),
176 },
177 };
178
179 let type_string = normalize_type_string(&blobPropertyBag.type_.str());
180 let blob_impl = BlobImpl::new_from_bytes(bytes, type_string);
181
182 Ok(Blob::new_with_proto(global, proto, blob_impl, can_gc))
183 }
184
185 fn Size(&self) -> u64 {
187 self.global().get_blob_size(&self.blob_id)
188 }
189
190 fn Type(&self) -> DOMString {
192 DOMString::from(self.type_string())
193 }
194
195 fn Stream(&self, can_gc: CanGc) -> Fallible<DomRoot<ReadableStream>> {
197 self.get_stream(can_gc)
198 }
199
200 fn Slice(
202 &self,
203 start: Option<i64>,
204 end: Option<i64>,
205 content_type: Option<DOMString>,
206 can_gc: CanGc,
207 ) -> DomRoot<Blob> {
208 let global = self.global();
209 let type_string = normalize_type_string(&content_type.unwrap_or_default().str());
210
211 let (parent, range) = match *global.get_blob_data(&self.blob_id) {
214 BlobData::Sliced(grandparent, parent_range) => {
215 let range = RelativePos {
216 start: parent_range.start + start.unwrap_or_default(),
217 end: end.map(|end| end + parent_range.start).or(parent_range.end),
218 };
219 (grandparent, range)
220 },
221 _ => (self.blob_id, RelativePos::from_opts(start, end)),
222 };
223
224 let blob_impl = BlobImpl::new_sliced(range, parent, type_string);
225 Blob::new(&global, blob_impl, can_gc)
226 }
227
228 fn Text(&self, can_gc: CanGc) -> Rc<Promise> {
230 let global = self.global();
231 let in_realm_proof = AlreadyInRealm::assert::<crate::DomTypeHolder>();
232 let p = Promise::new_in_current_realm(InRealm::Already(&in_realm_proof), can_gc);
233 let id = self.get_blob_url_id();
234 global.read_file_async(
235 id,
236 p.clone(),
237 Box::new(|promise, bytes| match bytes {
238 Ok(b) => {
239 let (text, _, _) = UTF_8.decode(&b);
240 let text = DOMString::from(text);
241 promise.resolve_native(&text, CanGc::note());
242 },
243 Err(e) => {
244 promise.reject_error(e, CanGc::note());
245 },
246 }),
247 );
248 p
249 }
250
251 fn ArrayBuffer(&self, in_realm: InRealm, can_gc: CanGc) -> Rc<Promise> {
253 let cx = GlobalScope::get_cx();
254 let promise = Promise::new_in_current_realm(in_realm, can_gc);
255
256 let stream = self.get_stream(can_gc);
258
259 let reader = match stream.and_then(|s| s.acquire_default_reader(can_gc)) {
262 Ok(reader) => reader,
263 Err(error) => {
264 promise.reject_error(error, can_gc);
265 return promise;
266 },
267 };
268
269 let success_promise = promise.clone();
271 let failure_promise = promise.clone();
272 reader.read_all_bytes(
273 cx,
274 Rc::new(move |bytes| {
275 rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
276 let array_buffer = create_buffer_source::<ArrayBufferU8>(
279 cx,
280 bytes,
281 js_object.handle_mut(),
282 can_gc,
283 )
284 .expect("Converting input to ArrayBufferU8 should never fail");
285 success_promise.resolve_native(&array_buffer, can_gc);
286 }),
287 Rc::new(move |cx, value| {
288 failure_promise.reject(cx, value, can_gc);
289 }),
290 can_gc,
291 );
292
293 promise
294 }
295
296 fn Bytes(&self, in_realm: InRealm, can_gc: CanGc) -> Rc<Promise> {
298 let cx = GlobalScope::get_cx();
299 let p = Promise::new_in_current_realm(in_realm, can_gc);
300
301 let stream = self.get_stream(can_gc);
303
304 let reader = match stream.and_then(|s| s.acquire_default_reader(can_gc)) {
307 Ok(r) => r,
308 Err(e) => {
309 p.reject_error(e, can_gc);
310 return p;
311 },
312 };
313
314 let p_success = p.clone();
316 let p_failure = p.clone();
317 reader.read_all_bytes(
318 cx,
319 Rc::new(move |bytes| {
320 rooted!(in(*cx) let mut js_object = ptr::null_mut::<JSObject>());
321 let arr = create_buffer_source::<Uint8>(cx, bytes, js_object.handle_mut(), can_gc)
322 .expect("Converting input to uint8 array should never fail");
323 p_success.resolve_native(&arr, can_gc);
324 }),
325 Rc::new(move |cx, v| {
326 p_failure.reject(cx, v, can_gc);
327 }),
328 can_gc,
329 );
330 p
331 }
332}
333
334pub(crate) fn normalize_type_string(s: &str) -> String {
340 if is_ascii_printable(s) {
341 s.to_ascii_lowercase()
342 } else {
346 "".to_string()
347 }
348}
349
350fn is_ascii_printable(string: &str) -> bool {
351 string.chars().all(|c| ('\x20'..='\x7E').contains(&c))
354}