Skip to main content

surrealdb_expr/val/
bytes.rs

1use std::ops::Deref;
2
3use revision::revisioned;
4use storekey::{BorrowDecode, Encode};
5use surrealdb_types::{SqlFormat, ToSql, write_sql};
6
7use crate::val::IndexFormat;
8
9#[revisioned(revision = 1)]
10#[derive(Clone, Debug, Default, Eq, PartialEq, PartialOrd, Hash, Encode, BorrowDecode)]
11#[storekey(format = "()")]
12#[storekey(format = "IndexFormat")]
13#[repr(transparent)]
14pub struct Bytes(pub ::bytes::Bytes);
15
16impl Bytes {
17	pub fn into_inner(self) -> bytes::Bytes {
18		self.0
19	}
20}
21
22impl From<Vec<u8>> for Bytes {
23	fn from(v: Vec<u8>) -> Self {
24		Self(bytes::Bytes::from(v))
25	}
26}
27
28impl From<Bytes> for bytes::Bytes {
29	fn from(bytes: Bytes) -> Self {
30		bytes.0
31	}
32}
33
34impl From<bytes::Bytes> for Bytes {
35	fn from(bytes: bytes::Bytes) -> Self {
36		Bytes(bytes)
37	}
38}
39
40impl From<surrealdb_types::Bytes> for Bytes {
41	fn from(v: surrealdb_types::Bytes) -> Self {
42		Bytes(v.into_inner())
43	}
44}
45
46impl From<Bytes> for surrealdb_types::Bytes {
47	fn from(v: Bytes) -> Self {
48		surrealdb_types::Bytes::from(v.into_inner())
49	}
50}
51
52impl Deref for Bytes {
53	type Target = bytes::Bytes;
54
55	fn deref(&self) -> &Self::Target {
56		&self.0
57	}
58}
59
60impl ToSql for Bytes {
61	fn fmt_sql(&self, f: &mut String, fmt: SqlFormat) {
62		write_sql!(f, fmt, "b\"{}\"", hex::encode_upper(&self.0))
63	}
64}
65
66#[cfg(test)]
67mod tests {
68	use crate::val::{Bytes, Value};
69
70	#[test]
71	fn serialize() {
72		let val = Value::Bytes(Bytes::from(vec![1, 2, 3, 5]));
73		let serialized: Vec<u8> = revision::to_vec(&val).unwrap();
74		println!("{serialized:?}");
75		let deserialized: Value = revision::from_slice(&serialized).unwrap();
76		assert_eq!(val, deserialized);
77	}
78}
79
80#[cfg(feature = "arbitrary")]
81impl<'a> arbitrary::Arbitrary<'a> for Bytes {
82	fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
83		Ok(Bytes(::bytes::Bytes::copy_from_slice(u.arbitrary()?)))
84	}
85}