memcache 0.20.0

memcached client 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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
//! Typed 1:1 mapping of the memcached meta protocol.
//!
//! This module builds wire commands (`mg`/`ms`/`md`/`ma`/`mn`/`me`) from
//! option structs and parses wire responses into [`MetaCommandResult`]. Every
//! option field corresponds to exactly one protocol flag. This layer performs
//! no serialization and no semantic interpretation of results; both belong to
//! the high-level client. Validation is limited to argument ranges and
//! combinations the protocol silently ignores.
//!
//! The `q` (noreply) and `b` (base64 key) flags are intentionally not
//! exposed: quiet semantics are an internal concern of the pipeline executor,
//! and binary keys are base64-encoded automatically by
//! [`MetaCommand`](super::MetaCommand).

use std::borrow::Cow;
use std::collections::HashMap;

use crate::error::{ClientError, MemcacheError};

use super::meta_command::{MetaCommand, MetaOp, MetaResponse, ReturnCode, base64_decode, encode_key};

const OPAQUE_MAX: usize = 32;

fn invalid<T>(message: &'static str) -> Result<T, MemcacheError> {
    Err(ClientError::Error(Cow::Borrowed(message)).into())
}

fn opaque_flag(opaque: &[u8]) -> Result<Vec<u8>, MemcacheError> {
    if opaque.is_empty() || opaque.len() > OPAQUE_MAX {
        return invalid("opaque must be 1-32 bytes");
    }
    if opaque.iter().any(|&byte| byte <= 0x20 || byte == 0x7f) {
        return invalid("opaque must not contain whitespace or control bytes");
    }
    let mut flag = Vec::with_capacity(opaque.len() + 1);
    flag.push(b'O');
    flag.extend_from_slice(opaque);
    Ok(flag)
}

struct FlagBuilder(Vec<Vec<u8>>);

impl FlagBuilder {
    fn new() -> FlagBuilder {
        FlagBuilder(Vec::new())
    }

    fn marker(&mut self, enabled: bool, wire: &'static [u8]) {
        if enabled {
            self.0.push(wire.to_vec());
        }
    }

    fn token(&mut self, prefix: u8, value: Option<u64>) {
        if let Some(value) = value {
            let mut flag = vec![prefix];
            flag.extend_from_slice(value.to_string().as_bytes());
            self.0.push(flag);
        }
    }

    fn opaque(&mut self, opaque: Option<&[u8]>) -> Result<(), MemcacheError> {
        if let Some(opaque) = opaque {
            self.0.push(opaque_flag(opaque)?);
        }
        Ok(())
    }

    fn into_inner(self) -> Vec<Vec<u8>> {
        self.0
    }
}

/// Options for [`build_get`] (`mg`). Each field maps to one protocol flag.
#[derive(Debug, Clone)]
pub struct GetOptions {
    /// `v` - return the item value.
    pub value: bool,
    /// `f` - return the client flags.
    pub return_client_flags: bool,
    /// `c` - return the item CAS.
    pub return_cas: bool,
    /// `t` - return the remaining TTL.
    pub return_ttl: bool,
    /// `s` - return the stored size.
    pub return_size: bool,
    /// `l` - return seconds since last access.
    pub return_last_access: bool,
    /// `h` - return whether the item was hit before.
    pub return_hit_before: bool,
    /// `k` - echo the key in the response.
    pub return_key: bool,
    /// `u` - don't bump the item in the LRU.
    pub no_lru_bump: bool,
    /// `T<ttl>` - update the item TTL.
    pub touch: Option<u32>,
    /// `N<ttl>` - vivify a missing item with this TTL and grant a lease.
    pub vivify_ttl: Option<u32>,
    /// `R<ttl>` - grant a recache lease when the remaining TTL is below this.
    pub recache_ttl: Option<u32>,
    /// `C<cas>` - suppress the value when the item CAS still matches.
    pub unless_cas: Option<u64>,
    /// `E<cas>` - replace the item CAS with this value.
    pub new_cas: Option<u64>,
    /// `O<token>` - opaque token echoed back in the response.
    pub opaque: Option<Vec<u8>>,
}

