metalize/src/collection.rs

57 lines
1.3 KiB
Rust
Raw Normal View History

2024-04-12 08:52:43 -04:00
use serde::Serialize;
2024-04-09 19:43:05 -04:00
use serde::de::DeserializeOwned;
2024-04-12 08:52:43 -04:00
use bson::Document;
2024-04-09 19:43:05 -04:00
use std::fs::File;
2024-04-12 08:52:43 -04:00
use std::io::{BufReader, Seek, Write};
2024-04-09 19:43:05 -04:00
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-12 08:54:00 -04:00
pub fn load(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
}
}