Use Cow instead of String

This commit is contained in:
Valentin Brandl 2019-04-29 20:37:20 +02:00
parent 39f11c14f5
commit a1c10938c5
No known key found for this signature in database
GPG Key ID: 30D341DD34118D7D

View File

@ -1,21 +1,22 @@
use crate::Error; use crate::Error;
use std::{ use std::{
borrow::Cow,
fs::{create_dir_all, File, OpenOptions}, fs::{create_dir_all, File, OpenOptions},
io::BufReader, io::BufReader,
path::Path, path::Path,
}; };
/// Enum to indicate the state of the cache /// Enum to indicate the state of the cache
pub(crate) enum CacheState { pub(crate) enum CacheState<'a> {
/// Current head and cached head are the same /// Current head and cached head are the same
Current(u64), Current(u64),
/// Cached head is older than current head /// Cached head is older than current head
Old(Cache), Old(Cache<'a>),
/// No cache was found /// No cache was found
No, No,
} }
impl CacheState { impl<'a> CacheState<'a> {
pub(crate) fn read_from_file(path: impl AsRef<Path>, head: &str) -> Result<CacheState, Error> { pub(crate) fn read_from_file(path: impl AsRef<Path>, head: &str) -> Result<CacheState, Error> {
if path.as_ref().exists() { if path.as_ref().exists() {
let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?; let cache: Cache = serde_json::from_reader(BufReader::new(File::open(path)?))?;
@ -29,7 +30,7 @@ impl CacheState {
} }
} }
pub(crate) fn calculate_new_cache(self, count: u64, head: String) -> Cache { pub(crate) fn calculate_new_cache(self, count: u64, head: Cow<'a, str>) -> Cache {
match self { match self {
CacheState::Old(mut cache) => { CacheState::Old(mut cache) => {
cache.head = head; cache.head = head;
@ -42,12 +43,12 @@ impl CacheState {
} }
#[derive(Serialize, Deserialize)] #[derive(Serialize, Deserialize)]
pub(crate) struct Cache { pub(crate) struct Cache<'a> {
pub head: String, pub head: Cow<'a, str>,
pub count: u64, pub count: u64,
} }
impl Cache { impl<'a> Cache<'a> {
pub(crate) fn write_to_file(&self, path: impl AsRef<Path>) -> Result<(), Error> { pub(crate) fn write_to_file(&self, path: impl AsRef<Path>) -> Result<(), Error> {
create_dir_all(path.as_ref().parent().ok_or(Error::Internal)?)?; create_dir_all(path.as_ref().parent().ok_or(Error::Internal)?)?;
serde_json::to_writer( serde_json::to_writer(