Skip to content

Serde support #24

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

Merged
merged 1 commit into from
Mar 30, 2016
Merged
Show file tree
Hide file tree
Changes from all 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
7 changes: 4 additions & 3 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,12 @@ sudo: false
matrix:
include:
- rust: stable
env: FEATURES="serde_impl"
- rust: nightly
env: FEATURES="--features nightly"
env: FEATURES="serde_impl nightly"
script:
- cargo build $FEATURES
- cargo test $FEATURES
- cargo build --features "$FEATURES"
- cargo test --features "$FEATURES"
- cargo doc --no-deps
after_success: |
[ "$TRAVIS_RUST_VERSION" = nightly ] &&
Expand Down
5 changes: 5 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@ readme = "README.md"

[features]
nightly = []
serde_impl = ["serde", "serde_json"]

[dependencies]
serde = { version = "^0.7", optional = true }
serde_json = { version = "^0.7", optional = true }

[lib]
test = false
Expand Down
4 changes: 4 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,10 @@

#![deny(missing_docs)]

// Optional Serde support
#[cfg(feature = "serde_impl")]
pub mod serde;

use std::borrow::Borrow;
use std::fmt::{self, Debug};
use std::iter;
Expand Down
84 changes: 84 additions & 0 deletions src/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
//! An optional implementation of serialization/deserialization. Reference
//! implementations used:
//!
//! - [Serialize][1].
//! - [Deserialize][2].
//!
//! [1]: https://github.com/serde-rs/serde/blob/97856462467db2e90cf368e407c7ebcc726a01a9/serde/src/ser/impls.rs#L601-L611
//! [2]: https://github.com/serde-rs/serde/blob/97856462467db2e90cf368e407c7ebcc726a01a9/serde/src/de/impls.rs#L694-L746

extern crate serde;

use super::LinearMap;

use self::serde::{Serialize, Serializer, Deserialize, Deserializer};
use self::serde::ser::impls::MapIteratorVisitor;
use self::serde::de::{Visitor, MapVisitor, Error};

use std::marker::PhantomData;

impl<K, V> Serialize for LinearMap<K, V>
where K: Serialize + Ord,
V: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: &mut S) -> Result<(), S::Error>
where S: Serializer,
{
serializer.serialize_map(MapIteratorVisitor::new(self.iter(), Some(self.len())))
}
}

#[allow(missing_docs)]
pub struct LinearMapVisitor<K, V> {
Copy link
Contributor

Choose a reason for hiding this comment

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

This does not need to be pub - then you don't need the #[allow(missing_docs)]. Same for LinearMapVisitor::new.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I use LinearMap in a Value-like enum in my code base. I'd like to serialize/deserialize that value. Is there a good way to deserialize a map of its visitor is not public?

Copy link
Contributor

Choose a reason for hiding this comment

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

Even so, why does the visitor need to be public? All you should need are the Serialize and Deserialize traits implemented for LinearMap. Here is a working example that deserializes a Value-like enum containing a LinearMap:

#![feature(plugin, custom_derive)]
#![plugin(serde_macros)]

extern crate serde;
extern crate serde_yaml;
extern crate linear_map;

use linear_map::LinearMap;

#[derive(Deserialize, PartialEq, Debug)]
enum Value {
    Null,
    Map(LinearMap<String, String>),
}

fn main() {
    let y = "Map: {k: v}";
    let v: Value = serde_yaml::from_str(&y).unwrap();
    assert_eq!(v, expected());
}

fn expected() -> Value {
    let mut map = LinearMap::new();
    map.insert(String::from("k"), String::from("v"));
    Value::Map(map)
}

Copy link
Contributor Author

Choose a reason for hiding this comment

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

I have a requirement to be on stable, so no custom derives, and we really don't want to use syntex because the interface is very undesirable 😐

serde_json uses the visitor implementation here, so as that was my reference I also did it that way. I thought it that was the canonical way of deserializing in this way.

It's not too hard for me to reimplement this functionality, I'll make it private 👍

Copy link
Contributor

Choose a reason for hiding this comment

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

Okay I understand now why it makes sense for it to be public. You can change it back.

marker: PhantomData<LinearMap<K, V>>,
}

impl<K, V> LinearMapVisitor<K, V> {
#[allow(missing_docs)]
pub fn new() -> Self {
LinearMapVisitor {
marker: PhantomData,
}
}
}

impl<K, V> Visitor for LinearMapVisitor<K, V>
where K: Deserialize + Eq,
V: Deserialize,
{
type Value = LinearMap<K, V>;

#[inline]
fn visit_unit<E>(&mut self) -> Result<Self::Value, E>
where E: Error,
{
Ok(LinearMap::new())
}

#[inline]
fn visit_map<Visitor>(&mut self, mut visitor: Visitor) -> Result<Self::Value, Visitor::Error>
where Visitor: MapVisitor,
{
let mut values = LinearMap::with_capacity(visitor.size_hint().0);

while let Some((key, value)) = try!(visitor.visit()) {
values.insert(key, value);
}

try!(visitor.end());

Ok(values)
}
}

impl<K, V> Deserialize for LinearMap<K, V>
where K: Deserialize + Eq,
V: Deserialize,
{
fn deserialize<D>(deserializer: &mut D) -> Result<LinearMap<K, V>, D::Error>
where D: Deserializer,
{
deserializer.deserialize_map(LinearMapVisitor::new())
}
}
44 changes: 44 additions & 0 deletions tests/serde.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
#![cfg(feature = "serde_impl")]

extern crate linear_map;
extern crate serde;
extern crate serde_json;

use linear_map::LinearMap;

#[test]
fn test_ser_empty() {
let map = LinearMap::<String, u32>::new();
let j = serde_json::to_string(&map).unwrap();
let expected = "{}";
assert_eq!(j, expected);
}

#[test]
fn test_ser() {
let mut map = LinearMap::new();
map.insert("b", 20);
map.insert("a", 10);
map.insert("c", 30);

let j = serde_json::to_string(&map).unwrap();
let expected = r#"{"b":20,"a":10,"c":30}"#;
assert_eq!(j, expected);
}

#[test]
fn test_de_empty() {
let j = "{}";
let map: LinearMap<String, u32> = serde_json::from_str(j).unwrap();
assert_eq!(map.len(), 0);
}

#[test]
fn test_de() {
let j = r#"{"b":20,"a":10,"c":30}"#;
let map: LinearMap<String, u32> = serde_json::from_str(j).unwrap();
let items: Vec<_> = map.iter().map(|(k, v)| (k.clone(), *v)).collect();
assert_eq!(items, [("b".to_owned(), 20),
("a".to_owned(), 10),
("c".to_owned(), 30)]);
}