mirror of https://github.com/zkat/cacache-rs.git
feat(get): add get::open() and get::open_hash()
This commit is contained in:
parent
54d159740a
commit
6e9a2f9f87
|
|
@ -1,11 +1,37 @@
|
|||
use std::fs;
|
||||
use std::fs::{self, File};
|
||||
use std::path::Path;
|
||||
|
||||
use ssri::Integrity;
|
||||
use ssri::{Algorithm, Integrity, IntegrityChecker};
|
||||
|
||||
use crate::content::path;
|
||||
use crate::errors::Error;
|
||||
|
||||
pub struct Reader {
|
||||
fd: File,
|
||||
checker: IntegrityChecker,
|
||||
}
|
||||
|
||||
impl std::io::Read for Reader {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
let amt = self.fd.read(buf)?;
|
||||
self.checker.input(&buf);
|
||||
Ok(amt)
|
||||
}
|
||||
}
|
||||
|
||||
impl Reader {
|
||||
pub fn check(self) -> Result<Algorithm, Error> {
|
||||
self.checker.result().ok_or(Error::IntegrityError)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open<'a>(cache: &Path, sri: Integrity) -> Result<Reader, Error> {
|
||||
Ok(Reader {
|
||||
fd: File::open(cache)?,
|
||||
checker: IntegrityChecker::new(sri),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read(cache: &Path, sri: &Integrity) -> Result<Vec<u8>, Error> {
|
||||
let cpath = path::content_path(&cache, &sri);
|
||||
let ret = fs::read(&cpath)?;
|
||||
|
|
|
|||
42
src/get.rs
42
src/get.rs
|
|
@ -1,12 +1,50 @@
|
|||
//! Functions for reading from cache.
|
||||
use std::path::Path;
|
||||
|
||||
use ssri::Integrity;
|
||||
use ssri::{Algorithm, Integrity};
|
||||
|
||||
use crate::content::read;
|
||||
use crate::content::read::{self, Reader};
|
||||
use crate::errors::Error;
|
||||
use crate::index::{self, Entry};
|
||||
|
||||
pub struct Get {
|
||||
reader: Reader,
|
||||
}
|
||||
|
||||
impl std::io::Read for Get {
|
||||
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
|
||||
self.reader.read(buf)
|
||||
}
|
||||
}
|
||||
|
||||
impl Get {
|
||||
pub fn check(self) -> Result<Algorithm, Error> {
|
||||
self.reader.check()
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open<P, K>(cache: P, key: K) -> Result<Get, Error>
|
||||
where
|
||||
P: AsRef<Path>,
|
||||
K: AsRef<str>,
|
||||
{
|
||||
if let Some(entry) = index::find(cache.as_ref(), key.as_ref())? {
|
||||
let reader = read::open(cache.as_ref(), entry.integrity)?;
|
||||
Ok(Get { reader })
|
||||
} else {
|
||||
Err(Error::NotFound)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn open_hash<P>(cache: P, sri: Integrity) -> Result<Get, Error>
|
||||
where
|
||||
P: AsRef<Path>
|
||||
{
|
||||
Ok(Get {
|
||||
reader: read::open(cache.as_ref(), sri)?,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn read<P: AsRef<Path>, K: AsRef<str>>(cache: P, key: K) -> Result<Vec<u8>, Error> {
|
||||
if let Some(entry) = index::find(cache.as_ref(), key.as_ref())? {
|
||||
read_hash(cache, &entry.integrity)
|
||||
|
|
|
|||
Loading…
Reference in New Issue