2020-02-16 23:21:32 +00:00
|
|
|
use std::convert::TryInto;
|
|
|
|
use std::fs::File;
|
|
|
|
use std::io::Read;
|
|
|
|
use std::path::Path;
|
|
|
|
|
2020-03-08 02:32:17 +00:00
|
|
|
#[derive (Debug)]
|
|
|
|
pub enum LoadFileErr {
|
|
|
|
FileTooBig,
|
|
|
|
Io (std::io::Error),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From <std::io::Error> for LoadFileErr {
|
|
|
|
fn from (e: std::io::Error) -> Self {
|
|
|
|
Self::Io (e)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
pub fn load_small_file <P> (name: P, max_size: u64)
|
|
|
|
-> Result <Vec <u8>, LoadFileErr>
|
2020-02-16 23:21:32 +00:00
|
|
|
where P: AsRef <Path>
|
|
|
|
{
|
2020-03-08 02:32:17 +00:00
|
|
|
let mut f = File::open (name)?;
|
|
|
|
let len = f.metadata ()?.len ();
|
2020-02-16 23:21:32 +00:00
|
|
|
|
|
|
|
if len > max_size {
|
2020-03-08 02:32:17 +00:00
|
|
|
return Err (LoadFileErr::FileTooBig);
|
2020-02-16 23:21:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
let mut data = vec! [0u8; len.try_into ().unwrap ()];
|
|
|
|
|
2020-03-08 02:32:17 +00:00
|
|
|
f.read_exact (&mut data [..])?;
|
2020-02-16 23:21:32 +00:00
|
|
|
|
2020-03-08 02:32:17 +00:00
|
|
|
Ok (data)
|
2020-02-16 23:21:32 +00:00
|
|
|
}
|