Unverified Commit f603d4ab authored by Will Binns-Smith's avatar Will Binns-Smith Committed by GitHub

Serialize frozen collections by value only (#96686)

## What?

Serialize `FrozenMap` as a map and `FrozenSet` as a sequence instead of
exposing their internal fields.

Add JSON shape and round-trip coverage for both collection types.

## Why?

Keep serialized formats tied to collection semantics rather than their
current storage representation. This matches Serde's implementations for
`HashMap` and `HashSet`, which serialize through `collect_map` and
`collect_seq` respectively.

---------
Co-authored-by: 's avatarBenjamin Woodruff ‮ <github@benjam.info>
parent da2a69db
......@@ -9994,6 +9994,7 @@ dependencies = [
"bincode 2.0.1",
"indexmap 2.13.0",
"serde",
"serde_json",
]
[[package]]
......
......@@ -10,6 +10,7 @@ indexmap = { workspace = true }
serde = { workspace = true }
[dev-dependencies]
serde_json = { workspace = true }
[lints]
workspace = true
......@@ -4,12 +4,16 @@ use std::{
fmt::{self, Debug},
hash::BuildHasher,
iter::FusedIterator,
marker::PhantomData,
ops::{Bound, Index, RangeBounds},
};
use bincode::{BorrowDecode, Decode, Encode};
use indexmap::IndexMap;
use serde::{Deserialize, Serialize};
use serde::{
Deserialize, Serialize,
de::{MapAccess, Visitor},
};
/// A compact frozen (immutable) ordered map backed by a sorted boxed slice.
///
......@@ -38,7 +42,7 @@ use serde::{Deserialize, Serialize};
///
/// Overlapping keys encountered during construction preserve the last overlapping entry, matching
/// similar behavior for other maps in the standard library.
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Serialize, Deserialize)]
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)]
#[rustfmt::skip] // rustfmt breaks bincode's proc macro string processing
#[bincode(
decode_bounds = "K: Decode<__Context> + 'static, V: Decode<__Context> + 'static",
......@@ -49,6 +53,44 @@ pub struct FrozenMap<K, V> {
pub(crate) entries: Box<[(K, V)]>,
}
impl<K: Serialize, V: Serialize> Serialize for FrozenMap<K, V> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_map(self.iter())
}
}
impl<'de, K, V> Deserialize<'de> for FrozenMap<K, V>
where
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct MapVisitor<K, V>(PhantomData<(K, V)>);
impl<'de, K, V> Visitor<'de> for MapVisitor<K, V>
where
K: Deserialize<'de> + Ord,
V: Deserialize<'de>,
{
type Value = FrozenMap<K, V>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a map")
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut entries = Vec::with_capacity(map.size_hint().unwrap_or(0));
while let Some(entry) = map.next_entry()? {
entries.push(entry);
}
Ok(FrozenMap::from(entries))
}
}
deserializer.deserialize_map(MapVisitor(PhantomData))
}
}
impl<K, V> FrozenMap<K, V> {
/// Creates an empty [`FrozenMap`]. Does not perform any heap allocations.
pub fn new() -> Self {
......@@ -812,6 +854,18 @@ impl<K, V> Clone for Range<'_, K, V> {
mod tests {
use super::*;
#[test]
fn serde_uses_map_shape() {
let map = FrozenMap::from([("b", 2), ("a", 1)]);
let json = serde_json::to_string(&map).unwrap();
assert_eq!(json, r#"{"a":1,"b":2}"#);
assert_eq!(
serde_json::from_str::<FrozenMap<&str, i32>>(r#"{"b":2, "a":1}"#).unwrap(),
map
);
}
#[test]
fn test_empty() {
let map = FrozenMap::<i32, i32>::new();
......
......@@ -4,12 +4,16 @@ use std::{
fmt::{self, Debug},
hash::BuildHasher,
iter::FusedIterator,
marker::PhantomData,
ops::RangeBounds,
};
use bincode::{BorrowDecode, Decode, Encode};
use indexmap::IndexSet;
use serde::{Deserialize, Serialize};
use serde::{
Deserialize, Serialize,
de::{SeqAccess, Visitor},
};
use crate::map::{self, FrozenMap};
......@@ -37,7 +41,7 @@ use crate::map::{self, FrozenMap};
/// [`Vec`] or boxed slice. Because of limitations of the internal representation and Rust's memory
/// layout rules, the most efficient way to convert from these data structures is via an
/// [`Iterator`].
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode, Serialize, Deserialize)]
#[derive(Clone, PartialEq, Eq, Hash, PartialOrd, Ord, Encode, Decode)]
#[bincode(
decode_bounds = "T: Decode<__Context> + 'static",
borrow_decode_bounds = "T: BorrowDecode<'__de, __Context> + '__de"
......@@ -46,6 +50,44 @@ pub struct FrozenSet<T> {
map: FrozenMap<T, ()>,
}
impl<T: Serialize> Serialize for FrozenSet<T> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
serializer.collect_seq(self.iter())
}
}
impl<'de, T> Deserialize<'de> for FrozenSet<T>
where
T: Deserialize<'de> + Ord,
{
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
struct SeqVisitor<T>(PhantomData<T>);
impl<'de, T> Visitor<'de> for SeqVisitor<T>
where
T: Deserialize<'de> + Ord,
{
type Value = FrozenSet<T>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a sequence")
}
fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<Self::Value, A::Error> {
let mut items = Vec::with_capacity(seq.size_hint().unwrap_or(0));
while let Some(item) = seq.next_element()? {
items.push((item, ()));
}
Ok(FrozenSet {
map: FrozenMap::from(items),
})
}
}
deserializer.deserialize_seq(SeqVisitor(PhantomData))
}
}
impl<T> FrozenSet<T> {
/// Creates an empty [`FrozenSet`]. Does not perform any heap allocations.
pub fn new() -> Self {
......@@ -355,6 +397,18 @@ impl<T> Clone for Range<'_, T> {
mod tests {
use super::*;
#[test]
fn serde_uses_sequence_shape() {
let set = FrozenSet::from([2, 1]);
let json = serde_json::to_string(&set).unwrap();
assert_eq!(json, "[1,2]");
assert_eq!(
serde_json::from_str::<FrozenSet<i32>>("[2, 1]").unwrap(),
set
);
}
#[test]
fn test_empty() {
let set = FrozenSet::<i32>::new();
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment