script/dom/bindings/
serializable.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 http://mozilla.org/MPL/2.0/. */
4
5//! Trait representing the concept of [serializable objects]
6//! (<https://html.spec.whatwg.org/multipage/#serializable-objects>).
7
8use base::id::{Index, NamespaceIndex, PipelineNamespaceId};
9use rustc_hash::FxHashMap;
10use script_bindings::structuredclone::MarkedAsSerializableInIdl;
11
12use crate::dom::bindings::reflector::DomObject;
13use crate::dom::bindings::root::DomRoot;
14use crate::dom::bindings::structuredclone::StructuredData;
15use crate::dom::globalscope::GlobalScope;
16use crate::script_runtime::CanGc;
17
18/// The key corresponding to the storage location
19/// of a serialized platform object stored in a StructuredDataHolder.
20#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
21pub(crate) struct StorageKey {
22    pub(crate) index: u32,
23    pub(crate) name_space: u32,
24}
25
26impl StorageKey {
27    pub(crate) fn new<T>(index: NamespaceIndex<T>) -> StorageKey {
28        let name_space = index.namespace_id.0.to_ne_bytes();
29        let index = index.index.0.get().to_ne_bytes();
30        StorageKey {
31            index: u32::from_ne_bytes(index),
32            name_space: u32::from_ne_bytes(name_space),
33        }
34    }
35}
36
37impl<T> From<StorageKey> for NamespaceIndex<T> {
38    fn from(key: StorageKey) -> NamespaceIndex<T> {
39        NamespaceIndex {
40            namespace_id: PipelineNamespaceId(key.name_space),
41            index: Index::new(key.index).expect("Index must not be zero"),
42        }
43    }
44}
45
46/// Interface for serializable platform objects.
47/// <https://html.spec.whatwg.org/multipage/#serializable>
48pub(crate) trait Serializable: DomObject + MarkedAsSerializableInIdl
49where
50    Self: Sized,
51{
52    type Index: Copy + Eq + std::hash::Hash;
53    type Data;
54
55    /// <https://html.spec.whatwg.org/multipage/#serialization-steps>
56    fn serialize(&self) -> Result<(NamespaceIndex<Self::Index>, Self::Data), ()>;
57    /// <https://html.spec.whatwg.org/multipage/#deserialization-steps>
58    fn deserialize(
59        owner: &GlobalScope,
60        serialized: Self::Data,
61        can_gc: CanGc,
62    ) -> Result<DomRoot<Self>, ()>
63    where
64        Self: Sized;
65
66    /// Returns the field of [StructuredDataReader]/[StructuredDataWriter] that
67    /// should be used to read/store serialized instances of this type.
68    fn serialized_storage<'a>(
69        data: StructuredData<'a, '_>,
70    ) -> &'a mut Option<FxHashMap<NamespaceIndex<Self::Index>, Self::Data>>;
71}
72
73pub(crate) fn assert_serializable<T: Serializable>() {}