Skip to content

Commit

Permalink
Added serializers for base64 bytes and optional base64 bytes
Browse files Browse the repository at this point in the history
  • Loading branch information
mappum committed Nov 28, 2019
1 parent 1407703 commit 2ced6c7
Showing 1 changed file with 46 additions and 3 deletions.
49 changes: 46 additions & 3 deletions tendermint/src/serializers.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@

use serde::{de::Error as _, Deserialize, Deserializer, Serialize, Serializer};
use std::time::Duration;
use subtle_encoding::hex;
use subtle_encoding::{base64, hex};

/// Parse `i64` from a JSON string
pub(crate) fn parse_i64<'de, D>(deserializer: D) -> Result<i64, D::Error>
Expand Down Expand Up @@ -69,9 +69,10 @@ pub(crate) fn serialize_hex<S, T>(bytes: T, serializer: S) -> Result<S::Ok, S::E
T: AsRef<[u8]>
{
use serde::ser::Error;
let hex_bytes = String::from_utf8(hex::encode(bytes.as_ref()))
let hex_bytes = hex::encode(bytes.as_ref());
let hex_string = String::from_utf8(hex_bytes)
.map_err(Error::custom)?;
serializer.serialize_str(&hex_bytes)
serializer.serialize_str(&hex_string)
}

pub(crate) fn parse_hex<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
Expand All @@ -83,3 +84,45 @@ pub(crate) fn parse_hex<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
.map_err(Error::custom)
}

pub(crate) fn serialize_base64<S, T>(bytes: T, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
T: AsRef<[u8]>
{
use serde::ser::Error;
let base64_bytes = base64::encode(bytes.as_ref());
let base64_string = String::from_utf8(base64_bytes)
.map_err(Error::custom)?;
serializer.serialize_str(&base64_string)
}

pub(crate) fn parse_base64<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
where D: Deserializer<'de>
{
use serde::de::Error;
let string = String::deserialize(deserializer)?;
base64::decode(&string)
.map_err(Error::custom)
}

pub(crate) fn serialize_option_base64<S>(maybe_bytes: &Option<Vec<u8>>, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
#[derive(Serialize)]
struct Wrapper<'a>(#[serde(serialize_with = "serialize_base64")] &'a Vec<u8>);

match maybe_bytes {
Some(bytes) => Wrapper(bytes).serialize(serializer),
None => maybe_bytes.serialize(serializer)
}
}

pub(crate) fn parse_option_base64<'de, D>(deserializer: D) -> Result<Option<Vec<u8>>, D::Error>
where D: Deserializer<'de>
{
#[derive(Deserialize)]
struct Wrapper(#[serde(deserialize_with = "parse_base64")] Vec<u8>);

let v = Option::deserialize(deserializer)?;
Ok(v.map(|Wrapper(a)| a))
}

0 comments on commit 2ced6c7

Please sign in to comment.