2024-04-09 19:43:05 -04:00
|
|
|
use serde::{Deserialize, Serialize};
|
|
|
|
|
use serde::de::DeserializeOwned;
|
|
|
|
|
use bson::{bson, Bson, doc, Document};
|
|
|
|
|
use std::fs::File;
|
|
|
|
|
use std::io::{BufReader, Seek, Write, Read};
|
|
|
|
|
use std::error::Error;
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
pub struct Collection<T>
|
|
|
|
|
{
|
|
|
|
|
pub entries: Vec<T>
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Collection<T>{
|
|
|
|
|
fn get(&self) -> Option<&T>{
|
|
|
|
|
self.entries.get(0)
|
|
|
|
|
}
|
2024-04-11 22:01:18 -04:00
|
|
|
fn new( entries: Vec<T>) -> Collection<T>{
|
|
|
|
|
Collection{
|
|
|
|
|
entries:entries
|
|
|
|
|
}
|
2024-04-09 19:43:05 -04:00
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Collection<T>
|
|
|
|
|
where
|
|
|
|
|
T : Serialize
|
|
|
|
|
{
|
|
|
|
|
pub fn save<W>(&self, mut writer : W) -> Result<(), Box<dyn Error>>
|
|
|
|
|
where W : Write {
|
|
|
|
|
for a in self.entries.iter(){
|
|
|
|
|
let d = bson::to_document(a)?;
|
|
|
|
|
d.to_writer(&mut writer)?;
|
|
|
|
|
}
|
|
|
|
|
Ok(())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
impl<T> Collection<T>
|
|
|
|
|
where
|
|
|
|
|
T: DeserializeOwned
|
|
|
|
|
{
|
2024-04-11 22:01:18 -04:00
|
|
|
pub fn load(mut file: File) -> Result<Collection<T>, Box<dyn Error>>{
|
2024-04-09 19:43:05 -04:00
|
|
|
let n = file.metadata()?.len();
|
|
|
|
|
let mut reader = BufReader::new(file);
|
|
|
|
|
let mut current_position = reader.stream_position()?;
|
2024-04-11 22:01:18 -04:00
|
|
|
let mut entries = Vec::new();
|
2024-04-09 19:43:05 -04:00
|
|
|
while current_position < n{
|
|
|
|
|
let d = Document::from_reader(&mut reader)?;
|
|
|
|
|
let h: T = bson::from_document(d)?;
|
2024-04-11 22:01:18 -04:00
|
|
|
entries.push(h);
|
2024-04-09 19:43:05 -04:00
|
|
|
current_position = reader.stream_position()?;
|
|
|
|
|
}
|
2024-04-11 22:01:18 -04:00
|
|
|
Ok(Collection::new( entries))
|
2024-04-09 19:43:05 -04:00
|
|
|
}
|
|
|
|
|
}
|