1use std::ptr;
6use std::rc::Rc;
7
8use dom_struct::dom_struct;
9use encoding_rs::UTF_8;
10use js::context::{JSContext, NoGC};
11use js::jsapi::JSObject;
12use js::realm::CurrentRealm;
13use js::rust::HandleObject;
14use js::typedarray::{ArrayBufferU8, Uint8};
15use net_traits::filemanager_thread::RelativePos;
16use rustc_hash::FxHashMap;
17use script_bindings::reflector::{Reflector, reflect_weak_referenceable_dom_object_with_proto};
18use servo_base::id::{BlobId, BlobIndex};
19use servo_constellation_traits::{BlobData, BlobImpl};
20use uuid::Uuid;
21
22use crate::dom::bindings::buffer_source::{create_buffer_source, get_buffer_source_slice};
23use crate::dom::bindings::codegen::Bindings::BlobBinding;
24use crate::dom::bindings::codegen::Bindings::BlobBinding::BlobMethods;
25use crate::dom::bindings::codegen::UnionTypes::{
26 ArrayBufferOrArrayBufferViewOrBlobOrString, ArrayBufferViewOrArrayBuffer,
27};
28use crate::dom::bindings::error::{Error, Fallible};
29use crate::dom::bindings::reflector::DomGlobal;
30use crate::dom::bindings::root::DomRoot;
31use crate::dom::bindings::serializable::Serializable;
32use crate::dom::bindings::str::DOMString;
33use crate::dom::bindings::structuredclone::StructuredData;
34use crate::dom::encoding::textdecoderstream::TextDecoderStream;
35use crate::dom::globalscope::GlobalScope;
36use crate::dom::promise::Promise;
37use crate::dom::stream::readablestream::{ReadableStream, pipe_through};
38
39#[dom_struct]
41pub(crate) struct Blob {
42 reflector_: Reflector,
43 #[no_trace]
44 blob_id: BlobId,
45}
46
47impl Blob {
48 pub(crate) fn new(
49 cx: &mut JSContext,
50 global: &GlobalScope,
51 blob_impl: BlobImpl,
52 ) -> DomRoot<Blob> {
53 Self::new_with_proto(cx, global, None, blob_impl)
54 }
55
56 fn new_with_proto(
57 cx: &mut JSContext,
58 global: &GlobalScope,
59 proto: Option<HandleObject>,
60 blob_impl: BlobImpl,
61 ) -> DomRoot<Blob> {
62 let dom_blob = reflect_weak_referenceable_dom_object_with_proto(
63 cx,
64 Rc::new(Blob::new_inherited(&blob_impl)),
65 global,
66 proto,
67 );
68 global.track_blob(&dom_blob, blob_impl);
69 dom_blob
70 }
71
72 pub(crate) fn new_inherited(blob_impl: &BlobImpl) -> Blob {
73 Blob {
74 reflector_: Reflector::new(),
75 blob_id: blob_impl.blob_id(),
76 }
77 }
78
79 pub(crate) fn get_bytes(&self) -> Result<Vec<u8>, ()> {
81 self.global().get_blob_bytes(&self.blob_id)
82 }
83
84 pub(crate) fn type_string(&self) -> String {
86 self.global().get_blob_type_string(&self.blob_id)
87 }
88
89 pub(crate) fn get_blob_url_id(&self) -> Uuid {
92 self.global().get_blob_url_id(&self.blob_id)
93 }
94
95 pub(crate) fn get_stream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
97 self.global().get_blob_stream(cx, &self.blob_id)
98 }
99}
100
101impl Serializable for Blob {
102 type Index = BlobIndex;
103 type Data = BlobImpl;
104
105 fn serialize(&self, _no_gc: &NoGC) -> Result<(BlobId, BlobImpl), ()> {
107 let blob_id = self.blob_id;
108
109 let blob_impl = self.global().serialize_blob(&blob_id);
111
112 let new_blob_id = blob_impl.blob_id();
114
115 Ok((new_blob_id, blob_impl))
116 }
117
118 fn deserialize(
120 cx: &mut JSContext,
121 owner: &GlobalScope,
122 serialized: BlobImpl,
123 ) -> Result<DomRoot<Self>, ()> {
124 Ok(Blob::new(cx, owner, serialized))
125 }
126
127 fn serialized_storage<'a>(
128 reader: StructuredData<'a, '_>,
129 ) -> &'a mut Option<FxHashMap<BlobId, Self::Data>> {
130 match reader {
131 StructuredData::Reader(r) => &mut r.blob_impls,
132 StructuredData::Writer(w) => &mut w.blobs,
133 }
134 }
135}
136
137fn convert_line_endings_to_native(s: &[u8]) -> Vec<u8> {
139 let native_line_ending: &[u8] = if cfg!(target_os = "windows") {
140 b"\r\n"
144 } else {
145 b"\n"
147 };
148
149 let len = s.len();
150 let mut result = Vec::with_capacity(len);
152
153 let mut position = 0;
155
156 let collect_a_sequence_of_code_points = |position: &mut usize| -> &[u8] {
158 let start = *position;
159 while *position < len && s[*position] != b'\r' && s[*position] != b'\n' {
160 *position += 1;
161 }
162 &s[start..*position]
163 };
164
165 result.extend_from_slice(collect_a_sequence_of_code_points(&mut position));
169
170 while position < len {
172 let byte = s[position];
173 if byte == b'\r' {
175 result.extend_from_slice(native_line_ending);
177 position += 1;
179 if position < len && s[position] == b'\n' {
182 position += 1;
183 }
184 }
185 else if byte == b'\n' {
187 position += 1;
189 result.extend_from_slice(native_line_ending);
190 }
191
192 result.extend_from_slice(collect_a_sequence_of_code_points(&mut position));
196 }
197
198 result
200}
201
202pub(crate) fn process_blob_parts(
204 no_gc: &NoGC,
205 blobparts: Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>,
206 endings: BlobBinding::EndingType,
207) -> Result<Vec<u8>, ()> {
208 let mut bytes = vec![];
210 for blobpart in blobparts {
212 match blobpart {
213 ArrayBufferOrArrayBufferViewOrBlobOrString::String(s) => {
215 if endings == BlobBinding::EndingType::Native {
219 let converted = convert_line_endings_to_native(&s.as_bytes());
220 bytes.extend(converted);
222 } else {
223 bytes.extend_from_slice(&s.as_bytes());
225 }
226 },
227 ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBuffer(a) => {
231 let array_buffer = ArrayBufferViewOrArrayBuffer::ArrayBuffer(a);
232 bytes.extend_from_slice(get_buffer_source_slice(&array_buffer, no_gc));
233 },
234 ArrayBufferOrArrayBufferViewOrBlobOrString::ArrayBufferView(a) => {
235 let array_view = ArrayBufferViewOrArrayBuffer::ArrayBufferView(a);
236 bytes.extend_from_slice(get_buffer_source_slice(&array_view, no_gc));
237 },
238 ArrayBufferOrArrayBufferViewOrBlobOrString::Blob(b) => {
240 let blob_bytes = b.get_bytes().unwrap_or(vec![]);
241 bytes.extend(blob_bytes);
242 },
243 }
244 }
245
246 Ok(bytes)
248}
249
250impl BlobMethods<crate::DomTypeHolder> for Blob {
251 #[expect(non_snake_case)]
253 fn Constructor(
254 cx: &mut JSContext,
255 global: &GlobalScope,
256 proto: Option<HandleObject>,
257 blobParts: Option<Vec<ArrayBufferOrArrayBufferViewOrBlobOrString>>,
258 blobPropertyBag: &BlobBinding::BlobPropertyBag,
259 ) -> Fallible<DomRoot<Blob>> {
260 let bytes: Vec<u8> = match blobParts {
261 None => Vec::new(),
262 Some(blobparts) => {
263 match process_blob_parts(cx.no_gc(), blobparts, blobPropertyBag.endings) {
264 Ok(bytes) => bytes,
265 Err(_) => return Err(Error::InvalidCharacter(None)),
266 }
267 },
268 };
269
270 let type_string = normalize_type_string(&blobPropertyBag.type_.str());
271 let blob_impl = BlobImpl::new_from_bytes(bytes, type_string);
272
273 Ok(Blob::new_with_proto(cx, global, proto, blob_impl))
274 }
275
276 fn Size(&self) -> u64 {
278 self.global().get_blob_size(&self.blob_id)
279 }
280
281 fn Type(&self) -> DOMString {
283 DOMString::from(self.type_string())
284 }
285
286 fn Stream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
288 self.get_stream(cx)
289 }
290
291 fn TextStream(&self, cx: &mut JSContext) -> Fallible<DomRoot<ReadableStream>> {
293 let stream = self.get_stream(cx)?;
295 let decoder = TextDecoderStream::new_with_proto(
298 cx,
299 &self.global(),
300 None,
301 UTF_8,
302 false, false, )?;
305 Ok(pipe_through(&stream, cx, &self.global(), &decoder))
307 }
308
309 fn Slice(
311 &self,
312 cx: &mut JSContext,
313 start: Option<i64>,
314 end: Option<i64>,
315 content_type: Option<DOMString>,
316 ) -> DomRoot<Blob> {
317 let global = self.global();
318 let type_string = normalize_type_string(&content_type.unwrap_or_default().str());
319
320 let (parent, range) = match *global.get_blob_data(&self.blob_id) {
323 BlobData::Sliced(grandparent, parent_range) => {
324 let range = RelativePos {
325 start: parent_range.start + start.unwrap_or_default(),
326 end: end.map(|end| end + parent_range.start).or(parent_range.end),
327 };
328 (grandparent, range)
329 },
330 _ => (self.blob_id, RelativePos::from_opts(start, end)),
331 };
332
333 let blob_impl = BlobImpl::new_sliced(range, parent, type_string);
334 Blob::new(cx, &global, blob_impl)
335 }
336
337 fn Text(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
339 let global = self.global();
340 let p = Promise::new_in_realm(cx);
341 let id = self.get_blob_url_id();
342 global.read_file_async(
343 id,
344 p.clone(),
345 Box::new(|cx, promise, bytes| match bytes {
346 Ok(b) => {
347 let (text, _) = UTF_8.decode_with_bom_removal(&b);
348 let text = DOMString::from(text);
349 promise.resolve_native(cx, &text);
350 },
351 Err(e) => {
352 promise.reject_error(cx, e);
353 },
354 }),
355 );
356 p
357 }
358
359 fn ArrayBuffer(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
361 let promise = Promise::new_in_realm(cx);
362
363 let stream = self.get_stream(cx);
365
366 let reader = match stream.and_then(|s| s.acquire_default_reader(cx)) {
369 Ok(reader) => reader,
370 Err(error) => {
371 promise.reject_error(cx, error);
372 return promise;
373 },
374 };
375
376 let success_promise = promise.clone();
378 let failure_promise = promise.clone();
379 reader.read_all_bytes(
380 cx,
381 Rc::new(move |cx, bytes| {
382 rooted!(&in(cx) let mut js_object = ptr::null_mut::<JSObject>());
383 let array_buffer =
386 create_buffer_source::<ArrayBufferU8>(cx, bytes, js_object.handle_mut())
387 .expect("Converting input to ArrayBufferU8 should never fail");
388 success_promise.resolve_native(cx, &array_buffer);
389 }),
390 Rc::new(move |cx, value| {
391 failure_promise.reject(cx, value);
392 }),
393 );
394
395 promise
396 }
397
398 fn Bytes(&self, cx: &mut CurrentRealm) -> Rc<Promise> {
400 let p = Promise::new_in_realm(cx);
401
402 let stream = self.get_stream(cx);
404
405 let reader = match stream.and_then(|s| s.acquire_default_reader(cx)) {
408 Ok(r) => r,
409 Err(e) => {
410 p.reject_error(cx, e);
411 return p;
412 },
413 };
414
415 let p_success = p.clone();
417 let p_failure = p.clone();
418 reader.read_all_bytes(
419 cx,
420 Rc::new(move |cx, bytes| {
421 rooted!(&in(cx) let mut js_object = ptr::null_mut::<JSObject>());
422 let arr = create_buffer_source::<Uint8>(cx, bytes, js_object.handle_mut())
423 .expect("Converting input to uint8 array should never fail");
424 p_success.resolve_native(cx, &arr);
425 }),
426 Rc::new(move |cx, v| {
427 p_failure.reject(cx, v);
428 }),
429 );
430 p
431 }
432}
433
434pub(crate) fn normalize_type_string(s: &str) -> String {
440 if is_ascii_printable(s) {
441 s.to_ascii_lowercase()
442 } else {
446 "".to_string()
447 }
448}
449
450fn is_ascii_printable(string: &str) -> bool {
451 string.chars().all(|c| ('\x20'..='\x7E').contains(&c))
454}