modio_logger_db/types/
datatype.rs1use crate::error::Error;
2use serde::{Deserialize, Serialize};
3
4#[derive(Debug, Copy, Clone, PartialEq, Eq, Serialize, Deserialize)]
5#[serde(rename_all = "lowercase")]
6pub enum DataType {
7 F64,
8 String,
9 Bool,
10 U64,
11}
12
13impl std::fmt::Display for DataType {
14 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
15 match self {
16 Self::F64 => write!(f, "f64"),
17 Self::String => write!(f, "string"),
18 Self::Bool => write!(f, "bool"),
19 Self::U64 => write!(f, "u64"),
20 }
21 }
22}
23
24impl DataType {
25 pub fn vec_from_str(value: &str) -> Result<Vec<Self>, Error> {
26 let res: Vec<Self> = serde_json::from_str(value)?;
27 Ok(res)
28 }
29}
30
31#[test]
32fn test_datatype_string_roundtrip() {
33 fn around(b: DataType) -> DataType {
34 let sval = serde_json::to_string(&b).expect("Failed to serialize value");
35 serde_json::from_str(&sval).expect("Failed to parse back again")
36 }
37 assert_eq!(DataType::F64, around(DataType::F64));
38 assert_eq!(DataType::String, around(DataType::String));
39 assert_eq!(DataType::Bool, around(DataType::Bool));
40 assert_eq!(DataType::U64, around(DataType::U64));
41}
42
43#[test]
44fn test_datatype_display() {
45 let out = format!("{}", DataType::String);
46 assert_eq!(out, "string");
47}
48
49#[test]
50fn test_datatype_json_trip() {
51 let data: Vec<DataType> = vec![
52 DataType::F64,
53 DataType::Bool,
54 DataType::U64,
55 DataType::String,
56 ];
57
58 let jsoned = serde_json::to_string(&data).expect("Failed to serialize");
59 let original: Vec<DataType> = serde_json::from_str(&jsoned).expect("Failed to deserialize");
60 let back = DataType::vec_from_str(&jsoned).expect("Failed to deserialize");
61 assert_eq!(data, back, "One is not like the other");
62 assert_eq!(jsoned, r#"["f64","bool","u64","string"]"#);
63 assert_eq!(
64 data, original,
65 "Before and after serialization should match"
66 );
67}