-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfile.rs
82 lines (64 loc) · 2.25 KB
/
file.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
use std::fs;
use std::io::{Cursor, Read, Seek, SeekFrom};
use std::path::Path;
use log::debug;
use crate::error::ManifestError;
use super::{FileHeader, Manifest};
#[derive(Debug, Default, Clone, PartialEq, Eq)]
pub struct ManifestFile {
file_header: FileHeader,
manifest: Manifest,
}
impl ManifestFile {
pub fn try_from_path<P>(path: P) -> Result<Self, ManifestError>
where
P: AsRef<Path>,
{
let bytes = match fs::read(path) {
Ok(result) => result,
Err(error) => return Err(ManifestError::ReadFileError(error)),
};
Self::try_from(&bytes[..])
}
}
impl TryFrom<Vec<u8>> for ManifestFile {
type Error = ManifestError;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
Self::try_from(&bytes[..])
}
}
impl TryFrom<&[u8]> for ManifestFile {
type Error = ManifestError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
let file_header = FileHeader::try_from(bytes)?;
let mut cursor = Cursor::new(bytes);
if let Err(error) = cursor.seek(SeekFrom::Start(file_header.offset.into())) {
return Err(ManifestError::SeekError(error));
};
debug!("Attempting to convert \"compressed_size\" into \"usize\".");
let compressed_size: usize = file_header.compressed_size.try_into()?;
debug!("Successfully converted \"compressed_size\" into \"usize\".");
let mut buf = vec![0u8; compressed_size];
cursor.read_exact(&mut buf)?;
debug!("Attempting to convert \"uncompressed_size\" into \"usize\".");
let uncompressed_size: usize = file_header.uncompressed_size.try_into()?;
debug!("Successfully converted \"uncompressed_size\" into \"usize\".");
let decompressed = match zstd::bulk::decompress(&buf, uncompressed_size) {
Ok(result) => result,
Err(error) => return Err(ManifestError::ZstdDecompressError(error)),
};
let manifest = Manifest::try_from(decompressed)?;
Ok(Self {
file_header,
manifest,
})
}
}
impl ManifestFile {
pub fn manifest_header(&self) -> &FileHeader {
&self.file_header
}
pub fn manifest(&self) -> &Manifest {
&self.manifest
}
}