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 3 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
1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ exclude = [

[dependencies]
serde = { version = "^1.0.80", default-features = false, features = ["alloc"] }
serde-cw-value = "0.7.0"

[dev-dependencies]
serde_derive = "^1.0.80"
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.deserialize_str(visitor)
}

fn deserialize_bytes<V>(self, _visitor: V) -> Result<V::Value, Self::Error>
Expand Down
30 changes: 14 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 @@ -608,6 +593,19 @@ impl<'a, 'de> de::Deserializer<'de> for &'a mut Deserializer<'de> {
} else {
Err(Error::InvalidType)
}

}

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>(
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>,
webmaster128 marked this conversation as resolved.
Show resolved Hide resolved
}

#[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();
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
48 changes: 48 additions & 0 deletions src/ser/map.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
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(())
}
}
8 changes: 6 additions & 2 deletions src/ser/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,9 +8,12 @@ use std::vec::Vec;

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

mod seq;
mod struct_;
mod map;


/// Serialization result
pub type Result<T> = ::core::result::Result<T, Error>;
Expand Down Expand Up @@ -153,7 +156,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 +403,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
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(())
}
}