impl Default for GetOptions {
    fn default() -> GetOptions {
        GetOptions {
            value: true,
            return_client_flags: false,
            return_cas: false,
            return_ttl: false,
            return_size: false,
            return_last_access: false,
            return_hit_before: false,
            return_key: false,
            no_lru_bump: false,
            touch: None,
            vivify_ttl: None,
            recache_ttl: None,
            unless_cas: None,
            new_cas: None,
            opaque: None,
        }
    }
}

pub fn build_get(key: impl Into<Vec<u8>>, options: &GetOptions) -> Result<MetaCommand, MemcacheError> {
    if options.recache_ttl == Some(0) {
        return invalid("recache_ttl must be >= 1");
    }
    let mut flags = FlagBuilder::new();
    flags.marker(options.value, b"v");
    flags.marker(options.return_client_flags, b"f");
    flags.marker(options.return_cas, b"c");
    flags.marker(options.return_ttl, b"t");
    flags.marker(options.return_size, b"s");
    flags.marker(options.return_last_access, b"l");
    flags.marker(options.return_hit_before, b"h");
    flags.marker(options.return_key, b"k");
    flags.marker(options.no_lru_bump, b"u");
    flags.token(b'T', options.touch.map(u64::from));
    flags.token(b'N', options.vivify_ttl.map(u64::from));
    flags.token(b'R', options.recache_ttl.map(u64::from));
    flags.token(b'C', options.unless_cas);
    flags.token(b'E', options.new_cas);
    flags.opaque(options.opaque.as_deref())?;
    let mut command = MetaCommand::new(MetaOp::Get, key);
    command.flags = flags.into_inner();
    Ok(command)
}

/// Storage mode for [`build_set`] (`ms` `M` flag).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SetMode {
    /// Unconditional store (the protocol default, no mode flag).
    #[default]
    Set,
    /// `ME` - store only when the item does not exist.
    Add,
    /// `MR` - store only when the item exists.
    Replace,
    /// `MA` - append raw bytes to the stored value.
    Append,
    /// `MP` - prepend raw bytes to the stored value.
    Prepend,
}

impl SetMode {
    fn flag(self) -> Option<&'static [u8]> {
        match self {
            SetMode::Set => None,
            SetMode::Add => Some(b"ME"),
            SetMode::Replace => Some(b"MR"),
            SetMode::Append => Some(b"MA"),
            SetMode::Prepend => Some(b"MP"),
        }
    }
}

/// Options for [`build_set`] (`ms`). Each field maps to one protocol flag.
#[derive(Debug, Clone, Default)]
pub struct SetOptions {
    /// `F<flags>` - client flags stored with the item.
    pub client_flags: Option<u32>,
    /// `T<ttl>` - item TTL.
    pub ttl: Option<u32>,
    /// `M<mode>` - storage mode.
    pub mode: SetMode,
    /// `C<cas>` - store only when the item CAS matches.
    pub compare_cas: Option<u64>,
    /// `E<cas>` - replace the item CAS with this value.
    pub new_cas: Option<u64>,
    /// `I` - invalidate: mark the item stale instead of replacing it.
    pub invalidate: bool,
    /// `N<ttl>` - for append/prepend, vivify a missing item with this TTL.
    pub vivify_ttl: Option<u32>,
    /// `c` - return the new item CAS.
    pub return_cas: bool,
    /// `s` - return the stored size.
    pub return_size: bool,
    /// `k` - echo the key in the response.
    pub return_key: bool,
    /// `O<token>` - opaque token echoed back in the response.
    pub opaque: Option<Vec<u8>>,
}

pub fn build_set(
    key: impl Into<Vec<u8>>,
    value: impl Into<Vec<u8>>,
    options: &SetOptions,
) -> Result<MetaCommand, MemcacheError> {
    let concatenation = matches!(options.mode, SetMode::Append | SetMode::Prepend);
    if options.vivify_ttl.is_some() && !concatenation {
        return invalid("vivify_ttl is only valid for append/prepend");
    }
    if options.ttl.is_some() && concatenation {
        // The server ignores T for concatenation; the miss path takes its
        // TTL from N (vivify_ttl) instead. Reject the no-op.
        return invalid("ttl is ignored for append/prepend; use vivify_ttl");
    }
    if options.compare_cas.is_some() && options.mode == SetMode::Add {
        // Add only stores when no item exists, so there is no CAS to
        // compare; the protocol leaves the combination undefined.
        return invalid("compare_cas cannot be combined with add mode");
    }
    let mut flags = FlagBuilder::new();
    if let Some(mode_flag) = options.mode.flag() {
        flags.marker(true, mode_flag);
    }
    flags.marker(options.invalidate, b"I");
    flags.marker(options.return_cas, b"c");
    flags.marker(options.return_size, b"s");
    flags.marker(options.return_key, b"k");
    flags.token(b'F', options.client_flags.map(u64::from));
    flags.token(b'T', options.ttl.map(u64::from));
    flags.token(b'C', options.compare_cas);
    flags.token(b'E', options.new_cas);
    flags.token(b'N', options.vivify_ttl.map(u64::from));
    flags.opaque(options.opaque.as_deref())?;
    let mut command = MetaCommand::new(MetaOp::Set, key);
    command.flags = flags.into_inner();
    command.value = Some(value.into());
    Ok(command)
}

