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    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}
55
56impl StructuredSerializedData {
57    fn is_empty(&self, val: Transferrable) -> bool {
58        fn is_field_empty<K, V>(field: &Option<FxHashMap<K, V>>) -> bool {
59            field.as_ref().is_none_or(|h| h.is_empty())
60        }
61        match val {
62            Transferrable::ImageBitmap => is_field_empty(&self.transferred_image_bitmaps),
63            Transferrable::MessagePort => is_field_empty(&self.ports),
64            Transferrable::OffscreenCanvas => is_field_empty(&self.offscreen_canvases),
65            Transferrable::ReadableStream => is_field_empty(&self.ports),
66            Transferrable::WritableStream => is_field_empty(&self.ports),
67            Transferrable::TransformStream => is_field_empty(&self.ports),
68        }
69    }
70
71    /// Clone all values of the same type stored in this StructuredSerializedData
72    /// into another instance.
73    fn clone_all_of_type<T: BroadcastClone>(&self, cloned: &mut StructuredSerializedData) {
74        let existing = T::source(self);
75        let Some(existing) = existing else { return };
76        let mut clones = FxHashMap::with_capacity_and_hasher(existing.len(), FxBuildHasher);
77
78        for (original_id, obj) in existing.iter() {
79            if let Some(clone) = obj.clone_for_broadcast() {
80                clones.insert(*original_id, clone);
81            }
82        }
83
84        *T::destination(cloned) = Some(clones);
85    }
86
87    /// Clone the serialized data for use with broadcast-channels.
88    pub fn clone_for_broadcast(&self) -> StructuredSerializedData {
89        for transferrable in Transferrable::iter() {
90            if !self.is_empty(transferrable) {
91                // Not panicking only because this is called from the constellation.
92                warn!(
93                    "Attempt to broadcast structured serialized data including {:?} (should never happen).",
94                    transferrable,
95                );
96            }
97        }
98
99        let serialized = self.serialized.clone();
100
101        let mut cloned = StructuredSerializedData {
102            serialized,
103            ..Default::default()
104        };
105
106        for serializable in Serializable::iter() {
107            let clone_impl = serializable.clone_values();
108            clone_impl(self, &mut cloned);
109        }
110
111        cloned
112    }
113}