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