/// Options for [`build_delete`] (`md`). Each field maps to one protocol flag.
#[derive(Debug, Clone, Default)]
pub struct DeleteOptions {
    /// `C<cas>` - delete only when the item CAS matches.
    pub compare_cas: Option<u64>,
    /// `E<cas>` - for invalidate, replace the item CAS with this value.
    pub new_cas: Option<u64>,
    /// `I` - invalidate: mark the item stale instead of removing it.
    pub invalidate: bool,
    /// `T<ttl>` - for invalidate, the TTL the stale item keeps.
    pub ttl: Option<u32>,
    /// `x` - drop the value but keep the item.
    pub drop_value: bool,
    /// `k` - echo the key in the response.
    pub return_key: bool,
    /// `O<token>` - opaque token echoed back in the response.
    pub opaque: Option<Vec<u8>>,
}

pub fn build_delete(key: impl Into<Vec<u8>>, options: &DeleteOptions) -> Result<MetaCommand, MemcacheError> {
    if options.ttl.is_some() && !options.invalidate {
        // The server only applies T when paired with I; reject the no-op.
        return invalid("ttl is only applied when invalidate is set");
    }
    let mut flags = FlagBuilder::new();
    flags.marker(options.invalidate, b"I");
    flags.marker(options.drop_value, b"x");
    flags.marker(options.return_key, b"k");
    flags.token(b'C', options.compare_cas);
    flags.token(b'E', options.new_cas);
    flags.token(b'T', options.ttl.map(u64::from));
    flags.opaque(options.opaque.as_deref())?;
    let mut command = MetaCommand::new(MetaOp::Delete, key);
    command.flags = flags.into_inner();
    Ok(command)
}

/// Arithmetic direction for [`build_arithmetic`] (`ma` `M` flag).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ArithmeticMode {
    /// Increment (the protocol default, no mode flag).
    #[default]
    Increment,
    /// `MD` - decrement.
    Decrement,
}

/// Options for [`build_arithmetic`] (`ma`). Each field maps to one protocol
/// flag.
#[derive(Debug, Clone)]
pub struct ArithmeticOptions {
    /// `D<delta>` - the delta to apply (the server defaults to 1).
    pub delta: Option<u64>,
    /// `M<mode>` - increment or decrement.
    pub mode: ArithmeticMode,
    /// `J<value>` - initial value when vivifying a missing item.
    pub initial: Option<u64>,
    /// `N<ttl>` - vivify a missing item with this TTL.
    pub initial_ttl: Option<u32>,
    /// `T<ttl>` - update the item TTL.
    pub ttl: Option<u32>,
    /// `C<cas>` - apply only when the item CAS matches.
    pub compare_cas: Option<u64>,
    /// `E<cas>` - replace the item CAS with this value.
    pub new_cas: Option<u64>,
    /// `v` - return the new value.
    pub return_value: bool,
    /// `t` - return the remaining TTL.
    pub return_ttl: bool,
    /// `c` - return the new item CAS.
    pub return_cas: bool,
    /// `k` - echo the key in the response.
    pub return_key: bool,
    /// `O<token>` - opaque token echoed back in the response.
    pub opaque: Option<Vec<u8>>,
}

impl Default for ArithmeticOptions {
    fn default() -> ArithmeticOptions {
        ArithmeticOptions {
            delta: None,
            mode: ArithmeticMode::Increment,
            initial: None,
            initial_ttl: None,
            ttl: None,
            compare_cas: None,
            new_cas: None,
            return_value: true,
            return_ttl: false,
            return_cas: false,
            return_key: false,
            opaque: None,
        }
    }
}

