Reduce indexing boilerplate for serializable/transferrable objects. (#36624)

Rather than creating unique types for each pipeline-namespaced index
type (eg. MessagePortId, DomExceptionId, etc.), we can create a generic
common type that uses a marker to prevent type confusion. This change
allows us to reduce the boilerplate code required when implementing
serializable/transferable interfaces, since the structured clone
implementation can rely on the common type.

Testing: Existing WPT tests for serialization and transferring provide
coverage.

---------

Signed-off-by: Josh Matthews <josh@joshmatthews.net>
This commit is contained in:
Josh Matthews 2025-04-21 22:02:02 -04:00 committed by GitHub
parent 0b8645d422
commit 7b16ae26b4
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
13 changed files with 170 additions and 337 deletions

View file

@ -6,9 +6,8 @@
//! (<https://html.spec.whatwg.org/multipage/#serializable-objects>).
use std::collections::HashMap;
use std::num::NonZeroU32;
use base::id::PipelineNamespaceId;
use base::id::{Index, NamespaceIndex, PipelineNamespaceId};
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
@ -25,9 +24,9 @@ pub(crate) struct StorageKey {
}
impl StorageKey {
pub(crate) fn new(name_space: PipelineNamespaceId, index: NonZeroU32) -> StorageKey {
let name_space = name_space.0.to_ne_bytes();
let index = index.get().to_ne_bytes();
pub(crate) fn new<T>(index: NamespaceIndex<T>) -> StorageKey {
let name_space = index.namespace_id.0.to_ne_bytes();
let index = index.index.0.get().to_ne_bytes();
StorageKey {
index: u32::from_ne_bytes(index),
name_space: u32::from_ne_bytes(name_space),
@ -35,11 +34,13 @@ impl StorageKey {
}
}
pub(crate) trait IntoStorageKey
where
Self: Sized,
{
fn into_storage_key(self) -> StorageKey;
impl<T> From<StorageKey> for NamespaceIndex<T> {
fn from(key: StorageKey) -> NamespaceIndex<T> {
NamespaceIndex {
namespace_id: PipelineNamespaceId(key.name_space),
index: Index::new(key.index).expect("Index must not be zero"),
}
}
}
/// Interface for serializable platform objects.
@ -48,11 +49,11 @@ pub(crate) trait Serializable: DomObject
where
Self: Sized,
{
type Id: Copy + Eq + std::hash::Hash + IntoStorageKey + From<StorageKey>;
type Index: Copy + Eq + std::hash::Hash;
type Data;
/// <https://html.spec.whatwg.org/multipage/#serialization-steps>
fn serialize(&self) -> Result<(Self::Id, Self::Data), ()>;
fn serialize(&self) -> Result<(NamespaceIndex<Self::Index>, Self::Data), ()>;
/// <https://html.spec.whatwg.org/multipage/#deserialization-steps>
fn deserialize(
owner: &GlobalScope,
@ -64,7 +65,9 @@ where
/// Returns the field of [StructuredDataReader]/[StructuredDataWriter] that
/// should be used to read/store serialized instances of this type.
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>>;
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<NamespaceIndex<Self::Index>, Self::Data>>;
/// Returns the field of [StructuredDataReader] that should be used to store
/// deserialized instances of this type.

View file

@ -6,11 +6,12 @@
use std::collections::HashMap;
use std::ffi::CStr;
use std::num::NonZeroU32;
use std::os::raw;
use std::ptr;
use base::id::{BlobId, DomExceptionId, DomPointId, MessagePortId, PipelineNamespaceId};
use base::id::{
BlobId, DomExceptionId, DomPointId, Index, MessagePortId, NamespaceIndex, PipelineNamespaceId,
};
use constellation_traits::{
BlobImpl, DomException, DomPoint, MessagePortImpl, Serializable as SerializableInterface,
StructuredSerializedData, Transferrable as TransferrableInterface,
@ -34,8 +35,8 @@ use strum::IntoEnumIterator;
use crate::dom::bindings::conversions::{ToJSValConvertible, root_from_object};
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::serializable::{IntoStorageKey, Serializable, StorageKey};
use crate::dom::bindings::transferable::{ExtractComponents, IdFromComponents, Transferable};
use crate::dom::bindings::serializable::{Serializable, StorageKey};
use crate::dom::bindings::transferable::Transferable;
use crate::dom::blob::Blob;
use crate::dom::dompoint::DOMPoint;
use crate::dom::dompointreadonly::DOMPointReadOnly;
@ -120,7 +121,7 @@ unsafe fn read_object<T: Serializable>(
// 1. Re-build the key for the storage location
// of the serialized object.
let id = T::Id::from(storage_key);
let id: NamespaceIndex<T::Index> = storage_key.into();
// 2. Get the transferred object from its storage, using the key.
let objects = T::serialized_storage(StructuredData::Reader(sc_reader));
@ -155,7 +156,7 @@ unsafe fn write_object<T: Serializable>(
let objects = T::serialized_storage(StructuredData::Writer(sc_writer))
.get_or_insert_with(HashMap::new);
objects.insert(new_id, serialized);
let storage_key = new_id.into_storage_key();
let storage_key = StorageKey::new(new_id);
assert!(JS_WriteUint32Pair(
w,
@ -282,13 +283,13 @@ fn receive_object<T: Transferable>(
.try_into()
.expect("name_space to be a slice of four."),
));
let id = <T::Id as IdFromComponents>::from(
let id: NamespaceIndex<T::Index> = NamespaceIndex {
namespace_id,
NonZeroU32::new(u32::from_ne_bytes(
index: Index::new(u32::from_ne_bytes(
index.try_into().expect("index to be a slice of four."),
))
.expect("Index to be non-zero"),
);
};
// 2. Get the transferred object from its storage, using the key.
let storage = T::serialized_storage(StructuredData::Reader(sc_reader));
@ -356,11 +357,10 @@ unsafe fn try_transfer<T: Transferable + IDLInterface>(
.get_or_insert_with(HashMap::new);
objects.insert(id, object);
let (PipelineNamespaceId(name_space), index) = id.components();
let index = index.get();
let index = id.index.0.get();
let mut big: [u8; 8] = [0; 8];
let name_space = name_space.to_ne_bytes();
let name_space = id.namespace_id.0.to_ne_bytes();
let index = index.to_ne_bytes();
let (left, right) = big.split_at_mut(4);

View file

@ -6,44 +6,34 @@
//! (<https://html.spec.whatwg.org/multipage/#transferable-objects>).
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::hash::Hash;
use base::id::PipelineNamespaceId;
use base::id::NamespaceIndex;
use crate::dom::bindings::reflector::DomObject;
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::structuredclone::{StructuredData, StructuredDataReader};
use crate::dom::globalscope::GlobalScope;
pub(crate) trait IdFromComponents
where
Self: Sized,
{
fn from(namespace_id: PipelineNamespaceId, index: NonZeroU32) -> Self;
}
pub(crate) trait ExtractComponents {
fn components(&self) -> (PipelineNamespaceId, NonZeroU32);
}
pub(crate) trait Transferable: DomObject
where
Self: Sized,
{
type Id: Eq + std::hash::Hash + Copy + IdFromComponents + ExtractComponents;
type Index: Copy + Eq + Hash;
type Data;
fn can_transfer(&self) -> bool {
true
}
fn transfer(&self) -> Result<(Self::Id, Self::Data), ()>;
fn transfer(&self) -> Result<(NamespaceIndex<Self::Index>, Self::Data), ()>;
fn transfer_receive(
owner: &GlobalScope,
id: Self::Id,
id: NamespaceIndex<Self::Index>,
serialized: Self::Data,
) -> Result<DomRoot<Self>, ()>;
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>>;
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<NamespaceIndex<Self::Index>, Self::Data>>;
fn deserialized_storage(reader: &mut StructuredDataReader) -> &mut Option<Vec<DomRoot<Self>>>;
}

View file

@ -3,11 +3,10 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::ptr;
use std::rc::Rc;
use base::id::{BlobId, BlobIndex, PipelineNamespaceId};
use base::id::{BlobId, BlobIndex};
use constellation_traits::BlobImpl;
use dom_struct::dom_struct;
use encoding_rs::UTF_8;
@ -25,7 +24,7 @@ use crate::dom::bindings::codegen::UnionTypes::ArrayBufferOrArrayBufferViewOrBlo
use crate::dom::bindings::error::{Error, Fallible};
use crate::dom::bindings::reflector::{DomGlobal, Reflector, reflect_dom_object_with_proto};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::serializable::{IntoStorageKey, Serializable, StorageKey};
use crate::dom::bindings::serializable::{Serializable, StorageKey};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::structuredclone::{StructuredData, StructuredDataReader};
use crate::dom::globalscope::GlobalScope;
@ -94,7 +93,7 @@ impl Blob {
}
impl Serializable for Blob {
type Id = BlobId;
type Index = BlobIndex;
type Data = BlobImpl;
/// <https://w3c.github.io/FileAPI/#ref-for-serialization-steps>
@ -120,9 +119,7 @@ impl Serializable for Blob {
Ok(deserialized_blob)
}
fn serialized_storage(
reader: StructuredData<'_>,
) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(reader: StructuredData<'_>) -> &mut Option<HashMap<BlobId, Self::Data>> {
match reader {
StructuredData::Reader(r) => &mut r.blob_impls,
StructuredData::Writer(w) => &mut w.blobs,
@ -136,26 +133,6 @@ impl Serializable for Blob {
}
}
impl From<StorageKey> for BlobId {
fn from(storage_key: StorageKey) -> BlobId {
let namespace_id = PipelineNamespaceId(storage_key.name_space);
let index =
BlobIndex(NonZeroU32::new(storage_key.index).expect("Deserialized blob index is zero"));
BlobId {
namespace_id,
index,
}
}
}
impl IntoStorageKey for BlobId {
fn into_storage_key(self) -> StorageKey {
let BlobIndex(index) = self.index;
StorageKey::new(self.namespace_id, index)
}
}
/// Extract bytes from BlobParts, used by Blob and File constructor
/// <https://w3c.github.io/FileAPI/#constructorBlob>
#[allow(unsafe_code)]

View file

@ -3,9 +3,8 @@
* file, You can obtain one at https://mozilla.org/MPL/2.0/. */
use std::collections::HashMap;
use std::num::NonZeroU32;
use base::id::{DomExceptionId, DomExceptionIndex, PipelineNamespaceId};
use base::id::{DomExceptionId, DomExceptionIndex};
use constellation_traits::DomException;
use dom_struct::dom_struct;
use js::rust::HandleObject;
@ -18,7 +17,7 @@ use crate::dom::bindings::reflector::{
Reflector, reflect_dom_object, reflect_dom_object_with_proto,
};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::serializable::{IntoStorageKey, Serializable, StorageKey};
use crate::dom::bindings::serializable::{Serializable, StorageKey};
use crate::dom::bindings::str::DOMString;
use crate::dom::bindings::structuredclone::{StructuredData, StructuredDataReader};
use crate::dom::globalscope::GlobalScope;
@ -224,11 +223,11 @@ impl DOMExceptionMethods<crate::DomTypeHolder> for DOMException {
}
impl Serializable for DOMException {
type Id = DomExceptionId;
type Index = DomExceptionIndex;
type Data = DomException;
// https://webidl.spec.whatwg.org/#idl-DOMException
fn serialize(&self) -> Result<(Self::Id, Self::Data), ()> {
fn serialize(&self) -> Result<(DomExceptionId, Self::Data), ()> {
let serialized = DomException {
message: self.message.to_string(),
name: self.name.to_string(),
@ -253,7 +252,9 @@ impl Serializable for DOMException {
))
}
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<DomExceptionId, Self::Data>> {
match data {
StructuredData::Reader(reader) => &mut reader.exceptions,
StructuredData::Writer(writer) => &mut writer.exceptions,
@ -266,24 +267,3 @@ impl Serializable for DOMException {
&mut reader.dom_exceptions
}
}
impl From<StorageKey> for DomExceptionId {
fn from(storage_key: StorageKey) -> DomExceptionId {
let namespace_id = PipelineNamespaceId(storage_key.name_space);
let index = DomExceptionIndex(
NonZeroU32::new(storage_key.index).expect("Deserialized exception index is zero"),
);
DomExceptionId {
namespace_id,
index,
}
}
}
impl IntoStorageKey for DomExceptionId {
fn into_storage_key(self) -> StorageKey {
let DomExceptionIndex(index) = self.index;
StorageKey::new(self.namespace_id, index)
}
}

View file

@ -4,7 +4,7 @@
use std::collections::HashMap;
use base::id::DomPointId;
use base::id::{DomPointId, DomPointIndex};
use constellation_traits::DomPoint;
use dom_struct::dom_struct;
use js::rust::HandleObject;
@ -132,10 +132,10 @@ impl DOMPointMethods<crate::DomTypeHolder> for DOMPoint {
}
impl Serializable for DOMPoint {
type Id = DomPointId;
type Index = DomPointIndex;
type Data = DomPoint;
fn serialize(&self) -> Result<(Self::Id, Self::Data), ()> {
fn serialize(&self) -> Result<(DomPointId, Self::Data), ()> {
let serialized = DomPoint {
x: self.X(),
y: self.Y(),
@ -163,7 +163,9 @@ impl Serializable for DOMPoint {
))
}
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<DomPointId, Self::Data>> {
match data {
StructuredData::Reader(reader) => &mut reader.points,
StructuredData::Writer(writer) => &mut writer.points,

View file

@ -4,9 +4,8 @@
use std::cell::Cell;
use std::collections::HashMap;
use std::num::NonZeroU32;
use base::id::{DomPointId, DomPointIndex, PipelineNamespaceId};
use base::id::{DomPointId, DomPointIndex};
use constellation_traits::DomPoint;
use dom_struct::dom_struct;
use js::rust::HandleObject;
@ -16,7 +15,7 @@ use crate::dom::bindings::codegen::Bindings::DOMPointReadOnlyBinding::DOMPointRe
use crate::dom::bindings::error::Fallible;
use crate::dom::bindings::reflector::{Reflector, reflect_dom_object_with_proto};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::serializable::{IntoStorageKey, Serializable, StorageKey};
use crate::dom::bindings::serializable::{Serializable, StorageKey};
use crate::dom::bindings::structuredclone::{StructuredData, StructuredDataReader};
use crate::dom::globalscope::GlobalScope;
use crate::script_runtime::CanGc;
@ -142,10 +141,10 @@ impl DOMPointWriteMethods for DOMPointReadOnly {
}
impl Serializable for DOMPointReadOnly {
type Id = DomPointId;
type Index = DomPointIndex;
type Data = DomPoint;
fn serialize(&self) -> Result<(Self::Id, Self::Data), ()> {
fn serialize(&self) -> Result<(DomPointId, Self::Data), ()> {
let serialized = DomPoint {
x: self.x.get(),
y: self.y.get(),
@ -173,7 +172,9 @@ impl Serializable for DOMPointReadOnly {
))
}
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<DomPointId, Self::Data>> {
match data {
StructuredData::Reader(r) => &mut r.points,
StructuredData::Writer(w) => &mut w.points,
@ -186,24 +187,3 @@ impl Serializable for DOMPointReadOnly {
&mut reader.points_read_only
}
}
impl From<StorageKey> for DomPointId {
fn from(storage_key: StorageKey) -> DomPointId {
let namespace_id = PipelineNamespaceId(storage_key.name_space);
let index = DomPointIndex(
NonZeroU32::new(storage_key.index).expect("Deserialized point index is zero"),
);
DomPointId {
namespace_id,
index,
}
}
}
impl IntoStorageKey for DomPointId {
fn into_storage_key(self) -> StorageKey {
let DomPointIndex(index) = self.index;
StorageKey::new(self.namespace_id, index)
}
}

View file

@ -4,11 +4,10 @@
use std::cell::{Cell, RefCell};
use std::collections::HashMap;
use std::num::NonZeroU32;
use std::ptr;
use std::rc::Rc;
use base::id::{MessagePortId, MessagePortIndex, PipelineNamespaceId};
use base::id::{MessagePortId, MessagePortIndex};
use constellation_traits::{MessagePortImpl, PortMessageTask};
use dom_struct::dom_struct;
use js::jsapi::{Heap, JS_NewObject, JSObject};
@ -26,7 +25,7 @@ use crate::dom::bindings::reflector::{DomGlobal, reflect_dom_object};
use crate::dom::bindings::root::DomRoot;
use crate::dom::bindings::structuredclone::{self, StructuredData, StructuredDataReader};
use crate::dom::bindings::trace::RootedTraceableBox;
use crate::dom::bindings::transferable::{ExtractComponents, IdFromComponents, Transferable};
use crate::dom::bindings::transferable::Transferable;
use crate::dom::bindings::utils::set_dictionary_property;
use crate::dom::eventtarget::EventTarget;
use crate::dom::globalscope::GlobalScope;
@ -239,7 +238,7 @@ impl MessagePort {
}
impl Transferable for MessagePort {
type Id = MessagePortId;
type Index = MessagePortIndex;
type Data = MessagePortImpl;
/// <https://html.spec.whatwg.org/multipage/#message-ports:transfer-steps>
@ -269,7 +268,9 @@ impl Transferable for MessagePort {
Ok(transferred_port)
}
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<MessagePortId, Self::Data>> {
match data {
StructuredData::Reader(r) => &mut r.port_impls,
StructuredData::Writer(w) => &mut w.ports,
@ -281,21 +282,6 @@ impl Transferable for MessagePort {
}
}
impl IdFromComponents for MessagePortId {
fn from(namespace_id: PipelineNamespaceId, index: NonZeroU32) -> MessagePortId {
MessagePortId {
namespace_id,
index: MessagePortIndex(index),
}
}
}
impl ExtractComponents for MessagePortId {
fn components(&self) -> (PipelineNamespaceId, NonZeroU32) {
(self.namespace_id, self.index.0)
}
}
impl MessagePortMethods<crate::DomTypeHolder> for MessagePort {
/// <https://html.spec.whatwg.org/multipage/#dom-messageport-postmessage>
fn PostMessage(

View file

@ -8,6 +8,8 @@ use std::ptr::{self};
use std::rc::Rc;
use std::collections::HashMap;
use base::id::{MessagePortId, MessagePortIndex};
use constellation_traits::MessagePortImpl;
use dom_struct::dom_struct;
use js::conversions::ToJSValConvertible;
use js::jsapi::{Heap, JSObject};
@ -56,8 +58,6 @@ use crate::js::conversions::FromJSValConvertible;
use crate::realms::{enter_realm, InRealm};
use crate::script_runtime::{CanGc, JSContext as SafeJSContext};
use crate::dom::promisenativehandler::{Callback, PromiseNativeHandler};
use base::id::MessagePortId;
use constellation_traits::MessagePortImpl;
use crate::dom::bindings::transferable::Transferable;
use crate::dom::bindings::structuredclone::{StructuredData, StructuredDataReader};
@ -2179,7 +2179,7 @@ pub(crate) fn get_read_promise_bytes(
/// <https://streams.spec.whatwg.org/#rs-transfer>
impl Transferable for ReadableStream {
type Id = MessagePortId;
type Index = MessagePortIndex;
type Data = MessagePortImpl;
/// <https://streams.spec.whatwg.org/#ref-for-readablestream%E2%91%A1%E2%91%A0>
@ -2247,7 +2247,9 @@ impl Transferable for ReadableStream {
}
/// Note: we are relying on the port transfer, so the data returned here are related to the port.
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<MessagePortId, Self::Data>> {
match data {
StructuredData::Reader(r) => &mut r.port_impls,
StructuredData::Writer(w) => &mut w.ports,

View file

@ -8,7 +8,7 @@ use std::mem;
use std::ptr::{self};
use std::rc::Rc;
use base::id::MessagePortId;
use base::id::{MessagePortId, MessagePortIndex};
use constellation_traits::MessagePortImpl;
use dom_struct::dom_struct;
use js::jsapi::{Heap, JSObject};
@ -1114,7 +1114,7 @@ impl CrossRealmTransformWritable {
/// <https://streams.spec.whatwg.org/#ws-transfer>
impl Transferable for WritableStream {
type Id = MessagePortId;
type Index = MessagePortIndex;
type Data = MessagePortImpl;
/// <https://streams.spec.whatwg.org/#ref-for-writablestream%E2%91%A0%E2%91%A4>
@ -1182,7 +1182,9 @@ impl Transferable for WritableStream {
}
/// Note: we are relying on the port transfer, so the data returned here are related to the port.
fn serialized_storage(data: StructuredData<'_>) -> &mut Option<HashMap<Self::Id, Self::Data>> {
fn serialized_storage(
data: StructuredData<'_>,
) -> &mut Option<HashMap<MessagePortId, Self::Data>> {
match data {
StructuredData::Reader(r) => &mut r.port_impls,
StructuredData::Writer(w) => &mut w.ports,