Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Map serde support #45

Merged
merged 19 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from 8 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/) and this
project adheres to [Semantic Versioning](http://semver.org/).

### Unreleased
- Add support for map (de)serialization.

## [0.4.1] - 2022-05-05

### Changed
Expand Down
4 changes: 2 additions & 2 deletions src/de/map.rs
Original file line number Diff line number Diff line change
Expand Up @@ -163,11 +163,11 @@ impl<'de, 'a> de::Deserializer<'de> for MapKey<'a, 'de> {
self.de.deserialize_str(visitor)
}

fn deserialize_string<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
fn deserialize_string<V>(self, visitor: V) -> Result<V::Value, Self::Error>
where
V: Visitor<'de>,
{
unreachable!()
webmaster128 marked this conversation as resolved.
Show resolved Hide resolved
self.de.deserialize_string(visitor)
webmaster128 marked this conversation as resolved.
Show resolved Hide resolved
}

fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
Expand Down
29 changes: 13 additions & 16 deletions src/de/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -576,22 +576,7 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
self.deserialize_seq(visitor)
}

/// Unsupported. Can’t make an arbitrary-sized map in no-std. Use a struct with a
/// known format, or implement a custom map deserializer / visitor:
/// https://serde.rs/deserialize-map.html
fn deserialize_map<V>(self, _visitor: V) -> Result<V::Value>
where
V: Visitor<'de>,
{
unreachable!()
}

fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
fn deserialize_map<V>(self, visitor: V) -> Result<V::Value>
where
V: Visitor<'de>,
{
Expand All @@ -610,6 +595,18 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
}
}

