From 1047a782e5f1a0323f24e132c1b899ba1da0e51f Mon Sep 17 00:00:00 2001 From: Jiahao XU Date: Wed, 27 Jul 2022 20:36:13 +1000 Subject: [PATCH] Impl newtype `Records` and methods `load{_from_path}` Signed-off-by: Jiahao XU --- src/metafiles/binstall_v1.rs | 40 ++++++++++++++++++++++++++++++++++-- 1 file changed, 38 insertions(+), 2 deletions(-) diff --git a/src/metafiles/binstall_v1.rs b/src/metafiles/binstall_v1.rs index 8ce59a4a..e2ecac5d 100644 --- a/src/metafiles/binstall_v1.rs +++ b/src/metafiles/binstall_v1.rs @@ -1,5 +1,7 @@ use std::{ - cmp, fs, hash, + cmp, + collections::BTreeSet, + fs, hash, io::{self, Write}, iter::IntoIterator, path::{Path, PathBuf}, @@ -12,7 +14,7 @@ use serde::{Deserialize, Serialize}; use thiserror::Error; use url::Url; -use crate::{cargo_home, cratesio_url, FileLock}; +use crate::{cargo_home, cratesio_url, create_if_not_exist, FileLock}; #[derive(Debug, Serialize, Deserialize)] pub struct MetaData { @@ -109,3 +111,37 @@ where pub fn default_path() -> Result { Ok(cargo_home()?.join(".binstall-crates.toml")) } + +#[derive(Debug)] +pub struct Records { + file: FileLock, + data: BTreeSet, +} + +impl Records { + fn load_impl(&mut self) -> Result<(), Error> { + let reader = io::BufReader::with_capacity(1024, &mut self.file); + let stream_deser = serde_json::Deserializer::from_reader(reader).into_iter(); + + for res in stream_deser { + let item = res?; + + self.data.replace(item); + } + + Ok(()) + } + + pub fn load_from_path(path: impl AsRef) -> Result { + let mut this = Self { + file: FileLock::new_exclusive(create_if_not_exist(path.as_ref())?)?, + data: BTreeSet::default(), + }; + this.load_impl()?; + Ok(this) + } + + pub fn load() -> Result { + Self::load_from_path(default_path()?) + } +}