Skip to main content

qail_redis/
value.rs

1//! Redis value types returned from commands.
2
3/// A value returned from Redis.
4#[derive(Debug, Clone, PartialEq)]
5pub enum Value {
6    /// Null value (key doesn't exist, etc.)
7    Null,
8    /// Simple string (status replies like "OK")
9    String(String),
10    /// Bulk string (actual data)
11    Bulk(Vec<u8>),
12    /// Integer
13    Integer(i64),
14    /// Boolean (RESP3)
15    Boolean(bool),
16    /// Double (RESP3)
17    Double(f64),
18    /// Array of values
19    Array(Vec<Value>),
20    /// Map of key-value pairs (RESP3)
21    Map(Vec<(Value, Value)>),
22    /// Error from Redis
23    Error(String),
24}
25
26impl Value {
27    /// Try to get as string.
28    pub fn as_str(&self) -> Option<&str> {
29        match self {
30            Value::String(s) => Some(s),
31            Value::Bulk(b) => std::str::from_utf8(b).ok(),
32            _ => None,
33        }
34    }
35
36    /// Try to get as bytes.
37    pub fn as_bytes(&self) -> Option<&[u8]> {
38        match self {
39            Value::Bulk(b) => Some(b),
40            Value::String(s) => Some(s.as_bytes()),
41            _ => None,
42        }
43    }
44
45    /// Try to get as integer.
46    pub fn as_int(&self) -> Option<i64> {
47        match self {
48            Value::Integer(i) => Some(*i),
49            _ => None,
50        }
51    }
52
53    /// Try to get as boolean.
54    pub fn as_bool(&self) -> Option<bool> {
55        match self {
56            Value::Boolean(b) => Some(*b),
57            Value::Integer(i) => Some(*i != 0),
58            _ => None,
59        }
60    }
61
62    /// Check if null.
63    pub fn is_null(&self) -> bool {
64        matches!(self, Value::Null)
65    }
66
67    /// Check if error.
68    pub fn is_error(&self) -> bool {
69        matches!(self, Value::Error(_))
70    }
71}