use std::fs;
use std::fmt;
use std_prelude::*;
use super::{Error, Result};
use super::{PathArc, PathFile};
pub struct FileOpen {
pub(crate) path: PathFile,
pub(crate) file: fs::File,
}
impl FileOpen {
pub fn open<P: AsRef<Path>>(path: P, options: fs::OpenOptions) -> Result<FileOpen> {
let file = options
.open(&path)
.map_err(|err| Error::new(err, "opening", PathArc::new(&path)))?;
let path = PathFile::new(path)?;
Ok(FileOpen {
path: path,
file: file,
})
}
pub fn open_path(path: PathFile, options: fs::OpenOptions) -> Result<FileOpen> {
let file = options
.open(&path)
.map_err(|err| Error::new(err, "opening", path.clone().into()))?;
Ok(FileOpen {
path: path,
file: file,
})
}
pub fn path(&self) -> &PathFile {
&self.path
}
pub fn metadata(&self) -> Result<fs::Metadata> {
self.file
.metadata()
.map_err(|err| Error::new(err, "getting metadata for", self.path.clone().into()))
}
pub fn try_clone(&self) -> Result<FileOpen> {
let file = self.file
.try_clone()
.map_err(|err| Error::new(err, "cloning file handle for", self.path.clone().into()))?;
Ok(FileOpen {
file: file,
path: self.path.clone(),
})
}
}
impl fmt::Debug for FileOpen {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "Open(")?;
self.path.fmt(f)?;
write!(f, ")")
}
}
impl Into<fs::File> for FileOpen {
fn into(self) -> fs::File {
self.file
}
}