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
use crate::read::read_index;
use std::fs::{self, File, OpenOptions};
use std::io::{self, BufReader, ErrorKind, Read, Seek, SeekFrom};
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
use std::path::Path;
pub fn extract<P: AsRef<Path>>(path: P) -> io::Result<()> {
let mut archive = BufReader::new(File::open(path)?);
let index = read_index(&mut archive)?;
for item in index {
archive.seek(SeekFrom::Start(item.offset as u64))?;
let mut data = archive.by_ref().take(item.length as u64);
{
let dir = Path::new(&item.name).parent().ok_or_else(|| {
io::Error::new(ErrorKind::InvalidData, "File name must not be empty")
})?;
fs::create_dir_all(dir)?;
}
let mut options = OpenOptions::new();
options.write(true);
options.create(true);
#[cfg(unix)]
{
options.mode(item.flags);
}
let mut file = options.open(item.name)?;
let bytes_written = io::copy(&mut data, &mut file)?;
if bytes_written != item.length as u64 {
return Err(io::Error::new(
ErrorKind::UnexpectedEof,
"Unexpected end of file",
));
}
}
Ok(())
}