Skip to content

Commit

Permalink
serde improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
ph0llux committed Mar 12, 2024
1 parent 578834f commit dcfa8a5
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
2 changes: 1 addition & 1 deletion src/lib/header/encryption_header.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub struct EncryptionHeader {
#[cfg_attr(feature = "serde", serde(serialize_with = "crate::helper::buffer_to_base64", deserialize_with = "crate::helper::base64_to_buffer"))]
pub encrypted_encryption_key: Vec<u8>,
/// The decrypted encryption key.
#[cfg_attr(feature = "serde", serde(serialize_with = "crate::helper::buffer_to_base64"))]
#[cfg_attr(feature = "serde", serde(serialize_with = "crate::helper::option_buffer_to_base64"))]
pub decrypted_encryption_key: Option<Vec<u8>>
}

Expand Down
23 changes: 18 additions & 5 deletions src/lib/helper.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,17 +89,30 @@ pub fn hex_to_buffer<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D:
#[cfg(feature = "serde")]
/// Serializes `buffer` to a lowercase base64 string.
pub fn buffer_to_base64<T, S>(buffer: &T, serializer: S) -> std::result::Result<S::Ok, S::Error>
where T: AsRef<[u8]>,
S: serde::Serializer
where
T: AsRef<[u8]>,
S: serde::Serializer
{
serializer.serialize_str(&base64engine.encode(&buffer))
serializer.serialize_str(&base64engine.encode(&buffer))
}

#[cfg(feature = "serde")]
/// Serializes `buffer` (Option) to a lowecase base64 Option<String>.
pub fn option_buffer_to_base64<S>(buffer: &Option<Vec<u8>>, serializer: S) -> std::result::Result<S::Ok, S::Error>
where
S: serde::Serializer
{
match buffer {
Some(buffer) => buffer_to_base64(&buffer, serializer),
None => serializer.serialize_none(),
}
}

#[cfg(feature = "serde")]
/// Deserializes a lowercase base64 string to a `Vec<u8>`.
pub fn base64_to_buffer<'de, D>(deserializer: D) -> std::result::Result<Vec<u8>, D::Error>
where D: serde::Deserializer<'de>
{
use serde::de::Error;
String::deserialize(deserializer).and_then(|string| base64engine.decode(&string).map_err(|err| Error::custom(err.to_string())))
use serde::de::Error;
String::deserialize(deserializer).and_then(|string| base64engine.decode(&string).map_err(|err| Error::custom(err.to_string())))
}

0 comments on commit dcfa8a5

Please sign in to comment.