use axio::{Result, SeekFrom, prelude::*};
use core::fmt;
use crate::fops;
pub type FileType = fops::FileType;
pub type Permissions = fops::FilePerm;
pub struct File {
inner: fops::File,
}
pub struct Metadata(fops::FileAttr);
#[derive(Clone, Debug)]
pub struct OpenOptions(fops::OpenOptions);
impl Default for OpenOptions {
fn default() -> Self {
Self::new()
}
}
impl OpenOptions {
pub const fn new() -> Self {
OpenOptions(fops::OpenOptions::new())
}
pub fn read(&mut self, read: bool) -> &mut Self {
self.0.read(read);
self
}
pub fn write(&mut self, write: bool) -> &mut Self {
self.0.write(write);
self
}
pub fn append(&mut self, append: bool) -> &mut Self {
self.0.append(append);
self
}
pub fn truncate(&mut self, truncate: bool) -> &mut Self {
self.0.truncate(truncate);
self
}
pub fn create(&mut self, create: bool) -> &mut Self {
self.0.create(create);
self
}
pub fn create_new(&mut self, create_new: bool) -> &mut Self {
self.0.create_new(create_new);
self
}
pub fn open(&self, path: &str) -> Result<File> {
fops::File::open(path, &self.0).map(|inner| File { inner })
}
}
impl Metadata {
pub const fn file_type(&self) -> FileType {
self.0.file_type()
}
pub const fn is_dir(&self) -> bool {
self.0.is_dir()
}
pub const fn is_file(&self) -> bool {
self.0.is_file()
}
#[allow(clippy::len_without_is_empty)]
pub const fn len(&self) -> u64 {
self.0.size()
}
pub const fn permissions(&self) -> Permissions {
self.0.perm()
}
pub const fn size(&self) -> u64 {
self.0.size()
}
pub const fn blocks(&self) -> u64 {
self.0.blocks()
}
}
impl fmt::Debug for Metadata {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Metadata")
.field("file_type", &self.file_type())
.field("is_dir", &self.is_dir())
.field("is_file", &self.is_file())
.field("permissions", &self.permissions())
.finish_non_exhaustive()
}
}
impl File {
pub fn open(path: &str) -> Result<Self> {
OpenOptions::new().read(true).open(path)
}
pub fn create(path: &str) -> Result<Self> {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(path)
}
pub fn create_new(path: &str) -> Result<Self> {
OpenOptions::new()
.read(true)
.write(true)
.create_new(true)
.open(path)
}
pub fn options() -> OpenOptions {
OpenOptions::new()
}
pub fn set_len(&self, size: u64) -> Result<()> {
self.inner.truncate(size)
}
pub fn metadata(&self) -> Result<Metadata> {
self.inner.get_attr().map(Metadata)
}
}
impl Read for File {
fn read(&mut self, buf: &mut [u8]) -> Result<usize> {
self.inner.read(buf)
}
}
impl Write for File {
fn write(&mut self, buf: &[u8]) -> Result<usize> {
self.inner.write(buf)
}
fn flush(&mut self) -> Result<()> {
self.inner.flush()
}
}
impl Seek for File {
fn seek(&mut self, pos: SeekFrom) -> Result<u64> {
self.inner.seek(pos)
}
}