-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathmod.rs
465 lines (363 loc) · 14.6 KB
/
mod.rs
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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
/*!
Defines types related to the [`RESP`](https://redis.io/docs/reference/protocol-spec/) protocol and their encoding/decoding
# Object Model
**rustis** provides an object model in the form of a generic data struct, comparable to the XML DOM,
and which matches perfectly the RESP protocol: the enum [`resp::Value`](Value).
Each variant of this enum matches a [`RESP`](https://redis.io/docs/reference/protocol-spec/) type.
Because, navigating through a [`resp::Value`](Value) instance can be verbose and requires a lot of pattern matching,
**rustis** provides a [`resp::Value`](Value) to Rust type conversion with a [serde](https://serde.rs/)
deserializer implementation of a [`resp::Value`](Value) reference.
This conversion is easily accessible through the associate function [`Value::into`](Value::into).
# Command arguments
**rustis** provides an idiomatic way to pass arguments to [commands](crate::commands).
Basically a [`Command`] is a builder which accepts a command name and one ore more command arguments.
You will notice that each built-in command expects arguments through a set of traits defined in this module.
For each trait, you can add your own implementations for your custom types
or request additional implementation for standard types.
### ToArgs
The trait [`ToArgs`] allows to convert a complex type into one ore multiple argumentss.
Basically, the conversion function can add multiple arguments to an existing argument collection: the [`CommandArgs`] struct.
Current implementation provides the following conversions:
* `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `usize`, `isize`,
* `f32`, `f64`,
* `bool`,
* `String`, `&String`, `char`, `&str`, [`BulkString`], `Vec<u8>`, `&[u8; N]`, `[u8; N]`, `&[u8]`
* `Option<T>` where `T: SingleArg`
* `(T, U)`
* `(T, U, V)`
* `Vec<T>`
* `[T;N]`
* `SmallVec<A>`
* `BTreeSet<T>`
* `HashSet<T, S>`
* `BTreeMap<K, V>`
* `HashMap<K, V, S>`
* [`CommandArgs`]
Nevertheless, [`ToArgs`] is not expected directly in built-in commands arguments.
The following traits are used to constraints which implementations of [`ToArgs`]
are expected by a specific argument of a built-in command.
### SingleArg
Several Redis commands expect a Rust type that should be converted in a single command argument.
**rustis** uses the trait [`SingleArg`] to implement this behavior.
Current implementation provides the following conversions:
* `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `usize`, `isize`,
* `f32`, `f64`,
* `bool`,
* `String`, `&String`, `char`, `&str`, [`BulkString`], `Vec<u8>`, `&[u8; N]`, `[u8; N]`, `&[u8]`
* `Option<T>` where `T: SingleArg`
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, StringCommands},
resp::{CommandArgs, ToArgs, SingleArg},
Result,
};
pub struct MyI32(i32);
impl ToArgs for MyI32 {
#[inline]
fn write_args(&self, args: &mut CommandArgs) {
args.arg(self.0);
}
}
impl SingleArg for MyI32 {}
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.set("key", 12).await?;
client.set("key", 12i64).await?;
client.set("key", 12.12).await?;
client.set("key", true).await?;
client.set("key", true).await?;
client.set("key", "value").await?;
client.set("key", "value".to_owned()).await?;
client.set("key", 'c').await?;
client.set("key", b"value").await?;
client.set("key", &b"value"[..]).await?;
client.set("key", b"value".to_vec()).await?;
client.set("key", MyI32(12)).await?;
Ok(())
}
```
### SingleArgCollection
Several Redis commands expect a collection with elements that will produced a single
command argument each
**rustis** uses the trait [`SingleArgCollection`] to implement this behavior.
Current implementation provides the following conversions:
* `T` (for the single item case)
* `Vec<T>`
* `[T;N]`
* `SmallVec<A>`
* `BTreeSet<T>`
* `HashSet<T, S>`
* [`CommandArgs`]
where each of theses implementations must also implement [`ToArgs`]
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, ListCommands},
Result,
};
use smallvec::{SmallVec};
use std::collections::{HashSet, BTreeSet};
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.lpush("key", 12).await?;
client.lpush("key", [12, 13, 14]).await?;
client.lpush("key", vec![12, 13, 14]).await?;
client.lpush("key", SmallVec::from([12, 13, 14])).await?;
client.lpush("key", HashSet::from([12, 13, 14])).await?;
client.lpush("key", BTreeSet::from([12, 13, 14])).await?;
client.lpush("key", "value1").await?;
client.lpush("key", ["value1", "value2", "value13"]).await?;
client.lpush("key", vec!["value1", "value2", "value13"]).await?;
client.lpush("key", SmallVec::from(["value1", "value2", "value13"])).await?;
client.lpush("key", HashSet::from(["value1", "value2", "value13"])).await?;
client.lpush("key", BTreeSet::from(["value1", "value2", "value13"])).await?;
Ok(())
}
```
### MultipleArgsCollection
Several Redis commands expect a collection with elements that will produced multiple
command arguments each
**rustis** uses the trait [`MultipleArgsCollection`] to implement this behavior.
Current implementation provides the following conversions:
* `T` (for the single item case)
* `Vec<T>`
* `[T;N]`
where each of theses implementations must also implement [`ToArgs`]
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, SortedSetCommands, ZAddOptions},
Result,
};
use std::collections::{HashSet, BTreeSet};
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.zadd("key", (1.0, "member1"), ZAddOptions::default()).await?;
client.zadd("key", [(1.0, "member1"), (2.0, "member2")], ZAddOptions::default()).await?;
client.zadd("key", vec![(1.0, "member1"), (2.0, "member2")], ZAddOptions::default()).await?;
Ok(())
}
```
### KeyValueArgsCollection
Several Redis commands expect one or multiple key/value pairs.
**rustis** uses the trait [`KeyValueArgsCollection`] to implement this behavior.
Current implementation provides the following conversions:
* `(K, V)` (for the single item case)
* `Vec<(K, V)>`
* `[(K, V);N]`
* `SmallVec<A>` where `A: Array<Item = (K, V)>`
* `BTreeMap<K, V>`
* `HashMap<K, V, S>`
where each of theses implementations must also implement [`ToArgs`]
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, StringCommands},
Result,
};
use smallvec::{SmallVec};
use std::collections::{HashMap, BTreeMap};
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.mset(("key1", "value1")).await?;
client.mset([("key1", "value1"), ("key2", "value2")]).await?;
client.mset(vec![("key1", "value1"), ("key2", "value2")]).await?;
client.mset(SmallVec::from([("key1", "value1"), ("key2", "value2")])).await?;
client.mset(HashMap::from([("key1", "value1"), ("key2", "value2")])).await?;
client.mset(BTreeMap::from([("key1", "value1"), ("key2", "value2")])).await?;
client.mset(("key1", 12)).await?;
client.mset([("key1", 12), ("key2", 13)]).await?;
client.mset(vec![("key1", 12), ("key2", 13)]).await?;
client.mset(SmallVec::from([("key1", 12), ("key2", 13)])).await?;
client.mset(HashMap::from([("key1", 12), ("key2", 13)])).await?;
client.mset(BTreeMap::from([("key1", 12), ("key2", 13)])).await?;
Ok(())
}
```
# Command results
**rustis** provides an idiomatic way to convert command results into Rust types with the help of [serde](serde.rs)
You will notice that each built-in command returns a [`PreparedCommand<R>`](crate::client::PreparedCommand)
struct where `R` represents the [`Response`] of the command.
The different command traits implementations ([`Client`](crate::client::Client), [`Pipeline`](crate::client::Pipeline)
or [`Transaction`](crate::client::Transaction)) add a constraint on the reponse `R`:
it must implement serde [`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html) trait.
Indeed, **rustis** provides a serde implementation of a [`RESP deserializer`](RespDeserializer).
Each custom struct or enum defined as a response of a built-command implements
serde [`Deserialize`](https://docs.rs/serde/latest/serde/trait.Deserialize.html) trait,
in order to deserialize it automatically from a RESP Buffer.
Some more advanced traits allow to constraint more which Rust types are allowed for specific commands.
For each trait, you can add your own implementations for your custom types
or request additional implementation for standard types.
### PrimitiveResponse
Several Redis commands return a simple primitive response.
**rustis** uses the trait [`PrimitiveResponse`] to implement this behavior.
Current implementation provides the following deserializations from a RESP Buffer:
* [`Value`]
* ()
* `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `usize`, `isize`,
* `f32`, `f64`,
* `bool`,
* `String`,
* [`BulkString`],
* `Option<T>`
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, StringCommands},
resp::{PrimitiveResponse, deserialize_byte_buf},
Result,
};
use serde::Deserialize;
#[derive(Deserialize)]
pub struct MyI32(i32);
impl PrimitiveResponse for MyI32 {}
#[derive(Deserialize)]
pub struct Buffer(#[serde(deserialize_with = "deserialize_byte_buf")] pub Vec<u8>);
impl PrimitiveResponse for Buffer {}
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.set("key", 12).await?;
let _result: i32 = client.get("key").await?;
let _result: MyI32 = client.get("key").await?;
client.set("key", 12.12).await?;
let _result: f64 = client.get("key").await?;
client.set("key", true).await?;
let _result: bool = client.get("key").await?;
client.set("key", "value").await?;
let _result: String = client.get("key").await?;
let _result: Buffer = client.get("key").await?;
Ok(())
}
```
### CollectionResponse
Several Redis commands return a collection of items.
**rustis** uses the trait [`CollectionResponse`] to implement this behavior.
Current implementation provides the following deserializations from a RESP Buffer:
* `Vec<T>`
* `[T;N]`
* `SmallVec<A>`
* `BTreeSet<T>`
* `HashSet<T, S>`
where each of theses implementations must also implement [`Response`]
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, ListCommands},
Result,
};
use smallvec::{SmallVec};
use std::collections::{HashSet, BTreeSet};
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.lpush("key", [12, 13, 14]).await?;
let _values: Vec<Option<i32>> = client.rpop("key", 3).await?;
client.lpush("key", [12, 13, 14]).await?;
let _values: HashSet<Option<i32>> = client.rpop("key", 3).await?;
client.lpush("key", [12, 13, 14]).await?;
let _values: BTreeSet<Option<i32>> = client.rpop("key", 3).await?;
client.lpush("key", [12, 13, 14]).await?;
let _values: SmallVec<[Option<i32>;3]> = client.rpop("key", 3).await?;
Ok(())
}
```
### KeyValueCollectionResponse
Several Redis commands return a collection of key/value pairs
**rustis** uses the trait [`KeyValueCollectionResponse`] to implement this behavior.
Current implementation provides the following deserializations from a RESP Buffer:
* `BTreeMap<K, V>`
* `HashMap<K, V, S>`
* `SmallVec<A>` where `A: Array<Item = (K, V)>`
* `Vec<(K, V>)>`
where each of theses implementations must also implement [`Response`]
#### Example
```
use rustis::{
client::Client,
commands::{FlushingMode, ServerCommands, HashCommands},
Result,
};
use smallvec::{SmallVec};
use std::collections::{HashMap, BTreeMap};
#[cfg_attr(feature = "tokio-runtime", tokio::main)]
#[cfg_attr(feature = "async-std-runtime", async_std::main)]
async fn main() -> Result<()> {
// Connect the client to a Redis server from its IP and port
let client = Client::connect("127.0.0.1:6379").await?;
// Flush all existing data in Redis
client.flushdb(FlushingMode::Sync).await?;
client.hset("key", [("field1", 12), ("field2", 13)]).await?;
let _values: BTreeMap<String, i32> = client.hgetall("key").await?;
let _values: HashMap<String, i32> = client.hgetall("key").await?;
let _values: SmallVec<[(String, i32); 10]> = client.hgetall("key").await?;
let _values: Vec<(String, i32)> = client.hgetall("key").await?;
Ok(())
}
```
*/
mod buffer_decoder;
mod bulk_string;
mod command;
mod command_args;
mod command_encoder;
mod resp_batch_deserializer;
mod resp_buf;
mod resp_deserializer;
mod resp_serializer;
mod response;
mod to_args;
mod util;
mod value;
mod value_deserialize;
mod value_deserializer;
mod value_serialize;
pub(crate) use buffer_decoder::*;
pub use bulk_string::*;
pub use command::*;
pub use command_args::*;
pub(crate) use command_encoder::*;
pub(crate) use resp_batch_deserializer::*;
pub use resp_buf::*;
pub use resp_deserializer::*;
pub use resp_serializer::*;
pub use response::*;
pub use to_args::*;
pub use util::*;
pub use value::*;
pub(crate) use value_deserialize::*;