Skip to main content

sqlite_types/
page_bytes.rs

1use std::{borrow::Borrow, ops::Deref};
2
3use bytes::Bytes;
4use serde::{Deserialize, Deserializer, Serialize, Serializer};
5
6/// Shared immutable bytes for one SQLite page version.
7///
8/// Adopting an owned `Vec<u8>` is zero-copy, and cloning this value only increments the backing
9/// buffer's reference count. Converting back to `Vec<u8>` is intentionally explicit because a
10/// generated protocol or storage boundary may require a new owned contiguous buffer.
11#[derive(Clone, Default, Eq, Hash, PartialEq)]
12pub struct PageBytes(Bytes);
13
14impl PageBytes {
15	pub fn copy_from_slice(bytes: &[u8]) -> Self {
16		Self(Bytes::copy_from_slice(bytes))
17	}
18
19	pub fn as_slice(&self) -> &[u8] {
20		self.0.as_ref()
21	}
22
23	pub fn len(&self) -> usize {
24		self.0.len()
25	}
26
27	pub fn is_empty(&self) -> bool {
28		self.0.is_empty()
29	}
30
31	pub fn to_vec(&self) -> Vec<u8> {
32		self.0.to_vec()
33	}
34
35	/// Returns mutable owned storage, reusing the page allocation when this is its only owner.
36	pub fn into_vec(self) -> Vec<u8> {
37		self.0.into()
38	}
39
40	/// Returns the shared buffer without copying, for protocol messages that hold `Bytes`.
41	pub fn into_bytes(self) -> Bytes {
42		self.0
43	}
44}
45
46impl std::fmt::Debug for PageBytes {
47	fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
48		formatter
49			.debug_tuple("PageBytes")
50			.field(&self.as_slice())
51			.finish()
52	}
53}
54
55impl From<Vec<u8>> for PageBytes {
56	fn from(bytes: Vec<u8>) -> Self {
57		Self(Bytes::from(bytes))
58	}
59}
60
61impl From<Bytes> for PageBytes {
62	fn from(bytes: Bytes) -> Self {
63		Self(bytes)
64	}
65}
66
67impl From<&[u8]> for PageBytes {
68	fn from(bytes: &[u8]) -> Self {
69		Self::copy_from_slice(bytes)
70	}
71}
72
73impl AsRef<[u8]> for PageBytes {
74	fn as_ref(&self) -> &[u8] {
75		self.as_slice()
76	}
77}
78
79impl Borrow<[u8]> for PageBytes {
80	fn borrow(&self) -> &[u8] {
81		self.as_slice()
82	}
83}
84
85impl Deref for PageBytes {
86	type Target = [u8];
87
88	fn deref(&self) -> &Self::Target {
89		self.as_slice()
90	}
91}
92
93impl Serialize for PageBytes {
94	fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
95	where
96		S: Serializer,
97	{
98		self.as_slice().serialize(serializer)
99	}
100}
101
102impl<'de> Deserialize<'de> for PageBytes {
103	fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
104	where
105		D: Deserializer<'de>,
106	{
107		Vec::<u8>::deserialize(deserializer).map(Self::from)
108	}
109}
110
111