Implement serde serialization

This commit is contained in:
Steven Roose 2020-10-08 15:00:12 +02:00
parent b69b25fee8
commit 2631c60a5a
No known key found for this signature in database
GPG Key ID: 2F2A88D7F8D68E87
3 changed files with 68 additions and 0 deletions

View File

@ -41,5 +41,7 @@ bitcoin_hashes = "0.7.6"
unicode-normalization = "=0.1.9"
rand = { version = "0.6.0", optional = true }
serde = { version = "1.0", optional = true }
[dev-dependencies]
rand = { version = "0.6.0", optional = false }

59
src/internal_macros.rs Normal file
View File

@ -0,0 +1,59 @@
/// Implement serde serialization based on the
/// fmt::Display and std::FromStr traits.
macro_rules! serde_string_impl {
($name:ident, $expecting:expr) => {
#[cfg(feature = "serde")]
impl<'de> $crate::serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>
where
D: $crate::serde::de::Deserializer<'de>,
{
use ::std::fmt::{self, Formatter};
use ::std::str::FromStr;
struct Visitor;
impl<'de> $crate::serde::de::Visitor<'de> for Visitor {
type Value = $name;
fn expecting(&self, formatter: &mut Formatter) -> fmt::Result {
formatter.write_str($expecting)
}
fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
where
E: $crate::serde::de::Error,
{
$name::from_str(v).map_err(E::custom)
}
fn visit_borrowed_str<E>(self, v: &'de str) -> Result<Self::Value, E>
where
E: $crate::serde::de::Error,
{
self.visit_str(v)
}
fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
where
E: $crate::serde::de::Error,
{
self.visit_str(&v)
}
}
deserializer.deserialize_str(Visitor)
}
}
#[cfg(feature = "serde")]
impl<'de> $crate::serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: $crate::serde::Serializer,
{
serializer.collect_str(&self)
}
}
};
}

View File

@ -28,8 +28,11 @@
extern crate bitcoin_hashes;
extern crate unicode_normalization;
#[cfg(feature = "rand")]
extern crate rand;
#[cfg(feature = "serde")]
pub extern crate serde;
use std::{error, fmt, str};
use std::borrow::Cow;
@ -37,6 +40,8 @@ use std::borrow::Cow;
use bitcoin_hashes::{sha256, Hash};
use unicode_normalization::UnicodeNormalization;
#[macro_use]
mod internal_macros;
mod language;
mod pbkdf2;
@ -100,6 +105,8 @@ impl error::Error for Error {
pub struct Mnemonic(String);
// The content of the mnemonic is ensured to be NFKD-normalized UTF-8.
serde_string_impl!(Mnemonic, "a BIP-39 Mnemonic Code");
impl Mnemonic {
/// Ensure the content of the [Cow] is normalized UTF8.
/// Performing this on a [Cow] means that all allocations for normalization