constellation_traits/structured_data/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! This module contains implementations of structured data as described in
6//! <https://html.spec.whatwg.org/multipage/#safe-passing-of-structured-data>
7
8mod serializable;
9mod transferable;
10
11use base::id::{
12    BlobId, DomExceptionId, DomMatrixId, DomPointId, DomQuadId, DomRectId, ImageBitmapId,
13    ImageDataId, MessagePortId, OffscreenCanvasId, QuotaExceededErrorId,
14};
15use log::warn;
16use malloc_size_of_derive::MallocSizeOf;
17use rustc_hash::{FxBuildHasher, FxHashMap};
18use serde::{Deserialize, Serialize};
19pub use serializable::*;
20use strum::IntoEnumIterator;
21pub use transferable::*;
22
23/// A data-holder for serialized data and transferred objects.
24/// <https://html.spec.whatwg.org/multipage/#structuredserializewithtransfer>
25#[derive(Debug, Default, Deserialize, MallocSizeOf, Serialize)]
26pub struct StructuredSerializedData {
27    /// Data serialized by SpiderMonkey.
28    pub serialized: Vec<u8>,
29    /// Serialized in a structured callback,
30    pub blobs: Option<FxHashMap<BlobId, BlobImpl>>,
31    /// Serialized point objects.
32    pub points: Option<FxHashMap<DomPointId, DomPoint>>,
33    /// Serialized rect objects.
34    pub rects: Option<FxHashMap<DomRectId, DomRect>>,
35    /// Serialized quad objects.
36    pub quads: Option<FxHashMap<DomQuadId, DomQuad>>,
37    /// Serialized matrix objects.
38    pub matrices: Option<FxHashMap<DomMatrixId, DomMatrix>>,
39    /// Serialized exception objects.
40    pub exceptions: Option<FxHashMap<DomExceptionId, DomException>>,
41    /// Serialized quota exceeded errors.
42    pub quota_exceeded_errors:
43        Option<FxHashMap<QuotaExceededErrorId, SerializableQuotaExceededError>>,
44    /// Transferred objects.
45    pub ports: Option<FxHashMap<MessagePortId, MessagePortImpl>>,
46    /// Transform streams transferred objects.
47    pub transform_streams: Option<FxHashMap<MessagePortId, TransformStreamData>>,
48    /// Serialized image bitmap objects.
49    pub image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
50    /// Transferred image bitmap objects.
51    pub transferred_image_bitmaps: Option<FxHashMap<ImageBitmapId, SerializableImageBitmap>>,
52    /// Transferred offscreen canvas objects.
53    pub offscreen_canvases: Option<FxHashMap<OffscreenCanvasId, TransferableOffscreenCanvas>>,
54    /// Serialized image data objects.
55    pub image_data: Option<FxHashMap<ImageDataId, SerializableImageData>>,
56}
57
58impl StructuredSerializedData {
59    fn is_empty(&self, val: Transferrable) -> bool {
60        fn is_field_empty<K, V>(field: &Option<FxHashMap<K, V>>) -> bool {
61            field.as_ref().is_none_or(|h| h.is_empty())
62        }
63        match val {
64            Transferrable::ImageBitmap => is_field_empty(&self.transferred_image_bitmaps),
65            Transferrable::MessagePort => is_field_empty(&self.ports),
66            Transferrable::OffscreenCanvas => is_field_empty(&self.offscreen_canvases),
67            Transferrable::ReadableStream => is_field_empty(&self.ports),
68            Transferrable::WritableStream => is_field_empty(&self.ports),
69            Transferrable::TransformStream => is_field_empty(&self.ports),
70        }
71    }
72
73    /// Clone all values of the same type stored in this StructuredSerializedData
74    /// into another instance.
75    fn clone_all_of_type<T: BroadcastClone>(&self, cloned: &mut StructuredSerializedData) {
76        let existing = T::source(self);
77        let Some(existing) = existing else { return };
78        let mut clones = FxHashMap::with_capacity_and_hasher(existing.len(), FxBuildHasher);
79
80        for (original_id, obj) in existing.iter() {
81            if let Some(clone) = obj.clone_for_broadcast() {
82                clones.insert(*original_id, clone);
83            }
84        }
85
86        *T::destination(cloned) = Some(clones);
87    }
88
89    /// Clone the serialized data for use with broadcast-channels.
90    pub fn clone_for_broadcast(&self) -> StructuredSerializedData {
91        for transferrable in Transferrable::iter() {
92            if !self.is_empty(transferrable) {
93                // Not panicking only because this is called from the constellation.
94                warn!(
95                    "Attempt to broadcast structured serialized data including {:?} (should never happen).",
96                    transferrable,
97                );
98            }
99        }
100
101        let serialized = self.serialized.clone();
102
103        let mut cloned = StructuredSerializedData {
104            serialized,
105            ..Default::default()
106        };
107
108        for serializable in Serializable::iter() {
109            let clone_impl = serializable.clone_values();
110            clone_impl(self, &mut cloned);
111        }
112
113        cloned
114    }
115}