json_db_rs 0.1.0

Database for simple projects
Documentation
use serde::{Deserialize, Serialize};
use std::{
    fs::{self, File},
    io::Read,
};

#[derive(Debug)]
pub struct Connection<T: for<'a> Deserialize<'a> + Serialize + Clone> {
    memory: Vec<T>,
    file_path: String,
}

impl<T: for<'a> Deserialize<'a> + Serialize + Clone> Connection<T> {
    pub fn read_data(&mut self) -> &Vec<T> {
        //self.memory =
        let mut buf = String::new();
        File::open(&self.file_path)
            .unwrap()
            .read_to_string(&mut buf)
            .unwrap();
        self.memory = serde_json::from_str(&buf).unwrap();
        return &self.memory;
    }

    pub fn append(&mut self, item: T) {
        self.memory.push(item);
    }

    pub fn sync(&self) {
        fs::write(
            &self.file_path,
            serde_json::to_string(&self.memory).unwrap(),
        )
        .unwrap();
    }

    pub fn drop(&mut self) {
        self.memory = Vec::new();
        self.sync();
    }
}

pub fn connect<T: for<'a> Deserialize<'a> + Serialize + Clone>(
    file_path: &str,
    data: Vec<T>,
) -> Connection<T> {
    let mut buf = String::new();
    File::open(file_path)
        .unwrap()
        .read_to_string(&mut buf)
        .unwrap();
    Connection {
        memory: data,
        file_path: String::from(file_path),
    }
}