rustis 0.22.0

Redis async driver for Rust
Documentation
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
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#[cfg(test)]
use crate::resp::next_sequence_counter;
use crate::resp::{ArgLayout, ArgsLayout, Command, cmd};
use bytes::{BufMut, BytesMut};
use dtoa::Float;
use itoa::Integer;
use serde::{Serialize, Serializer, ser};
use smallvec::SmallVec;
use std::{fmt::Error, ops::Range};

pub struct FastPathCommandBuilder {
    buffer: BytesMut,
    name_layout: (usize, usize),
    args_layout: ArgsLayout,
    is_readonly: bool,
}

impl FastPathCommandBuilder {
    #[inline(always)]
    pub fn new(header: &[u8], name_layout: (usize, usize)) -> Self {
        let mut buffer = BytesMut::with_capacity(128);
        buffer.put_slice(header);

        FastPathCommandBuilder {
            buffer,
            name_layout,
            args_layout: SmallVec::new(),
            is_readonly: false,
        }
    }

    /// Declares the command as read-only, like [`CommandBuilder::readonly`](crate::resp::CommandBuilder::readonly).
    #[inline(always)]
    fn readonly(mut self) -> Self {
        self.is_readonly = true;
        self
    }

    /// Serializes `arg` onto the fast path, returning the builder on success or
    /// `Err` on any non-primitive. The caller falls back to the generic builder
    /// rather than panicking.
    #[inline(always)]
    fn try_arg(mut self, arg: impl Serialize) -> Result<Self, Error> {
        let mut serializer = FastPathRespSerializer::new(&mut self.buffer);
        let range = arg.serialize(&mut serializer)?;

        self.args_layout.push(ArgLayout::arg(range));
        Ok(self)
    }

    /// Same as [`Self::try_arg`] for a key, marking it for Cluster routing. The
    /// CRC16 slot is computed later by [`Command::compute_slots`], on the caller
    /// thread and only in Cluster mode.
    #[inline(always)]
    fn try_key(mut self, key: impl Serialize) -> Result<Self, Error> {
        let mut serializer = FastPathRespSerializer::new(&mut self.buffer);
        let range = key.serialize(&mut serializer)?;

        self.args_layout.push(ArgLayout::key(range));
        Ok(self)
    }

    #[inline(always)]
    pub fn build(self) -> Command {
        Command::new(
            self.buffer.freeze(),
            self.name_layout,
            self.args_layout,
            #[cfg(test)]
            0,
            #[cfg(test)]
            0,
            #[cfg(test)]
            next_sequence_counter(),
            None,
            None,
            0,
            self.is_readonly,
        )
    }

    #[inline(always)]
    pub fn get(key: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*2\r\n$3\r\nGET\r\n", (8, 3)).try_key(&key) {
            Ok(builder) => builder.readonly().build(),
            Err(_) => cmd("GET").key(key).readonly().into(),
        }
    }

    #[inline(always)]
    pub fn set(key: impl Serialize, value: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$3\r\nSET\r\n", (8, 3))
            .try_key(&key)
            .and_then(|b| b.try_arg(&value))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("SET").key(key).arg(value).into(),
        }
    }

    #[inline(always)]
    pub fn expire(key: impl Serialize, seconds: u64) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$6\r\nEXPIRE\r\n", (8, 6))
            .try_key(&key)
            .and_then(|b| b.try_arg(seconds))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("EXPIRE").key(key).arg(seconds).into(),
        }
    }

    #[inline(always)]
    pub fn hget(key: impl Serialize, field: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$4\r\nHGET\r\n", (8, 4))
            .try_key(&key)
            .and_then(|b| b.try_arg(&field))
        {
            Ok(builder) => builder.readonly().build(),
            Err(_) => cmd("HGET").key(key).arg(field).readonly().into(),
        }
    }

    #[inline(always)]
    pub fn hincrby(key: impl Serialize, field: impl Serialize, increment: i64) -> Command {
        match FastPathCommandBuilder::new(b"*4\r\n$7\r\nHINCRBY\r\n", (8, 7))
            .try_key(&key)
            .and_then(|b| b.try_arg(&field))
            .and_then(|b| b.try_arg(increment))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("HINCRBY").key(key).arg(field).arg(increment).into(),
        }
    }

    #[inline(always)]
    pub fn sismember(key: impl Serialize, member: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$9\r\nSISMEMBER\r\n", (8, 9))
            .try_key(&key)
            .and_then(|b| b.try_arg(&member))
        {
            Ok(builder) => builder.readonly().build(),
            Err(_) => cmd("SISMEMBER").key(key).arg(member).readonly().into(),
        }
    }

    #[inline(always)]
    pub fn zincrby(key: impl Serialize, increment: f64, member: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*4\r\n$7\r\nZINCRBY\r\n", (8, 7))
            .try_key(&key)
            .and_then(|b| b.try_arg(increment))
            .and_then(|b| b.try_arg(&member))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("ZINCRBY").key(key).arg(increment).arg(member).into(),
        }
    }

    #[inline(always)]
    pub fn publish(channel: impl Serialize, message: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$7\r\nPUBLISH\r\n", (8, 7))
            .try_arg(&channel)
            .and_then(|b| b.try_arg(&message))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("PUBLISH").arg(channel).arg(message).into(),
        }
    }

    #[inline(always)]
    pub fn lpush(key: impl Serialize, element: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$5\r\nLPUSH\r\n", (8, 5))
            .try_key(&key)
            .and_then(|b| b.try_arg(&element))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("LPUSH").key(key).arg(element).into(),
        }
    }

    #[inline(always)]
    pub fn rpush(key: impl Serialize, element: impl Serialize) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$5\r\nRPUSH\r\n", (8, 5))
            .try_key(&key)
            .and_then(|b| b.try_arg(&element))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("RPUSH").key(key).arg(element).into(),
        }
    }

    #[inline(always)]
    pub fn lpop(key: impl Serialize, count: u32) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$4\r\nLPOP\r\n", (8, 4))
            .try_key(&key)
            .and_then(|b| b.try_arg(count))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("LPOP").key(key).arg(count).into(),
        }
    }

    #[inline(always)]
    pub fn rpop(key: impl Serialize, count: u32) -> Command {
        match FastPathCommandBuilder::new(b"*3\r\n$4\r\nRPOP\r\n", (8, 4))
            .try_key(&key)
            .and_then(|b| b.try_arg(count))
        {
            Ok(builder) => builder.build(),
            Err(_) => cmd("RPOP").key(key).arg(count).into(),
        }
    }
}

