Maraiah/maraiah/file.rs

68 lines
1.4 KiB
Rust

//! File utilities.
use crate::{err::*, machdr};
use std::{fs, path::Path, io::{SeekFrom, prelude::*}};
/// Confirms that the path `p` is a folder.
pub fn validate_folder_path(p: &str) -> ResultS<()>
{
let at = fs::metadata(p)?;
if at.is_dir() {
Ok(())
} else {
Err(err_msg("not a directory"))
}
}
/// Opens the file at `path` and skips past any macintosh headers.
pub fn open_mac<P: AsRef<Path>>(path: P) -> ResultS<fs::File>
{
let mut fp = fs::File::open(path)?;
machdr::skip_mac_header(&mut fp);
Ok(fp)
}
impl<T> Drop for SeekBackToStart<T>
where T: Seek
{
fn drop(&mut self) {if self.fl {let _ = self.seek(SeekFrom::Start(0));}}
}
impl<T> std::ops::Deref for SeekBackToStart<T>
where T: Seek
{
type Target = T;
fn deref(&self) -> &Self::Target {&self.sc}
}
impl<T> std::ops::DerefMut for SeekBackToStart<T>
where T: Seek
{
fn deref_mut(&mut self) -> &mut Self::Target {&mut self.sc}
}
impl<T> SeekBackToStart<T>
where T: Seek
{
/// Creates a new `SeekBackToStart` object.
pub fn new(sc: T) -> Self {Self{sc, fl: true}}
/// Sets the seek-back flag.
pub fn set_seek(&mut self, fl: bool) {self.fl = fl;}
/// 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> {
sc: T,
fl: bool,
}
// EOF