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