pub fn build_arithmetic(key: impl Into<Vec<u8>>, options: &ArithmeticOptions) -> Result<MetaCommand, MemcacheError> {
    if options.initial.is_some() && options.initial_ttl.is_none() {
        // J is silently ignored without N; reject the no-op.
        return invalid("initial requires initial_ttl to vivify on miss");
    }
    let mut flags = FlagBuilder::new();
    flags.marker(options.mode == ArithmeticMode::Decrement, b"MD");
    flags.marker(options.return_value, b"v");
    flags.marker(options.return_ttl, b"t");
    flags.marker(options.return_cas, b"c");
    flags.marker(options.return_key, b"k");
    flags.token(b'D', options.delta);
    flags.token(b'N', options.initial_ttl.map(u64::from));
    flags.token(b'J', options.initial);
    flags.token(b'T', options.ttl.map(u64::from));
    flags.token(b'C', options.compare_cas);
    flags.token(b'E', options.new_cas);
    flags.opaque(options.opaque.as_deref())?;
    let mut command = MetaCommand::new(MetaOp::Arithmetic, key);
    command.flags = flags.into_inner();
    Ok(command)
}

/// Build an `mn` no-op, used as a pipeline barrier.
pub fn build_noop() -> MetaCommand {
    MetaCommand::new(MetaOp::Noop, Vec::new())
}

/// Build an `me` debug command.
pub fn build_debug(key: impl Into<Vec<u8>>) -> Result<MetaCommand, MemcacheError> {
    let key = key.into();
    let (_, needs_base64) = encode_key(&key)?;
    if needs_base64 {
        // protocol.txt documents the `b` flag for `me`, but real servers
        // (verified on memcached 1.6.45) look up the base64 token literally,
        // so a binary-key debug would silently report a miss for a live item.
        return invalid("meta debug does not support keys that require base64");
    }
    Ok(MetaCommand::new(MetaOp::Debug, key))
}

/// A fully parsed meta protocol response.
///
/// The typed fields are response flags decoded to native types; a field is
/// `None` (or `false` for markers) when the server did not send the flag.
/// `flags` keeps the raw tokens for anything this layer does not decode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct MetaCommandResult {
    /// The wire return code.
    pub rc: ReturnCode,
    /// The raw data block, if any.
    pub value: Option<Vec<u8>>,
    /// `c` - item CAS.
    pub cas: Option<u64>,
    /// `t` - remaining TTL (`-1` means unlimited).
    pub ttl: Option<i64>,
    /// `f` - client flags.
    pub client_flags: Option<u32>,
    /// `s` - stored size.
    pub size: Option<u64>,
    /// `l` - seconds since last access.
    pub last_access: Option<u64>,
    /// `h` - whether the item was hit before.
    pub hit_before: Option<bool>,
    /// `k` - the echoed key (base64-decoded when the `b` flag is present).
    pub key: Option<Vec<u8>>,
    /// `O` - the echoed opaque token.
    pub opaque: Option<Vec<u8>>,
    /// `W` - this client won a vivify/recache lease.
    pub won: bool,
    /// `Z` - another client holds the lease.
    pub busy: bool,
    /// `X` - the value is stale.
    pub stale: bool,
    /// The raw response flag tokens.
    pub flags: Vec<Vec<u8>>,
}

impl MetaCommandResult {
    /// Whether the command succeeded (`HD` or `VA`).
    pub fn ok(&self) -> bool {
        matches!(self.rc, ReturnCode::Hd | ReturnCode::Va)
    }
}

fn parse_int<T: std::str::FromStr<Err = std::num::ParseIntError>>(token: &[u8]) -> Result<T, MemcacheError> {
    Ok(std::str::from_utf8(token)?.parse::<T>()?)
}

