#![doc(html_root_url = "https://docs.rs/fs-err/2.2.0")]
#![deny(missing_debug_implementations, missing_docs)]
mod dir;
mod errors;
mod file;
use std::fs;
use std::io::{self, Read, Write};
use std::path::{Path, PathBuf};
use errors::{CopyError, Error, ErrorKind};
pub use dir::*;
pub use file::*;
pub fn read<P: AsRef<Path> + Into<PathBuf>>(path: P) -> io::Result<Vec<u8>> {
let mut file = File::open(path)?;
let mut bytes = Vec::with_capacity(initial_buffer_size(&file));
file.read_to_end(&mut bytes)?;
Ok(bytes)
}
pub fn read_to_string<P: AsRef<Path> + Into<PathBuf>>(path: P) -> io::Result<String> {
let mut file = File::open(path)?;
let mut string = String::with_capacity(initial_buffer_size(&file));
file.read_to_string(&mut string)?;
Ok(string)
}
pub fn write<P: AsRef<Path> + Into<PathBuf>, C: AsRef<[u8]>>(
path: P,
contents: C,
) -> io::Result<()> {
File::create(path)?.write_all(contents.as_ref())
}
pub fn copy<P, Q>(from: P, to: Q) -> io::Result<u64>
where
P: AsRef<Path> + Into<PathBuf>,
Q: AsRef<Path> + Into<PathBuf>,
{
fs::copy(from.as_ref(), to.as_ref()).map_err(|source| CopyError::new(source, from, to))
}
pub fn metadata<P: AsRef<Path> + Into<PathBuf>>(path: P) -> io::Result<fs::Metadata> {
fs::metadata(path.as_ref()).map_err(|source| Error::new(source, ErrorKind::Metadata, path))
}
fn initial_buffer_size(file: &File) -> usize {
file.file()
.metadata()
.map(|m| m.len() as usize + 1)
.unwrap_or(0)
}