use serde::{Deserialize, Serialize};
use libconfig::{from_str, to_string};
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct AppConfig {
version: String,
application: Application,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Application {
window: Window,
constants: Constants,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Window {
title: String,
size: Size,
pos: Position,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Size {
w: i32,
h: i32,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Position {
x: i32,
y: i32,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
struct Constants {
pi: f64,
columns: Vec<String>,
}
fn main() {
let config = AppConfig {
version: "1.0".to_string(),
application: Application {
window: Window {
title: "My Application".to_string(),
size: Size { w: 640, h: 480 },
pos: Position { x: 350, y: 250 },
},
constants: Constants {
pi: 3.141592654,
columns: vec![
"Last Name".to_string(),
"First Name".to_string(),
"MI".to_string(),
],
},
},
};
println!("=== Serialization ===");
let serialized = to_string(&config).expect("Failed to serialize");
println!("{}", serialized);
println!("\n=== Deserialization ===");
let libconfig_str = r#"
version = "1.0";
application = {
window = {
title = "My Application";
size = { w = 640; h = 480; };
pos = { x = 350; y = 250; };
};
constants = {
pi = 3.141592654;
columns = ["Last Name", "First Name", "MI"];
};
};
"#;
let deserialized: AppConfig = from_str(libconfig_str).expect("Failed to deserialize");
println!("{:#?}", deserialized);
println!("\n=== Round-trip Verification ===");
let reserialized = to_string(&deserialized).expect("Failed to re-serialize");
let redeserialized: AppConfig = from_str(&reserialized).expect("Failed to re-deserialize");
if config == redeserialized {
println!("Round-trip successful!");
} else {
println!("Round-trip failed!");
}
}