diff options
| author | ihc童鞋@提不起劲 <[email protected]> | 2023-07-12 17:51:50 +0800 |
|---|---|---|
| committer | GitHub <[email protected]> | 2023-07-12 17:51:50 +0800 |
| commit | 4e1cb8e846f56c2a993ce5f16481efb43a376a7c (patch) | |
| tree | b5896d2efaedf2c486c742c5b31e5b1f697fef39 | |
| parent | 8b95e3f1ec825028e2791f96d85bf694187e41da (diff) | |
feat: add file read and write function(but with directly statx) (#193)
| -rw-r--r-- | monoio/src/fs/mod.rs | 32 |
1 files changed, 32 insertions, 0 deletions
diff --git a/monoio/src/fs/mod.rs b/monoio/src/fs/mod.rs index ba38fc9..e4ec774 100644 --- a/monoio/src/fs/mod.rs +++ b/monoio/src/fs/mod.rs @@ -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 +} |
