1use base64_lib::{engine::general_purpose::STANDARD_NO_PAD, Engine};
2use revision::revisioned;
3use serde::{
4 de::{self, Visitor},
5 Deserialize, Serialize,
6};
7use std::fmt::{self, Display, Formatter};
8use std::ops::Deref;
9
10#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Hash)]
11#[revisioned(revision = 1)]
12pub struct Bytes(pub(crate) Vec<u8>);
13
14impl Bytes {
15 pub fn into_inner(self) -> Vec<u8> {
16 self.0
17 }
18}
19
20impl From<Vec<u8>> for Bytes {
21 fn from(v: Vec<u8>) -> Self {
22 Self(v)
23 }
24}
25
26impl Deref for Bytes {
27 type Target = Vec<u8>;
28
29 fn deref(&self) -> &Self::Target {
30 &self.0
31 }
32}
33
34impl Display for Bytes {
35 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
36 write!(f, "encoding::base64::decode(\"{}\")", STANDARD_NO_PAD.encode(&self.0))
37 }
38}
39
40impl Serialize for Bytes {
41 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
42 where
43 S: serde::Serializer,
44 {
45 serializer.serialize_bytes(&self.0)
46 }
47}
48
49impl<'de> Deserialize<'de> for Bytes {
50 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
51 where
52 D: serde::Deserializer<'de>,
53 {
54 struct RawBytesVisitor;
55
56 impl<'de> Visitor<'de> for RawBytesVisitor {
57 type Value = Bytes;
58
59 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
60 formatter.write_str("bytes")
61 }
62
63 fn visit_byte_buf<E>(self, v: Vec<u8>) -> Result<Self::Value, E>
64 where
65 E: de::Error,
66 {
67 Ok(Bytes(v))
68 }
69
70 fn visit_bytes<E>(self, v: &[u8]) -> Result<Self::Value, E>
71 where
72 E: de::Error,
73 {
74 Ok(Bytes(v.to_owned()))
75 }
76 }
77
78 deserializer.deserialize_byte_buf(RawBytesVisitor)
79 }
80}
81
82#[cfg(test)]
83mod tests {
84 use crate::{Bytes, Value};
85
86 #[test]
87 fn serialize() {
88 let val = Value::Bytes(Bytes(vec![1, 2, 3, 5]));
89 let serialized: Vec<u8> = val.clone().into();
90 println!("{serialized:?}");
91 let deserialized = Value::from(serialized);
92 assert_eq!(val, deserialized);
93 }
94}