Skip to main content

redust_resp/resp2/data/
bulk.rs

1use std::{
2	fmt::{self, Debug},
3	hash::{Hash, Hasher},
4	ops::Deref,
5};
6
7use bytes::Bytes;
8
9/// The contents of a [bulk string](crate::Data::BulkString).
10///
11/// Like a [`Cow`](std::borrow::Cow), this either borrows its bytes or owns them. Owned bytes are a
12/// reference-counted [`Bytes`], so data decoded by the [codec](crate::Codec) shares the buffer it
13/// was read into instead of being copied out of it.
14#[derive(Clone)]
15pub enum Bulk<'a> {
16	/// Borrowed bytes.
17	Borrowed(&'a [u8]),
18	/// Owned, reference-counted bytes.
19	Shared(Bytes),
20}
21
22impl Bulk<'_> {
23	/// Convert these bytes into owned bytes, copying them if they are borrowed.
24	pub fn into_owned(self) -> Bulk<'static> {
25		Bulk::Shared(self.into_bytes())
26	}
27
28	/// Convert these bytes into [`Bytes`], copying them if they are borrowed.
29	pub fn into_bytes(self) -> Bytes {
30		match self {
31			Self::Borrowed(bytes) => Bytes::copy_from_slice(bytes),
32			Self::Shared(bytes) => bytes,
33		}
34	}
35}
36
37impl Deref for Bulk<'_> {
38	type Target = [u8];
39
40	fn deref(&self) -> &[u8] {
41		match self {
42			Self::Borrowed(bytes) => bytes,
43			Self::Shared(bytes) => bytes,
44		}
45	}
46}
47
48impl AsRef<[u8]> for Bulk<'_> {
49	fn as_ref(&self) -> &[u8] {
50		self
51	}
52}
53
54impl Debug for Bulk<'_> {
55	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
56		Debug::fmt(&**self, f)
57	}
58}
59
60impl Hash for Bulk<'_> {
61	fn hash<H: Hasher>(&self, state: &mut H) {
62		(**self).hash(state)
63	}
64}
65
66impl PartialEq for Bulk<'_> {
67	fn eq(&self, other: &Self) -> bool {
68		**self == **other
69	}
70}
71
72impl Eq for Bulk<'_> {}
73
74impl PartialEq<[u8]> for Bulk<'_> {
75	fn eq(&self, other: &[u8]) -> bool {
76		**self == *other
77	}
78}
79
80impl PartialEq<&[u8]> for Bulk<'_> {
81	fn eq(&self, other: &&[u8]) -> bool {
82		**self == **other
83	}
84}
85
86impl<const N: usize> PartialEq<[u8; N]> for Bulk<'_> {
87	fn eq(&self, other: &[u8; N]) -> bool {
88		**self == *other
89	}
90}
91
92impl<const N: usize> PartialEq<&[u8; N]> for Bulk<'_> {
93	fn eq(&self, other: &&[u8; N]) -> bool {
94		**self == **other
95	}
96}
97
98impl<'a> From<&'a [u8]> for Bulk<'a> {
99	fn from(bytes: &'a [u8]) -> Self {
100		Self::Borrowed(bytes)
101	}
102}
103
104impl<'a, const N: usize> From<&'a [u8; N]> for Bulk<'a> {
105	fn from(bytes: &'a [u8; N]) -> Self {
106		Self::Borrowed(bytes)
107	}
108}
109
110impl From<Vec<u8>> for Bulk<'_> {
111	fn from(bytes: Vec<u8>) -> Self {
112		Self::Shared(bytes.into())
113	}
114}
115
116impl From<Bytes> for Bulk<'_> {
117	fn from(bytes: Bytes) -> Self {
118		Self::Shared(bytes)
119	}
120}