hightower_kv/
command.rs

1use serde::{Deserialize, Serialize};
2
3/// Commands that can be applied to the key-value store
4#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
5pub enum Command {
6    /// Sets a key to a value with version and timestamp
7    Set {
8        /// The key to set
9        key: Vec<u8>,
10        /// The value to store
11        value: Vec<u8>,
12        /// Version number for conflict resolution
13        version: u64,
14        /// Timestamp when the command was created
15        timestamp: i64,
16    },
17    /// Deletes a key with version and timestamp
18    Delete {
19        /// The key to delete
20        key: Vec<u8>,
21        /// Version number for conflict resolution
22        version: u64,
23        /// Timestamp when the command was created
24        timestamp: i64,
25    },
26}
27
28impl Command {
29    /// Returns the key referenced by this command
30    pub fn key(&self) -> &[u8] {
31        match self {
32            Command::Set { key, .. } | Command::Delete { key, .. } => key,
33        }
34    }
35
36    /// Returns the version number of this command
37    pub fn version(&self) -> u64 {
38        match self {
39            Command::Set { version, .. } | Command::Delete { version, .. } => *version,
40        }
41    }
42
43    /// Returns the timestamp of this command
44    pub fn timestamp(&self) -> i64 {
45        match self {
46            Command::Set { timestamp, .. } | Command::Delete { timestamp, .. } => *timestamp,
47        }
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn round_trip_serialization() {
57        let cmd = Command::Set {
58            key: b"k".to_vec(),
59            value: b"v".to_vec(),
60            version: 7,
61            timestamp: 42,
62        };
63        let bytes = serde_cbor::to_vec(&cmd).expect("serialize");
64        let decoded: Command = serde_cbor::from_slice(&bytes).expect("deserialize");
65        assert_eq!(decoded, cmd);
66    }
67
68    #[test]
69    fn key_accessor_returns_expected_slice() {
70        let cmd = Command::Delete {
71            key: b"alpha".to_vec(),
72            version: 1,
73            timestamp: 5,
74        };
75        assert_eq!(cmd.key(), b"alpha");
76        assert_eq!(cmd.version(), 1);
77        assert_eq!(cmd.timestamp(), 5);
78    }
79}