-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbyte_source.rs
61 lines (48 loc) · 1.45 KB
/
byte_source.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
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use error::{Result, ErrorKind, ResultExt};
#[derive(Clone, Debug)]
pub enum ByteSource {
File(PathBuf),
Memory(Vec<u8>)
}
pub fn vec_from_byte_source(source: ByteSource) -> Result<Vec<u8>> {
match source {
ByteSource::File(path) => {
let mut file = File::open(&path)
.chain_err(||ErrorKind::ByteSourceExpansionFailed)?;
let mut buffer = vec!();
file.read_to_end(&mut buffer)
.chain_err(||ErrorKind::ByteSourceExpansionFailed)?;
Ok(buffer)
},
ByteSource::Memory(vec) => Ok(vec)
}
}
pub fn write_byte_source_to_file(source: ByteSource, path: &Path) -> Result<()> {
let content = vec_from_byte_source(source)?;
let mut file = File::create(path)?;
file.write_all(&content)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn vec_byte_source() {
let bytesource = ByteSource::Memory(vec!(0,1,2,3));
assert_eq!(vec_from_byte_source(bytesource).unwrap(), vec!(0,1,2,3));
}
#[test]
fn file_byte_source() {
let bs = ByteSource::File(PathBuf::from("test/files/exif1.txt"));
assert_eq!(
vec_from_byte_source(bs).unwrap(),
include_bytes!("../test/files/exif1.txt")
.into_iter()
.map(|x| *x)
.collect::<Vec<_>>()
);
}
}