use std::ops::{Deref, DerefMut};
use derive_more::{Display, From, Into};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Display, From, Into, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct Cmd(String);
impl Cmd {
pub fn new(cmd: impl Into<String>) -> Self {
Self(cmd.into())
}
pub fn program(&self) -> &str {
match self.0.split_once(' ') {
Some((program, _)) => program.trim(),
None => self.0.trim(),
}
}
pub fn arguments(&self) -> &str {
match self.0.split_once(' ') {
Some((_, arguments)) => arguments.trim(),
None => "",
}
}
}
impl Deref for Cmd {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl DerefMut for Cmd {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn should_be_able_to_serialize_to_json() {
let cmd = Cmd::new("echo some text");
let value = serde_json::to_value(cmd).unwrap();
assert_eq!(value, serde_json::json!("echo some text"));
}
#[test]
fn should_be_able_to_deserialize_from_json() {
let value = serde_json::json!("echo some text");
let cmd: Cmd = serde_json::from_value(value).unwrap();
assert_eq!(cmd, Cmd::new("echo some text"));
}
#[test]
fn should_be_able_to_serialize_to_msgpack() {
let cmd = Cmd::new("echo some text");
let _ = rmp_serde::encode::to_vec_named(&cmd).unwrap();
}
#[test]
fn should_be_able_to_deserialize_from_msgpack() {
let buf = rmp_serde::encode::to_vec_named(&Cmd::new("echo some text")).unwrap();
let cmd: Cmd = rmp_serde::decode::from_slice(&buf).unwrap();
assert_eq!(cmd, Cmd::new("echo some text"));
}
}