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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
use crate::{
resp::{Array, BulkString, FromValue},
Error, Result, RedisError,
};
#[derive(Debug)]
pub enum Value {
SimpleString(String),
Integer(i64),
Double(f64),
BulkString(BulkString),
Array(Array),
Push(Array),
Error(RedisError),
}
impl Value {
pub fn into<T>(self) -> Result<T>
where
T: FromValue,
{
T::from_value(self)
}
}
impl Default for Value {
fn default() -> Self {
Value::BulkString(BulkString::Nil)
}
}
impl ToString for Value {
fn to_string(&self) -> String {
match &self {
Value::SimpleString(s) => s.clone(),
Value::Integer(i) => i.to_string(),
Value::Double(f) => f.to_string(),
Value::BulkString(s) => s.to_string(),
Value::Array(Array::Vec(v)) => format!(
"[{}]",
v.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
),
Value::Array(Array::Nil) => "[]".to_string(),
Value::Push(Array::Vec(v)) => format!(
"Push[{}]",
v.iter()
.map(ToString::to_string)
.collect::<Vec<_>>()
.join(", ")
),
Value::Push(Array::Nil) => "Push[]".to_string(),
Value::Error(e) => e.to_string(),
}
}
}
pub(crate) trait ResultValueExt {
fn into_result(self) -> Result<Value>;
fn map_into_result<T, F>(self, op: F) -> Result<T>
where
F: FnOnce(Value) -> T;
}
impl ResultValueExt for Result<Value> {
#[inline]
fn into_result(self) -> Result<Value> {
match self {
Ok(value) => match value {
Value::Error(e) => Err(Error::Redis(e)),
_ => Ok(value),
},
Err(e) => Err(e),
}
}
#[inline]
fn map_into_result<T, F>(self, op: F) -> Result<T>
where
F: FnOnce(Value) -> T,
{
match self {
Ok(value) => match value {
Value::Error(e) => Err(Error::Redis(e)),
_ => Ok(op(value)),
},
Err(e) => Err(e),
}
}
}
pub(crate) trait IntoValueIterator: Sized {
fn into_value_iter<T>(self) -> ValueIterator<T>
where
T: FromValue;
}
impl IntoValueIterator for Vec<Value> {
fn into_value_iter<T>(self) -> ValueIterator<T>
where
T: FromValue,
{
ValueIterator::new(self.into_iter())
}
}
pub(crate) struct ValueIterator<T>
where
T: FromValue,
{
iter: std::vec::IntoIter<Value>,
phantom: std::marker::PhantomData<T>,
#[allow(clippy::complexity)]
next_functor: Box<dyn FnMut(&mut std::vec::IntoIter<Value>) -> Option<Result<T>>>,
}
impl<T> ValueIterator<T>
where
T: FromValue,
{
pub fn new(iter: std::vec::IntoIter<Value>) -> Self {
Self {
iter,
phantom: std::marker::PhantomData,
next_functor: T::next_functor(),
}
}
}
impl<T> Iterator for ValueIterator<T>
where
T: FromValue,
{
type Item = Result<T>;
fn next(&mut self) -> Option<Self::Item> {
(self.next_functor)(&mut self.iter)
}
}