use serde::{Deserialize, Serialize};
use std::collections::HashMap;
#[derive(Serialize, Deserialize, Debug)]
pub struct Computer {
secret: bool,
question: String,
awnser: Option<usize>,
}
#[dbstruct::dbstruct(db=sled)]
pub struct Test {
#[dbstruct(Default)]
the_awnser: u8,
#[dbstruct(Default = "vec![\"What is Life\".to_owned()]")]
questions: Vec<String>,
#[dbstruct(Default)]
computers: HashMap<String, Computer>,
}
fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempdir::TempDir::new("dbstruct_examples")?;
let path = dir.path().join("advanced");
let db = Test::new(&path)?;
assert_eq!(0, db.the_awnser().get()?);
db.the_awnser().set(&42)?;
let mut questions = db.questions().get()?;
assert_eq!(vec!["What is Life".to_owned()], questions);
questions.push("What is the Universe".to_owned());
questions.push("What is Everything".to_owned());
db.questions().set(&questions)?;
let deep_thought = Computer {
secret: false,
question: "The Ultimate Question of Life, the Universe, and Everything".to_owned(),
awnser: Some(42),
};
let a_planet = Computer {
secret: true,
question: "What is The Ultimate Question".to_owned(),
awnser: None, };
let mut computers = HashMap::new();
computers.insert("Deep Thought".to_owned(), deep_thought);
computers.insert("Earth".to_owned(), a_planet);
db.computers().set(&computers)?;
std::mem::drop(db); let db = Test::new(&path)?;
assert_eq!(42u8, db.the_awnser().get()?);
let second = &db.questions().get()?[1];
assert_eq!(&"What is the Universe".to_owned(), second);
let computers = db.computers().get()?;
let earth = computers.get(&"Earth".to_owned());
assert_eq!(earth.map(|c| c.secret), Some(true));
Ok(())
}