use base64::{engine::general_purpose::STANDARD_NO_PAD, Engine}; use revision::revisioned; use serde::{ de::{self, Visitor}, Deserialize, Serialize, }; use std::fmt::{self, Display, Formatter}; use std::ops::Deref; #[revisioned(revision = 1)] #[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Hash)] #[cfg_attr(feature = "arbitrary", derive(arbitrary::Arbitrary))] #[non_exhaustive] pub struct Bytes(pub(crate) Vec); impl Bytes { pub fn into_inner(self) -> Vec { self.0 } } impl From> for Bytes { fn from(v: Vec) -> Self { Self(v) } } impl Deref for Bytes { type Target = Vec; fn deref(&self) -> &Self::Target { &self.0 } } impl Display for Bytes { fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { write!(f, "encoding::base64::decode(\"{}\")", STANDARD_NO_PAD.encode(&self.0)) } } impl Serialize for Bytes { fn serialize(&self, serializer: S) -> Result where S: serde::Serializer, { serializer.serialize_bytes(&self.0) } } impl<'de> Deserialize<'de> for Bytes { fn deserialize(deserializer: D) -> Result where D: serde::Deserializer<'de>, { struct RawBytesVisitor; impl<'de> Visitor<'de> for RawBytesVisitor { type Value = Bytes; fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result { formatter.write_str("bytes") } fn visit_byte_buf(self, v: Vec) -> Result where E: de::Error, { Ok(Bytes(v)) } fn visit_bytes(self, v: &[u8]) -> Result where E: de::Error, { Ok(Bytes(v.to_owned())) } } deserializer.deserialize_byte_buf(RawBytesVisitor) } } #[cfg(test)] mod tests { use crate::sql::{Bytes, Value}; #[test] fn serialize() { let val = Value::Bytes(Bytes(vec![1, 2, 3, 5])); let serialized: Vec = val.clone().into(); println!("{serialized:?}"); let deserialized = Value::from(serialized); assert_eq!(val, deserialized); } }