Skip to main content

script_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 https://mozilla.org/MPL/2.0/. */
4
5use js::context::{JSContext, NoGC};
6use rustc_hash::FxHashMap;
7use servo_base::id::NamespaceIndex;
8
9use crate::DomTypes;
10use crate::reflector::DomObject;
11use crate::root::DomRoot;
12use crate::structuredclone::{MarkedAsSerializableInIdl, StructuredData};
13
14/// Interface for serializable platform objects.
15/// <https://html.spec.whatwg.org/multipage/#serializable>
16#[allow(clippy::result_unit_err)]
17pub trait Serializable<D: DomTypes>: DomObject + MarkedAsSerializableInIdl
18where
19    Self: Sized,
20{
21    type Index: Copy + Eq + std::hash::Hash;
22    type Data;
23
24    /// <https://html.spec.whatwg.org/multipage/#serialization-steps>
25    fn serialize(&self, no_gc: &NoGC) -> Result<(NamespaceIndex<Self::Index>, Self::Data), ()>;
26
27    /// <https://html.spec.whatwg.org/multipage/#deserialization-steps>
28    fn deserialize(
29        cx: &mut JSContext,
30        owner: &D::GlobalScope,
31        serialized: Self::Data,
32    ) -> Result<DomRoot<Self>, ()>
33    where
34        Self: Sized;
35
36    /// Returns the field of [StructuredDataReader]/[StructuredDataWriter] that
37    /// should be used to read/store serialized instances of this type.
38    fn serialized_storage<'a>(
39        data: StructuredData<'a, '_>,
40    ) -> &'a mut Option<FxHashMap<NamespaceIndex<Self::Index>, Self::Data>>;
41}