struct FastPathRespSerializer<'a> {
    buffer: &'a mut BytesMut,
}

impl<'a> FastPathRespSerializer<'a> {
    #[inline(always)]
    pub(crate) fn new(buffer: &'a mut BytesMut) -> Self {
        FastPathRespSerializer { buffer }
    }

    #[inline(always)]
    fn serialize_integer<I: Integer>(&mut self, i: I) -> Range<usize> {
        let mut buf = itoa::Buffer::new();
        self.write_arg(buf.format(i).as_bytes())
    }

    #[inline(always)]
    fn serialize_float<F: Float>(&mut self, f: F) -> Range<usize> {
        let mut buf = dtoa::Buffer::new();
        self.write_arg(buf.format(f).as_bytes())
    }

    /// Serializes a raw argument into the buffer using RESP format (BulkString).
    ///
    /// # Format
    /// `$Length\r\nData\r\n`
    #[inline]
    #[expect(
        clippy::arithmetic_side_effects,
        reason = "the header adds a fixed handful of bytes to the length of a slice \
                  that is already allocated, and the payload range ends where the \
                  bytes just written end."
    )]
    pub(crate) fn write_arg(&mut self, data: &[u8]) -> Range<usize> {
        // 1. Write the RESP BulkString header ($Len\r\n)
        let data_len = data.len();
        let mut len_buf = itoa::Buffer::new();
        let len_str = len_buf.format(data_len);
        let len_bytes = len_str.as_bytes();
        let total_size = 1 + len_bytes.len() + 2 + data_len + 2;
        self.buffer.reserve(total_size);
        self.buffer.put_u8(b'$');
        self.buffer.put_slice(len_bytes);
        self.buffer.put_slice(b"\r\n");

        // 2. Capture the absolute position of the data for the index
        let start_pos = self.buffer.len();

        // 3. Write the actual data
        self.buffer.put_slice(data);
        self.buffer.put_slice(b"\r\n");

        // 4. return the layout range
        start_pos..start_pos + data_len
    }
}

