2021-32-bit-holiday-jam/src/file.rs

35 lines
622 B
Rust

use std::convert::TryInto;
use std::fs::File;
use std::io::Read;
use std::path::Path;
#[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>
where P: AsRef <Path>
{
let mut f = File::open (name)?;
let len = f.metadata ()?.len ();
if len > max_size {
return Err (LoadFileErr::FileTooBig);
}
let mut data = vec! [0u8; len.try_into ().unwrap ()];
f.read_exact (&mut data [..])?;
Ok (data)
}