modio-logger-db 0.11.1

modio-logger Dbus service
Documentation
use crate::error::Error;
use serde::{Deserialize, Serialize};

#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum DataType {
    F64,
    String,
    Bool,
    U64,
}

impl std::fmt::Display for DataType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::F64 => write!(f, "f64"),
            Self::String => write!(f, "string"),
            Self::Bool => write!(f, "bool"),
            Self::U64 => write!(f, "u64"),
        }
    }
}

impl DataType {
    pub fn vec_from_str(value: &str) -> Result<Vec<Self>, Error> {
        let res: Vec<Self> = serde_json::from_str(value)?;
        Ok(res)
    }
}

#[test]
fn test_datatype_string_roundtrip() {
    fn around(b: DataType) -> DataType {
        let sval = serde_json::to_string(&b).expect("Failed to serialize value");
        serde_json::from_str(&sval).expect("Failed to parse back again")
    }
    assert_eq!(DataType::F64, around(DataType::F64));
    assert_eq!(DataType::String, around(DataType::String));
    assert_eq!(DataType::Bool, around(DataType::Bool));
    assert_eq!(DataType::U64, around(DataType::U64));
}

#[test]
fn test_datatype_display() {
    let out = format!("{}", DataType::String);
    assert_eq!(out, "string");
}

#[test]
fn test_datatype_json_trip() {
    let data: Vec<DataType> = vec![
        DataType::F64,
        DataType::Bool,
        DataType::U64,
        DataType::String,
    ];

    let jsoned = serde_json::to_string(&data).expect("Failed to serialize");
    let original: Vec<DataType> = serde_json::from_str(&jsoned).expect("Failed to deserialize");
    let back = DataType::vec_from_str(&jsoned).expect("Failed to deserialize");
    assert_eq!(data, back, "One is not like the other");
    assert_eq!(jsoned, r#"["f64","bool","u64","string"]"#);
    assert_eq!(
        data, original,
        "Before and after serialization should match"
    );
}