Maraiah/maraiah/file.rs

68 lines
1.4 KiB
Rust
Raw Normal View History

//! File utilities.
2019-06-23 06:21:49 -07:00
use crate::{err::*, machdr};
use std::{fs, path::Path, io::{SeekFrom, prelude::*}};
2019-03-01 01:27:14 -08:00
/// Confirms that the path `p` is a folder.
pub fn validate_folder_path(p: &str) -> ResultS<()>
{
2019-07-05 20:21:11 -07:00
let at = fs::metadata(p)?;
if at.is_dir() {
Ok(())
} else {
Err(err_msg("not a directory"))
}
}
2019-06-23 06:21:49 -07:00
/// Opens the file at `path` and skips past any macintosh headers.
2019-06-25 03:52:21 -07:00
pub fn open_mac<P: AsRef<Path>>(path: P) -> ResultS<fs::File>
2019-06-23 06:21:49 -07:00
{
2019-07-05 20:21:11 -07:00
let mut fp = fs::File::open(path)?;
2019-06-23 06:21:49 -07:00
2019-07-05 20:21:11 -07:00
machdr::skip_mac_header(&mut fp);
2019-06-23 06:21:49 -07:00
2019-07-05 20:21:11 -07:00
Ok(fp)
2019-06-23 06:21:49 -07:00
}
impl<T> Drop for SeekBackToStart<T>
2019-07-05 20:21:11 -07:00
where T: Seek
{
2019-07-05 20:21:11 -07:00
fn drop(&mut self) {if self.fl {let _ = self.seek(SeekFrom::Start(0));}}
}
impl<T> std::ops::Deref for SeekBackToStart<T>
2019-07-05 20:21:11 -07:00
where T: Seek
{
2019-07-05 20:21:11 -07:00
type Target = T;
2019-07-05 20:21:11 -07:00
fn deref(&self) -> &Self::Target {&self.sc}
}
impl<T> std::ops::DerefMut for SeekBackToStart<T>
2019-07-05 20:21:11 -07:00
where T: Seek
{
2019-07-05 20:21:11 -07:00
fn deref_mut(&mut self) -> &mut Self::Target {&mut self.sc}
}
impl<T> SeekBackToStart<T>
2019-07-05 20:21:11 -07:00
where T: Seek
{
2019-07-05 20:21:11 -07:00
/// Creates a new `SeekBackToStart` object.
pub fn new(sc: T) -> Self {Self{sc, fl: true}}
2019-07-05 20:21:11 -07:00
/// Sets the seek-back flag.
pub fn set_seek(&mut self, fl: bool) {self.fl = fl;}
2019-07-05 20:21:11 -07:00
/// Returns the seek-back flag.
pub fn get_seek(&self) -> bool {self.fl}
}
/// Seeks back to the starting position of the inner object when losing scope,
/// unless a flag is set.
pub struct SeekBackToStart<T: Seek> {
2019-07-05 20:21:11 -07:00
sc: T,
fl: bool,
}
// EOF