logtail: support serde

Signed-off-by: Christine Dodrill <me@christine.website>
This commit is contained in:
Cadey Ratio 2021-09-09 12:04:09 -04:00
parent c223853267
commit 916afc8852
4 changed files with 81 additions and 1 deletions

1
Cargo.lock generated
View File

@ -537,6 +537,7 @@ version = "0.1.0"
dependencies = [
"hex",
"rand 0.8.4",
"serde",
"sha2",
]

View File

@ -3,9 +3,18 @@ name = "logtail"
version = "0.1.0"
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
# See more keys and their definitions at
# https://doc.rust-lang.org/cargo/reference/manifest.html
[features]
default = [ "serde-ser" ]
serde-ser = [ "serde" ]
[dependencies]
hex = "0.4"
rand = "0"
sha2 = "0.9"
[dependencies.serde]
version = "1"
optional = true

View File

@ -10,6 +10,9 @@ use std::fmt;
#[derive(Clone, PartialEq, Eq)]
pub struct PrivateID([u8; SHA256_SIZE]);
#[cfg(feature = "serde-ser")]
mod serde;
impl PrivateID {
/// Safely generate a new PrivateId for use in Config objects.
/// You should persist this across runs of an instance of your app, so that

View File

@ -0,0 +1,67 @@
use super::{PrivateID, PublicID};
use serde::{de, Serialize, Serializer};
use std::fmt;
impl Serialize for PrivateID {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.as_hex())
}
}
struct PrivateIDVisitor;
impl<'de> de::Visitor<'de> for PrivateIDVisitor {
type Value = PrivateID;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a base-16 formatted ID as a string")
}
fn visit_str<E>(self, id: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match PrivateID::from_hex(id.to_string()) {
Ok(id) => Ok(id),
Err(_) => Err(de::Error::invalid_value(
de::Unexpected::Str(id),
&"a base-16 32 byte ID",
)),
}
}
}
impl Serialize for PublicID {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.as_hex())
}
}
struct PublicIDVisitor;
impl<'de> de::Visitor<'de> for PublicIDVisitor {
type Value = PublicID;
fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str("a base-16 formatted ID as a string")
}
fn visit_str<E>(self, id: &str) -> Result<Self::Value, E>
where
E: de::Error,
{
match PublicID::from_hex(id.to_string()) {
Ok(id) => Ok(id),
Err(_) => Err(de::Error::invalid_value(
de::Unexpected::Str(id),
&"a base-16 32 byte ID",
)),
}
}
}