1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
/// One RESP2 value.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum RespValue {
/// A simple string, such as `OK`.
Simple(String),
/// An error reply. [`crate::Client::execute`] returns this as [`crate::Error::Server`].
Error(String),
/// A signed integer.
Integer(i64),
/// A bulk string, including the empty bulk.
Bulk(Vec<u8>),
/// An array of values.
Array(Vec<RespValue>),
/// A null bulk or a null array.
Null,
}
impl RespValue {
/// UTF-8 text of a simple string or a bulk string. `None` when the value is null.
pub fn as_string(&self) -> Result<Option<String>, crate::Error> {
match self {
RespValue::Null => Ok(None),
RespValue::Simple(text) | RespValue::Error(text) => Ok(Some(text.clone())),
RespValue::Bulk(bytes) => {
let text = String::from_utf8(bytes.clone())
.map_err(|_| crate::Error::Protocol("bulk string is not UTF-8".to_owned()))?;
Ok(Some(text))
}
RespValue::Integer(_) | RespValue::Array(_) => {
Err(crate::Error::Protocol(format!("{self:?} is not a string")))
}
}
}
/// The integer, or `None` for any other kind.
pub fn as_integer(&self) -> Option<i64> {
match self {
RespValue::Integer(value) => Some(*value),
_ => None,
}
}
/// The array items, or `None` for any other kind.
pub fn as_array(&self) -> Option<&[RespValue]> {
match self {
RespValue::Array(items) => Some(items),
_ => None,
}
}
/// True for a null bulk or a null array.
pub fn is_null(&self) -> bool {
matches!(self, RespValue::Null)
}
}