/// Decode the response flags of a [`MetaResponse`] into a
/// [`MetaCommandResult`]. Unknown flags are kept in `flags` but otherwise
/// ignored.
pub fn parse_meta_result(response: MetaResponse) -> Result<MetaCommandResult, MemcacheError> {
    let mut result = MetaCommandResult {
        rc: response.rc,
        value: response.value,
        cas: None,
        ttl: None,
        client_flags: None,
        size: None,
        last_access: None,
        hit_before: None,
        key: None,
        opaque: None,
        won: false,
        busy: false,
        stale: false,
        flags: response.flags,
    };
    let mut key_base64 = false;
    for flag in &result.flags {
        let Some((&code, token)) = flag.split_first() else {
            continue;
        };
        match code {
            b'f' => result.client_flags = Some(parse_int(token)?),
            b'c' => result.cas = Some(parse_int(token)?),
            b't' => result.ttl = Some(parse_int(token)?),
            b'l' => result.last_access = Some(parse_int(token)?),
            b's' => result.size = Some(parse_int(token)?),
            b'h' => result.hit_before = Some(token != b"0"),
            b'k' => result.key = Some(token.to_vec()),
            b'O' => result.opaque = Some(token.to_vec()),
            b'W' => result.won = true,
            b'Z' => result.busy = true,
            b'X' => result.stale = true,
            b'b' => key_base64 = true,
            _ => {}
        }
    }
    if key_base64 && let Some(key) = &result.key {
        result.key = Some(base64_decode(key)?);
    }
    Ok(result)
}