impl<'a> Serializer for &'a mut FastPathRespSerializer<'a> {
    type Ok = Range<usize>;
    type Error = Error;
    type SerializeSeq = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTuple = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeTupleVariant = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeMap = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeStruct = ser::Impossible<Self::Ok, Self::Error>;
    type SerializeStructVariant = ser::Impossible<Self::Ok, Self::Error>;

    #[inline(always)]
    fn serialize_bool(self, v: bool) -> Result<Self::Ok, Self::Error> {
        Ok(self.write_arg(if v { b"1" } else { b"0" }))
    }

    #[inline(always)]
    fn serialize_i8(self, v: i8) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_i16(self, v: i16) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_i32(self, v: i32) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_i64(self, v: i64) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_u8(self, v: u8) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_u16(self, v: u16) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_u32(self, v: u32) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_u64(self, v: u64) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_integer(v))
    }

    #[inline(always)]
    fn serialize_f32(self, v: f32) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_float(v))
    }

    #[inline(always)]
    fn serialize_f64(self, v: f64) -> Result<Self::Ok, Self::Error> {
        Ok(self.serialize_float(v))
    }

    #[inline(always)]
    fn serialize_char(self, v: char) -> Result<Self::Ok, Self::Error> {
        let mut buf = [0; 4];
        let str = v.encode_utf8(&mut buf);
        Ok(self.write_arg(str.as_bytes()))
    }

    #[inline(always)]
    fn serialize_str(self, v: &str) -> Result<Self::Ok, Self::Error> {
        Ok(self.write_arg(v.as_bytes()))
    }

    #[inline(always)]
    fn serialize_bytes(self, v: &[u8]) -> Result<Self::Ok, Self::Error> {
        Ok(self.write_arg(v))
    }

    #[inline(always)]
    fn serialize_none(self) -> Result<Self::Ok, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    #[inline(always)]
    fn serialize_some<T: ?Sized + Serialize>(self, value: &T) -> Result<Self::Ok, Self::Error> {
        value.serialize(self)
    }

    fn serialize_unit(self) -> Result<Self::Ok, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_unit_struct(self, _name: &'static str) -> Result<Self::Ok, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_unit_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        variant: &'static str,
    ) -> Result<Self::Ok, Self::Error> {
        self.serialize_str(variant)
    }

    fn serialize_newtype_struct<T: ?Sized + Serialize>(
        self,
        _name: &'static str,
        value: &T,
    ) -> Result<Self::Ok, Self::Error> {
        value.serialize(self)
    }

    fn serialize_newtype_variant<T>(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _value: &T,
    ) -> Result<Self::Ok, Self::Error>
    where
        T: ?Sized + Serialize,
    {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_seq(self, _len: Option<usize>) -> Result<Self::SerializeSeq, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_tuple(self, _len: usize) -> Result<Self::SerializeTuple, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_tuple_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleStruct, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_tuple_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeTupleVariant, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_map(self, _len: Option<usize>) -> Result<Self::SerializeMap, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_struct(
        self,
        _name: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStruct, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }

    fn serialize_struct_variant(
        self,
        _name: &'static str,
        _variant_index: u32,
        _variant: &'static str,
        _len: usize,
    ) -> Result<Self::SerializeStructVariant, Self::Error> {
        Err(ser::Error::custom("FastPath only supports primitives"))
    }
}

#[cfg(test)]
mod tests {
    #![allow(
        clippy::unwrap_used,
        clippy::expect_used,
        clippy::panic,
        clippy::unreachable,
        clippy::indexing_slicing,
        reason = "test code: a panic is how a test reports failure"
    )]
    use super::FastPathCommandBuilder;

    #[test]
    fn primitive_args_stay_on_the_fast_path() {
        // Regression guard: the common primitive case must keep working exactly
        // as before the fallback was added.
        let command = FastPathCommandBuilder::set("key", "value");
        assert_eq!(b"SET", command.name());
        assert_eq!(2, command.num_args());
        assert_eq!(Some(&b"key"[..]), command.get_arg(0).as_deref());
        assert_eq!(Some(&b"value"[..]), command.get_arg(1).as_deref());
    }

    #[test]
    fn none_argument_falls_back_instead_of_panicking() {
        // `set(key, None::<String>)` used to panic the caller thread. It must now
        // fall back to the generic builder, which drops the None as a no-op (a
        // caller-visible arity error from Redis, not a panic).
        let command = FastPathCommandBuilder::set("key", None::<String>);
        assert_eq!(b"SET", command.name());
        assert_eq!(1, command.num_args());
        assert_eq!(Some(&b"key"[..]), command.get_arg(0).as_deref());
        assert_eq!(None, command.get_arg(1));
    }

    #[test]
    fn collection_argument_falls_back_to_a_flattened_command() {
        // `lpush(key, vec!["a","b"])` used to panic. The generic builder
        // flattens the sequence into a correct multi-element LPUSH.
        let command = FastPathCommandBuilder::lpush("key", vec!["a", "b"]);
        assert_eq!(b"LPUSH", command.name());
        assert_eq!(3, command.num_args());
        assert_eq!(Some(&b"key"[..]), command.get_arg(0).as_deref());
        assert_eq!(Some(&b"a"[..]), command.get_arg(1).as_deref());
        assert_eq!(Some(&b"b"[..]), command.get_arg(2).as_deref());
    }

    #[test]
    fn some_primitive_still_serializes_on_the_fast_path() {
        // `serialize_some` delegates, so `Some(primitive)` stays on the fast
        // path — only `None` degrades.
        let command = FastPathCommandBuilder::set("key", Some("value"));
        assert_eq!(2, command.num_args());
        assert_eq!(Some(&b"value"[..]), command.get_arg(1).as_deref());
    }
}