Skip to main content

redis_tower_commands/
arg.rs

1//! Binary-safe arguments shared by typed Redis commands.
2
3use std::borrow::Cow;
4use std::fmt;
5
6use bytes::Bytes;
7
8/// An owned, binary-safe Redis command argument.
9///
10/// Redis keys, values, fields, and members are byte strings, not UTF-8 text.
11/// `CommandArg` lets typed command builders accept those bytes without giving
12/// up the convenient string call sites used by most applications.
13///
14/// Owned [`String`], [`Vec<u8>`], and [`Bytes`] inputs reuse their allocation
15/// (or shared storage). Borrowed strings, byte slices, and arrays are copied
16/// once because command values must be owned and may outlive the caller.
17/// Cloning a `CommandArg` is cheap because [`Bytes`] uses shared storage.
18///
19/// # Examples
20///
21/// ```
22/// use bytes::Bytes;
23/// use redis_tower_commands::CommandArg;
24///
25/// let text = CommandArg::from("users:42");
26/// let invalid_utf8 = CommandArg::from(&b"key:\xff"[..]);
27/// let shared = CommandArg::from(Bytes::from_static(b"payload"));
28///
29/// assert_eq!(text.as_bytes(), b"users:42");
30/// assert_eq!(invalid_utf8.as_bytes(), b"key:\xff");
31/// assert_eq!(shared.as_bytes(), b"payload");
32/// ```
33#[derive(Clone, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
34pub struct CommandArg(Bytes);
35
36impl CommandArg {
37    /// Construct an argument by copying a borrowed byte slice.
38    pub fn copy_from_slice(value: &[u8]) -> Self {
39        Self(Bytes::copy_from_slice(value))
40    }
41
42    /// Construct an argument backed by static bytes without copying.
43    pub const fn from_static(value: &'static [u8]) -> Self {
44        Self(Bytes::from_static(value))
45    }
46
47    /// Borrow the exact bytes that will be sent to Redis.
48    pub fn as_bytes(&self) -> &[u8] {
49        &self.0
50    }
51
52    /// Consume the argument and return its shared byte storage.
53    pub fn into_bytes(self) -> Bytes {
54        self.0
55    }
56
57    /// Return the argument length in bytes.
58    pub fn len(&self) -> usize {
59        self.0.len()
60    }
61
62    /// Return `true` when the argument contains no bytes.
63    pub fn is_empty(&self) -> bool {
64        self.0.is_empty()
65    }
66}
67
68impl fmt::Debug for CommandArg {
69    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
70        formatter.debug_tuple("CommandArg").field(&self.0).finish()
71    }
72}
73
74impl AsRef<[u8]> for CommandArg {
75    fn as_ref(&self) -> &[u8] {
76        self.as_bytes()
77    }
78}
79
80impl From<Bytes> for CommandArg {
81    fn from(value: Bytes) -> Self {
82        Self(value)
83    }
84}
85
86impl From<&Bytes> for CommandArg {
87    fn from(value: &Bytes) -> Self {
88        Self(value.clone())
89    }
90}
91
92impl From<&CommandArg> for CommandArg {
93    fn from(value: &CommandArg) -> Self {
94        value.clone()
95    }
96}
97
98impl From<CommandArg> for Bytes {
99    fn from(value: CommandArg) -> Self {
100        value.into_bytes()
101    }
102}
103
104impl From<Vec<u8>> for CommandArg {
105    fn from(value: Vec<u8>) -> Self {
106        Self(Bytes::from(value))
107    }
108}
109
110impl From<&Vec<u8>> for CommandArg {
111    fn from(value: &Vec<u8>) -> Self {
112        Self::copy_from_slice(value)
113    }
114}
115
116impl From<String> for CommandArg {
117    fn from(value: String) -> Self {
118        Self(Bytes::from(value))
119    }
120}
121
122impl From<Box<str>> for CommandArg {
123    fn from(value: Box<str>) -> Self {
124        Self::from(String::from(value))
125    }
126}
127
128impl From<char> for CommandArg {
129    fn from(value: char) -> Self {
130        let mut encoded = [0; 4];
131        Self::from(value.encode_utf8(&mut encoded))
132    }
133}
134
135impl From<&str> for CommandArg {
136    fn from(value: &str) -> Self {
137        Self::copy_from_slice(value.as_bytes())
138    }
139}
140
141impl From<&&str> for CommandArg {
142    fn from(value: &&str) -> Self {
143        Self::from(*value)
144    }
145}
146
147impl From<&mut str> for CommandArg {
148    fn from(value: &mut str) -> Self {
149        Self::from(&*value)
150    }
151}
152
153impl From<&String> for CommandArg {
154    fn from(value: &String) -> Self {
155        Self::from(value.as_str())
156    }
157}
158
159impl From<&[u8]> for CommandArg {
160    fn from(value: &[u8]) -> Self {
161        Self::copy_from_slice(value)
162    }
163}
164
165impl From<&&[u8]> for CommandArg {
166    fn from(value: &&[u8]) -> Self {
167        Self::from(*value)
168    }
169}
170
171impl<const N: usize> From<[u8; N]> for CommandArg {
172    fn from(value: [u8; N]) -> Self {
173        Self::copy_from_slice(&value)
174    }
175}
176
177impl<const N: usize> From<&[u8; N]> for CommandArg {
178    fn from(value: &[u8; N]) -> Self {
179        Self::copy_from_slice(value)
180    }
181}
182
183impl<'a> From<Cow<'a, str>> for CommandArg {
184    fn from(value: Cow<'a, str>) -> Self {
185        match value {
186            Cow::Borrowed(value) => Self::from(value),
187            Cow::Owned(value) => Self::from(value),
188        }
189    }
190}
191
192impl<'a> From<Cow<'a, [u8]>> for CommandArg {
193    fn from(value: Cow<'a, [u8]>) -> Self {
194        match value {
195            Cow::Borrowed(value) => Self::from(value),
196            Cow::Owned(value) => Self::from(value),
197        }
198    }
199}
200
201#[cfg(test)]
202mod tests {
203    use super::*;
204
205    #[test]
206    fn preserves_every_byte_from_supported_inputs() {
207        let expected = b"\xff\x00\r\n";
208        assert_eq!(CommandArg::from(expected).as_bytes(), expected);
209        assert_eq!(CommandArg::from(expected.as_slice()).as_bytes(), expected);
210        assert_eq!(CommandArg::from(expected.to_vec()).as_bytes(), expected);
211        assert_eq!(
212            CommandArg::from(Bytes::copy_from_slice(expected)).as_bytes(),
213            expected
214        );
215    }
216
217    #[test]
218    fn accepts_text_and_empty_values() {
219        assert_eq!(CommandArg::from("hello").as_bytes(), b"hello");
220        assert!(CommandArg::from(String::new()).is_empty());
221        assert!(CommandArg::from(Vec::<u8>::new()).is_empty());
222    }
223}