/// Parse an `me` response into its `name=value` fields. Returns `None` on a
/// miss (`EN`).
pub fn parse_debug_result(response: &MetaResponse) -> Result<Option<HashMap<String, String>>, MemcacheError> {
    if response.rc == ReturnCode::En {
        return Ok(None);
    }
    if response.rc != ReturnCode::Me {
        return Err(crate::error::ServerError::BadResponse(Cow::Owned(format!(
            "unexpected debug response {:?}",
            response.rc
        )))
        .into());
    }
    let mut fields = HashMap::new();
    // The first token is the (possibly base64) key; the rest are name=value.
    for token in response.flags.iter().skip(1) {
        let mut split = token.splitn(2, |&byte| byte == b'=');
        let name = split.next().unwrap_or_default();
        let value = split.next().unwrap_or_default();
        fields.insert(String::from_utf8(name.to_vec())?, String::from_utf8(value.to_vec())?);
    }
    Ok(Some(fields))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn build_get_default() {
        let command = build_get("foo", &GetOptions::default()).unwrap();
        assert_eq!(command.encode().unwrap(), b"mg foo v\r\n".to_vec());
    }

    #[test]
    fn build_get_all_flags() {
        let options = GetOptions {
            value: true,
            return_client_flags: true,
            return_cas: true,
            return_ttl: true,
            return_size: true,
            return_last_access: true,
            return_hit_before: true,
            return_key: true,
            no_lru_bump: true,
            touch: Some(60),
            vivify_ttl: Some(30),
            recache_ttl: Some(10),
            unless_cas: Some(7),
            new_cas: Some(8),
            opaque: Some(b"tok".to_vec()),
        };
        let command = build_get("foo", &options).unwrap();
        assert_eq!(
            command.encode().unwrap(),
            b"mg foo v f c t s l h k u T60 N30 R10 C7 E8 Otok\r\n".to_vec()
        );
    }

    #[test]
    fn build_get_validation() {
        let options = GetOptions {
            recache_ttl: Some(0),
            ..GetOptions::default()
        };
        assert!(build_get("foo", &options).is_err());
    }

    #[test]
    fn build_set_modes() {
        let command = build_set("foo", "bar", &SetOptions::default()).unwrap();
        assert_eq!(command.encode().unwrap(), b"ms foo 3\r\nbar\r\n".to_vec());

        let options = SetOptions {
            mode: SetMode::Add,
            ttl: Some(60),
            client_flags: Some(1),
            return_cas: true,
            ..SetOptions::default()
        };
        let command = build_set("foo", "bar", &options).unwrap();
        assert_eq!(command.encode().unwrap(), b"ms foo 3 ME c F1 T60\r\nbar\r\n".to_vec());
    }

    #[test]
    fn build_set_validation() {
        let append_with_ttl = SetOptions {
            mode: SetMode::Append,
            ttl: Some(60),
            ..SetOptions::default()
        };
        assert!(build_set("foo", "bar", &append_with_ttl).is_err());

        let set_with_vivify = SetOptions {
            vivify_ttl: Some(60),
            ..SetOptions::default()
        };
        assert!(build_set("foo", "bar", &set_with_vivify).is_err());

        let add_with_cas = SetOptions {
            mode: SetMode::Add,
            compare_cas: Some(1),
            ..SetOptions::default()
        };
        assert!(build_set("foo", "bar", &add_with_cas).is_err());
    }

    #[test]
    fn build_delete_flags() {
        let command = build_delete("foo", &DeleteOptions::default()).unwrap();
        assert_eq!(command.encode().unwrap(), b"md foo\r\n".to_vec());

        let options = DeleteOptions {
            invalidate: true,
            ttl: Some(30),
            compare_cas: Some(5),
            ..DeleteOptions::default()
        };
        let command = build_delete("foo", &options).unwrap();
        assert_eq!(command.encode().unwrap(), b"md foo I C5 T30\r\n".to_vec());

        let ttl_without_invalidate = DeleteOptions {
            ttl: Some(30),
            ..DeleteOptions::default()
        };
        assert!(build_delete("foo", &ttl_without_invalidate).is_err());
    }

    #[test]
    fn build_arithmetic_flags() {
        let command = build_arithmetic("counter", &ArithmeticOptions::default()).unwrap();
        assert_eq!(command.encode().unwrap(), b"ma counter v\r\n".to_vec());

        let options = ArithmeticOptions {
            mode: ArithmeticMode::Decrement,
            delta: Some(2),
            initial: Some(0),
            initial_ttl: Some(60),
            ..ArithmeticOptions::default()
        };
        let command = build_arithmetic("counter", &options).unwrap();
        assert_eq!(command.encode().unwrap(), b"ma counter MD v D2 N60 J0\r\n".to_vec());

        let initial_without_ttl = ArithmeticOptions {
            initial: Some(0),
            ..ArithmeticOptions::default()
        };
        assert!(build_arithmetic("counter", &initial_without_ttl).is_err());
    }

    #[test]
    fn build_noop_and_debug() {
        assert_eq!(build_noop().encode().unwrap(), b"mn\r\n".to_vec());
        assert_eq!(build_debug("foo").unwrap().encode().unwrap(), b"me foo\r\n".to_vec());
        assert!(build_debug(b"a key".to_vec()).is_err());
    }

    #[test]
    fn opaque_validation() {
        for opaque in [&b""[..], &[b'x'; 33][..], b"a b", b"a\x7f"] {
            let options = GetOptions {
                opaque: Some(opaque.to_vec()),
                ..GetOptions::default()
            };
            assert!(build_get("foo", &options).is_err(), "opaque {:?} should fail", opaque);
        }
    }

    #[test]
    fn parse_meta_result_flags() {
        let mut response = MetaResponse::parse_header(b"VA 3 f1 c42 t-1 h1 l5 s3 W Otok kZm9v b").unwrap();
        response.value = Some(b"bar".to_vec());
        let result = parse_meta_result(response).unwrap();
        assert!(result.ok());
        assert_eq!(result.rc, ReturnCode::Va);
        assert_eq!(result.value, Some(b"bar".to_vec()));
        assert_eq!(result.client_flags, Some(1));
        assert_eq!(result.cas, Some(42));
        assert_eq!(result.ttl, Some(-1));
        assert_eq!(result.hit_before, Some(true));
        assert_eq!(result.last_access, Some(5));
        assert_eq!(result.size, Some(3));
        assert!(result.won);
        assert!(!result.busy);
        assert!(!result.stale);
        assert_eq!(result.opaque, Some(b"tok".to_vec()));
        assert_eq!(result.key, Some(b"foo".to_vec()));
    }

    #[test]
    fn parse_meta_result_miss() {
        let response = MetaResponse::parse_header(b"EN").unwrap();
        let result = parse_meta_result(response).unwrap();
        assert!(!result.ok());
        assert_eq!(result.rc, ReturnCode::En);
    }

    #[test]
    fn parse_debug_result_fields() {
        let response = MetaResponse::parse_header(b"ME foo exp=-1 la=2 cas=3").unwrap();
        let fields = parse_debug_result(&response).unwrap().unwrap();
        assert_eq!(fields.get("exp").map(String::as_str), Some("-1"));
        assert_eq!(fields.get("la").map(String::as_str), Some("2"));
        assert_eq!(fields.get("cas").map(String::as_str), Some("3"));

        let miss = MetaResponse::parse_header(b"EN").unwrap();
        assert!(parse_debug_result(&miss).unwrap().is_none());

        let unexpected = MetaResponse::parse_header(b"HD").unwrap();
        assert!(parse_debug_result(&unexpected).is_err());
    }
}