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

Add support for deserialization of owned values #16

Closed
wants to merge 6 commits into from
Closed
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
217 changes: 184 additions & 33 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -49,10 +49,12 @@ pub mod utils;
pub use config::*;
pub use types::{Error, ParseHexError};

use serde::{Deserialize, Deserializer, Serializer};
use serde::{Deserializer, Serializer};
use smallvec::SmallVec;
use std::iter::FromIterator;
use std::{error, io};
use std::{error, io, fmt};
use serde::de::{Visitor};
use serde::__private::{PhantomData};

Choose a reason for hiding this comment

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

Well, we should really be importing this from std, haha.


/// Trait specifying custom serialization and deserialization logic from a
/// hexadecimal string to some arbitrary type. This trait can be used to apply
Expand Down Expand Up @@ -122,13 +124,52 @@ where
where
D: Deserializer<'de>,
{
use serde::de::Error;
let buff: &[u8] = Deserialize::deserialize(deserializer)?;
let rslt = Self::from_hex_raw(buff).map_err(D::Error::custom)?;
let rslt = deserializer.deserialize_any(HexBytesVisitor::default())?;
Ok(rslt)
}
}

struct HexBytesVisitor<S, C> {
_phantom: PhantomData<(S, C)>
}

impl<S, C> Default for HexBytesVisitor<S, C> {
fn default() -> Self {
Self {
_phantom: PhantomData
}
}
}

impl<'de, S, C> Visitor<'de> for HexBytesVisitor<S, C> where S: SerHex<C>, C: HexConf {
type Value = S;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a hex string")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
S::from_hex_raw(v).map_err(E::custom)
}

fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
S::from_hex_raw(v).map_err(E::custom)
}

fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
S::from_hex_raw(v).map_err(E::custom)
}
}

/// Variant of `SerHex` for serializing/deserializing `Option` types.
///
/// Any type `T` which implements `SerHex<C>` implements `SerHexOpt<C>`
Expand Down Expand Up @@ -185,24 +226,86 @@ where
where
D: Deserializer<'de>,
{
use serde::de::Error;
let option: Option<&[u8]> = Deserialize::deserialize(deserializer)?;
if let Some(ref buff) = option {
let rslt = Self::from_hex_raw(buff).map_err(D::Error::custom)?;
Ok(Some(rslt))
} else {
Ok(None)
}
let option = deserializer.deserialize_any(OptHexBytesVisitor::default())?;

Ok(option)
}
}

impl<T, C> SerHexOpt<C> for T
impl<S, C> SerHexOpt<C> for S
where
T: Sized + SerHex<C>,
S: Sized + SerHex<C>,
C: HexConf,
{
}

struct OptHexBytesVisitor<S, C> {
_phantom: PhantomData<(S, C)>
}

impl<T, C> Default for OptHexBytesVisitor<T, C> {
fn default() -> Self {
Self {
_phantom: PhantomData
}
}
}


impl<'de, S, C> Visitor<'de> for OptHexBytesVisitor<S, C> where S: SerHexOpt<C>, C: HexConf {
type Value = Option<S>;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a hex string")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let s = S::from_hex_raw(v).map_err(E::custom)?;

Ok(Some(s))
}

fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let s = S::from_hex_raw(v).map_err(E::custom)?;

Ok(Some(s))
}

fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
let s = S::from_hex_raw(v).map_err(E::custom)?;

Ok(Some(s))
}

fn visit_none<E>(self) -> Result<Self::Value, E> where
E: serde::de::Error, {
Ok(None)
}

fn visit_unit<E>(self) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
Ok(None)
}

fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, <D as Deserializer<'de>>::Error> where
D: Deserializer<'de>, {
let result = deserializer.deserialize_bytes(self)?;

Ok(result)
}
}

/// Variant of `SerHex` for serializing/deserializing sequence types as
/// contiguous hexadecimal strings.
///
Expand Down Expand Up @@ -266,25 +369,73 @@ where
D: Deserializer<'de>,
T: FromIterator<Self>,
{
use serde::de::Error;
let raw: &[u8] = Deserialize::deserialize(deserializer)?;
let src = if raw.starts_with(b"0x") {
&raw[2..]
} else {
&raw[..]
};
let hexsize = Self::size() * 2;
if src.len() % hexsize == 0 {
let mut buff = Vec::with_capacity(src.len() / hexsize);
for chunk in src.chunks(hexsize) {
let elem =
<Self as SerHex<Strict>>::from_hex_raw(chunk).map_err(D::Error::custom)?;
buff.push(elem);
}
Ok(buff.into_iter().collect())
} else {
Err(D::Error::custom("bad hexadecimal sequence size"))
deserializer.deserialize_bytes(SeqHexBytesVisitor::<Self, C, T>::default())
}
}

struct SeqHexBytesVisitor<S, C, T> {
_phantom: PhantomData<(S, C, T)>
}

impl<S, C, T> Default for SeqHexBytesVisitor<S, C, T> {
fn default() -> Self {
Self {
_phantom: PhantomData
}
}
}

impl<'de, S, C, T> Visitor<'de> for SeqHexBytesVisitor<S, C, T> where S: SerHexSeq<C>, C: HexConf, T: FromIterator<S> {
type Value = T;

fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a hex string")
}

fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
seq_from_bytes(v.as_bytes(), S::size())
}

fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
seq_from_bytes(v.as_bytes(), S::size())
}

fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E> where
E: serde::de::Error, {
seq_from_bytes(v, S::size())
}

fn visit_borrowed_bytes<E>(self, v: &'de [u8]) -> Result<Self::Value, E>
where
E: serde::de::Error,
{
seq_from_bytes(v, S::size())
}
}

fn seq_from_bytes<S, E, T>(raw: &[u8], size_hint: usize) -> Result<T, E> where S: SerHex<Strict>, E: serde::de::Error, T: FromIterator<S> {
let src = if raw.starts_with(b"0x") {
&raw[2..]
} else {
&raw[..]
};
let hexsize = size_hint * 2;
if src.len() % hexsize == 0 {
let mut buff = Vec::with_capacity(src.len() / hexsize);
for chunk in src.chunks(hexsize) {
let elem =
S::from_hex_raw(chunk).map_err(E::custom)?;
buff.push(elem);
}
Ok(buff.into_iter().collect())
} else {
Err(E::custom("bad hexadecimal sequence size"))
}
}

Expand Down
28 changes: 28 additions & 0 deletions tests/extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,31 @@ fn deserialize() {
};
assert_eq!(ext, exp);
}

#[test]
fn deserialize_owned() {
let ser = serde_json::json!({
"seq": "0x0123456789abcdef",
"opt": "aa"
});
let ext = serde_json::from_value::<Ext>(ser).unwrap();
let exp = Ext {
seq: vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
opt: Some(0xaa),
};
assert_eq!(ext, exp);
}

#[test]
fn deserialize_none() {
let ser = serde_json::json!({
"seq": "0x0123456789abcdef",
"opt": null
});
let ext = serde_json::from_value::<Ext>(ser).unwrap();
let exp = Ext {
seq: vec![0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef],
opt: None,
};
assert_eq!(ext, exp);
}
14 changes: 14 additions & 0 deletions tests/json.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,17 @@ fn deserialize() {
};
assert_eq!(foo, exp);
}

#[test]
fn deserialize_owned() {
let ser = serde_json::json!({
"bar": "0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"bin": "0x1234"
});
let foo = serde_json::from_value::<Foo>(ser).unwrap();
let exp = Foo {
bar: [0xaa; 32],
bin: 0x1234,
};
assert_eq!(foo, exp);
}