-
Notifications
You must be signed in to change notification settings - Fork 9
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add a `serde` module and feature gate it behind the "serde" feature as is customary. Add an example showing how to use the new module to serialize struct fields as hex. Fix: #6
- Loading branch information
Showing
5 changed files
with
146 additions
and
1 deletion.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
//! Demonstrate how to use the serde module with struct fields. | ||
#![allow(clippy::disallowed_names)] // Foo is a valid name. | ||
|
||
use hex_conservative as hex; | ||
use serde::{Deserialize, Serialize}; | ||
|
||
fn main() { | ||
let v = vec![0xde, 0xad, 0xbe, 0xef]; | ||
|
||
let foo = Foo { v: v.clone() }; | ||
let bar = Bar { v: v.clone() }; | ||
|
||
let ser_foo = serde_json::to_string(&foo).expect("failed to serialize foo"); | ||
let ser_bar = serde_json::to_string(&bar).expect("failed to serialize bar"); | ||
|
||
println!(); | ||
println!("foo: {}", ser_foo); | ||
println!("bar: {}", ser_bar); | ||
} | ||
|
||
/// Abstracts over foo. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
struct Foo { | ||
#[serde(with = "hex")] | ||
v: Vec<u8>, | ||
} | ||
|
||
/// Abstracts over bar. | ||
#[derive(Debug, Serialize, Deserialize)] | ||
struct Bar { | ||
v: Vec<u8>, | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
//! Hex encoding with `serde`. | ||
//! | ||
//! # Examples | ||
//! | ||
//! ``` | ||
//! # #[cfg(feature = "std")] { | ||
//! use hex_conservative as hex; | ||
//! use serde::{Serialize, Deserialize}; | ||
//! | ||
//! #[derive(Debug, Serialize, Deserialize)] | ||
//! struct Foo { | ||
//! #[serde(with = "hex")] | ||
//! bar: Vec<u8>, | ||
//! } | ||
//! # } | ||
//! ``` | ||
use core::fmt; | ||
use core::marker::PhantomData; | ||
|
||
use serde::de::{Error, Visitor}; | ||
use serde::{Deserialize, Deserializer, Serialize, Serializer}; | ||
|
||
use crate::prelude::*; | ||
|
||
/// Serializes `data` as a hex string using lowercase characters. | ||
pub fn serialize<S, T>(data: T, s: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: Serializer, | ||
T: Serialize + DisplayHex, | ||
{ | ||
serialize_lower(data, s) | ||
} | ||
|
||
/// Serializes `data` as a hex string using lowercase characters. | ||
pub fn serialize_lower<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: Serializer, | ||
T: Serialize + DisplayHex, | ||
{ | ||
// Don't do anything special when not human readable. | ||
if !serializer.is_human_readable() { | ||
serde::Serialize::serialize(&data, serializer) | ||
} else { | ||
serializer.collect_str(&format_args!("{:x}", data.as_hex())) | ||
} | ||
} | ||
|
||
/// Serializes `data` as hex string using uppercase characters. | ||
pub fn serialize_upper<S, T>(data: T, serializer: S) -> Result<S::Ok, S::Error> | ||
where | ||
S: Serializer, | ||
T: Serialize + DisplayHex, | ||
{ | ||
// Don't do anything special when not human readable. | ||
if !serializer.is_human_readable() { | ||
serde::Serialize::serialize(&data, serializer) | ||
} else { | ||
serializer.collect_str(&format_args!("{:X}", data.as_hex())) | ||
} | ||
} | ||
|
||
/// Deserializes a hex string into raw bytes. | ||
/// | ||
/// Allows upper, lower, and mixed case characters (e.g. `a5b3c1`, `A5B3C1` and `A5b3C1`). | ||
pub fn deserialize<'de, D, T>(d: D) -> Result<T, D::Error> | ||
where | ||
D: Deserializer<'de>, | ||
T: Deserialize<'de> + FromHex, | ||
{ | ||
struct HexVisitor<T>(PhantomData<T>); | ||
|
||
impl<'de, T> Visitor<'de> for HexVisitor<T> | ||
where | ||
T: FromHex, | ||
{ | ||
type Value = T; | ||
|
||
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result { | ||
f.write_str("an ASCII hex string") | ||
} | ||
|
||
fn visit_str<E: Error>(self, data: &str) -> Result<Self::Value, E> { | ||
FromHex::from_hex(data).map_err(Error::custom) | ||
} | ||
|
||
fn visit_borrowed_str<E: Error>(self, data: &'de str) -> Result<Self::Value, E> { | ||
FromHex::from_hex(data).map_err(Error::custom) | ||
} | ||
} | ||
|
||
// Don't do anything special when not human readable. | ||
if !d.is_human_readable() { | ||
serde::Deserialize::deserialize(d) | ||
} else { | ||
d.deserialize_map(HexVisitor(PhantomData)) | ||
} | ||
} |