fn deserialize_struct<V>(
self,
_name: &'static str,
_fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value>
where
V: Visitor<'de>,
{
self.deserialize_map(visitor)
}

fn deserialize_enum<V>(
self,
_name: &'static str,
Expand Down
11 changes: 11 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,8 @@ pub use self::ser::{to_string, to_vec};

#[cfg(test)]
mod test {
use std::collections::BTreeMap;

use super::*;
use serde_derive::{Deserialize, Serialize};

Expand Down Expand Up @@ -95,6 +97,7 @@ mod test {
published: bool,
comments: Vec<CommentId>,
stats: Stats,
balances: BTreeMap<String, u16>,
}

#[test]
Expand All @@ -107,7 +110,10 @@ mod test {
published: false,
comments: vec![],
stats: Stats { views: 0, score: 0 },
balances: BTreeMap::new(),
};
let mut balances: BTreeMap<String, u16> = BTreeMap::new();
balances.insert("chareen".into(), 347);
let max = Item {
model: Model::Post {
category: "fun".to_string(),
Expand All @@ -122,6 +128,7 @@ mod test {
views: std::u64::MAX,
score: std::i64::MIN,
},
balances,
};

// binary
Expand Down Expand Up @@ -172,6 +179,9 @@ mod test {
author: Address("[email protected]".to_owned()),
});

let mut balances: BTreeMap<String, u16> = BTreeMap::new();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Okay, so this test will show parse(serialize(x)) == x right?

And does work with u16 as tree value, which is promising.

Maybe other pieces already work. Can you add test cases for other types?

Also, this only works when the map has all the same type of value, right? I guess we need some more work for flatten, but we can leave that for another PR.

balances.insert("chareen".into(), 347);

let item = ModelOrItem::Item(Item {
model: Model::Comment,
title: "Title".to_owned(),
Expand All @@ -183,6 +193,7 @@ mod test {
views: 110,
score: 12,
},
balances,
});

assert_eq!(
Expand Down
45 changes: 45 additions & 0 deletions src/ser/map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
use serde::ser;

use crate::ser::{Error, Result, Serializer};

pub struct SerializeMap<'a> {
ser: &'a mut Serializer,
first: bool,
}

impl<'a> SerializeMap<'a> {
pub(crate) fn new(ser: &'a mut Serializer) -> Self {
SerializeMap { ser, first: true }
}
}

impl<'a> ser::SerializeMap for SerializeMap<'a> {
type Ok = ();
type Error = Error;

fn end(self) -> Result<Self::Ok> {
self.ser.buf.push(b'}');
Ok(())
}

fn serialize_key<T: ?Sized>(&mut self, key: &T) -> Result<()>
where
T: ser::Serialize,
{
if !self.first {
self.ser.buf.push(b',');
}
self.first = false;
key.serialize(&mut *self.ser)?;
self.ser.buf.extend_from_slice(b":");
Ok(())
}

fn serialize_value<T: ?Sized>(&mut self, value: &T) -> Result<()>
where
T: ser::Serialize,
{
value.serialize(&mut *self.ser)?;
Ok(())
}
}
32 changes: 30 additions & 2 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@ use serde::ser;

use std::vec::Vec;

use self::map::SerializeMap;
use self::seq::SerializeSeq;
use self::struct_::SerializeStruct;

mod map;
mod seq;
mod struct_;

Expand Down Expand Up @@ -153,7 +155,7 @@ impl<'a> ser::Serializer for &'a mut Serializer {
type SerializeTuple = SerializeSeq<'a>;
type SerializeTupleStruct = Unreachable;
type SerializeTupleVariant = SerializeSeq<'a>;
type SerializeMap = Unreachable;
type SerializeMap = SerializeMap<'a>;
type SerializeStruct = SerializeStruct<'a>;
type SerializeStructVariant = SerializeStruct<'a>;

Expand Down Expand Up @@ -400,7 +402,8 @@ impl<'a> ser::Serializer for &'a mut Serializer {
}

fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap> {
unreachable!()
self.buf.push(b'{');
Ok(SerializeMap::new(self))
}

fn serialize_struct(self, _name: &'static str, _len: usize) -> Result<Self::SerializeStruct> {
Expand Down Expand Up @@ -530,6 +533,7 @@ impl ser::SerializeStructVariant for Unreachable {

#[cfg(test)]
mod tests {

use super::to_string;
use serde_derive::Serialize;

Expand Down Expand Up @@ -979,6 +983,30 @@ mod tests {
);
}

#[test]
fn btree_map() {
use std::collections::BTreeMap;
// empty map
assert_eq!(to_string(&BTreeMap::<(), ()>::new()).unwrap(), r#"{}"#);

let mut two_values = BTreeMap::new();
two_values.insert("my_name", "joseph");
two_values.insert("her_name", "aline");
assert_eq!(
to_string(&two_values).unwrap(),
r#"{"her_name":"aline","my_name":"joseph"}"#
);

let mut nested_map = BTreeMap::new();
nested_map.insert("two_entries", two_values.clone());

two_values.remove("my_name");
nested_map.insert("one_entry", two_values);
assert_eq!(
to_string(&nested_map).unwrap(),
r#"{"one_entry":{"her_name":"aline"},"two_entries":{"her_name":"aline","my_name":"joseph"}}"#
);
}
use serde_derive::Deserialize;

#[test]
Expand Down
32 changes: 16 additions & 16 deletions src/ser/struct_.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@ use serde::ser;
use crate::ser::{Error, Result, Serializer};

pub struct SerializeStruct<'a> {
de: &'a mut Serializer,
ser: &'a mut Serializer,
first: bool,
}

impl<'a> SerializeStruct<'a> {
pub(crate) fn new(de: &'a mut Serializer) -> Self {
SerializeStruct { de, first: true }
pub(crate) fn new(ser: &'a mut Serializer) -> Self {
SerializeStruct { ser, first: true }
}
}

Expand All @@ -23,21 +23,21 @@ impl<'a> ser::SerializeStruct for SerializeStruct<'a> {
{
// XXX if `value` is `None` we not produce any output for this field
if !self.first {
self.de.buf.push(b',');
self.ser.buf.push(b',');
}
self.first = false;

self.de.buf.push(b'"');
self.de.buf.extend_from_slice(key.as_bytes());
self.de.buf.extend_from_slice(b"\":");
self.ser.buf.push(b'"');
self.ser.buf.extend_from_slice(key.as_bytes());
self.ser.buf.extend_from_slice(b"\":");

value.serialize(&mut *self.de)?;
value.serialize(&mut *self.ser)?;

Ok(())
}

fn end(self) -> Result<Self::Ok> {
self.de.buf.push(b'}');
self.ser.buf.push(b'}');
Ok(())
}
}
Expand All @@ -52,24 +52,24 @@ impl<'a> ser::SerializeStructVariant for SerializeStruct<'a> {
{
// XXX if `value` is `None` we not produce any output for this field
if !self.first {
self.de.buf.push(b',');
self.ser.buf.push(b',');
}
self.first = false;

self.de.buf.push(b'"');
self.de.buf.extend_from_slice(key.as_bytes());
self.de.buf.extend_from_slice(b"\":");
self.ser.buf.push(b'"');
self.ser.buf.extend_from_slice(key.as_bytes());
self.ser.buf.extend_from_slice(b"\":");

value.serialize(&mut *self.de)?;
value.serialize(&mut *self.ser)?;

Ok(())
}

fn end(self) -> Result<Self::Ok> {
// close struct
self.de.buf.push(b'}');
self.ser.buf.push(b'}');
// close surrounding enum
self.de.buf.push(b'}');
self.ser.buf.push(b'}');
Ok(())
}
}