Skip to content

Commit

Permalink
feat: add file read and write function(but with directly statx) (#193)
Browse files Browse the repository at this point in the history
  • Loading branch information
ihciah committed Jul 12, 2023
1 parent 8b95e3f commit 4e1cb8e
Showing 1 changed file with 32 additions and 0 deletions.
32 changes: 32 additions & 0 deletions monoio/src/fs/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,39 @@
//! Filesystem manipulation operations.

mod file;
use std::{io, path::Path};

pub use file::File;

mod open_options;
pub use open_options::OpenOptions;

use crate::buf::IoBuf;

/// Read the entire contents of a file into a bytes vector.
#[cfg(unix)]
pub async fn read<P: AsRef<Path>>(path: P) -> io::Result<Vec<u8>> {
use std::os::fd::{AsRawFd, FromRawFd, IntoRawFd};

use crate::buf::IoBufMut;

let file = File::open(path).await?;
let sys_file = unsafe { std::fs::File::from_raw_fd(file.as_raw_fd()) };
let size = sys_file.metadata()?.len() as usize;
let _ = sys_file.into_raw_fd();

let (res, buf) = file
.read_exact_at(Vec::with_capacity(size).slice_mut(0..size), 0)
.await;
res?;
Ok(buf.into_inner())
}

/// Write a buffer as the entire contents of a file.
pub async fn write<P: AsRef<Path>, C: IoBuf>(path: P, contents: C) -> (io::Result<()>, C) {
let file = match File::create(path).await {
Ok(f) => f,
Err(e) => return (Err(e), contents),
};
file.write_all_at(contents, 0).await
}

0 comments on commit 4e1cb8e

Please sign in to comment.