use super::canonical::{dump_otoml, load_otoml};
use super::error::{OtomlError, Result};
use serde::{Serialize, de::DeserializeOwned};
pub trait OtomlSerialize: Serialize + DeserializeOwned + Sized {
fn to_otoml(&self) -> Result<String> {
dump_otoml(self)
}
fn from_otoml(s: &str) -> Result<Self> {
load_otoml(s)
}
fn to_json(&self) -> Result<String> {
serde_json::to_string(self).map_err(|e| OtomlError::JsonSerialize(e.to_string()))
}
fn to_json_pretty(&self) -> Result<String> {
serde_json::to_string_pretty(self).map_err(|e| OtomlError::JsonSerialize(e.to_string()))
}
fn from_json(s: &str) -> Result<Self> {
serde_json::from_str(s).map_err(|e| OtomlError::JsonDeserialize(e.to_string()))
}
}
impl<T> OtomlSerialize for T where T: Serialize + DeserializeOwned {}
#[cfg(test)]
mod tests {
use super::*;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
struct TestUser {
name: String,
age: u32,
}
#[test]
fn test_otoml_roundtrip() {
let user = TestUser {
name: "Alice".to_string(),
age: 30,
};
let otoml = user.to_otoml().unwrap();
assert!(otoml.starts_with("O:\n"));
let loaded = TestUser::from_otoml(&otoml).unwrap();
assert_eq!(user, loaded);
}
#[test]
fn test_json_roundtrip() {
let user = TestUser {
name: "Bob".to_string(),
age: 25,
};
let json = user.to_json().unwrap();
assert!(json.contains("\"name\":\"Bob\""));
let loaded = TestUser::from_json(&json).unwrap();
assert_eq!(user, loaded);
}
#[test]
fn test_json_pretty() {
let user = TestUser {
name: "Charlie".to_string(),
age: 35,
};
let json = user.to_json_pretty().unwrap();
assert!(json.contains('\n'));
assert!(json.contains(" ")); }
}