distant_protocol/common/
cmd.rs

1use std::ops::{Deref, DerefMut};
2
3use derive_more::{Display, From, Into};
4use serde::{Deserialize, Serialize};
5
6/// Represents some command with arguments to execute
7#[derive(Clone, Debug, Display, From, Into, Hash, PartialEq, Eq, Serialize, Deserialize)]
8pub struct Cmd(String);
9
10impl Cmd {
11    /// Creates a new command from the given `cmd`
12    pub fn new(cmd: impl Into<String>) -> Self {
13        Self(cmd.into())
14    }
15}
16
17impl Deref for Cmd {
18    type Target = String;
19
20    fn deref(&self) -> &Self::Target {
21        &self.0
22    }
23}
24
25impl DerefMut for Cmd {
26    fn deref_mut(&mut self) -> &mut Self::Target {
27        &mut self.0
28    }
29}
30
31#[cfg(test)]
32mod tests {
33    use super::*;
34
35    #[test]
36    fn should_be_able_to_serialize_to_json() {
37        let cmd = Cmd::new("echo some text");
38
39        let value = serde_json::to_value(cmd).unwrap();
40        assert_eq!(value, serde_json::json!("echo some text"));
41    }
42
43    #[test]
44    fn should_be_able_to_deserialize_from_json() {
45        let value = serde_json::json!("echo some text");
46
47        let cmd: Cmd = serde_json::from_value(value).unwrap();
48        assert_eq!(cmd, Cmd::new("echo some text"));
49    }
50
51    #[test]
52    fn should_be_able_to_serialize_to_msgpack() {
53        let cmd = Cmd::new("echo some text");
54
55        // NOTE: We don't actually check the output here because it's an implementation detail
56        // and could change as we change how serialization is done. This is merely to verify
57        // that we can serialize since there are times when serde fails to serialize at
58        // runtime.
59        let _ = rmp_serde::encode::to_vec_named(&cmd).unwrap();
60    }
61
62    #[test]
63    fn should_be_able_to_deserialize_from_msgpack() {
64        // NOTE: It may seem odd that we are serializing just to deserialize, but this is to
65        // verify that we are not corrupting or causing issues when serializing on a
66        // client/server and then trying to deserialize on the other side. This has happened
67        // enough times with minor changes that we need tests to verify.
68        let buf = rmp_serde::encode::to_vec_named(&Cmd::new("echo some text")).unwrap();
69
70        let cmd: Cmd = rmp_serde::decode::from_slice(&buf).unwrap();
71        assert_eq!(cmd, Cmd::new("echo some text"));
72    }
73}