feat: lay the ground for login
This commit is contained in:
54
src/utils.rs
54
src/utils.rs
@@ -83,3 +83,57 @@ pub mod shasum {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub mod fs {
|
||||
use std::{io, os::unix::fs::MetadataExt as _, path::Path};
|
||||
|
||||
use tokio::{fs::File, io::AsyncReadExt};
|
||||
|
||||
/// # Errors
|
||||
///
|
||||
/// On any underlaying file i/o error.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If a file's [`u64`] doesn't fit in memory.
|
||||
pub async fn read_limited_path<const MAXSIZE: u64>(path: &Path) -> io::Result<Vec<u8>> {
|
||||
let f = File::open(path).await?;
|
||||
let size = f.metadata().await?.size();
|
||||
|
||||
if size > MAXSIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::FileTooLarge,
|
||||
"filesize is bigger than MAXSIZE",
|
||||
));
|
||||
}
|
||||
let mut buf = Vec::with_capacity(size.try_into().expect("u64 to fit in usize"));
|
||||
// `.take()` just in case an open fd happens to grow, `.metadata()` SHOULD take
|
||||
// properties from the fd and lock the read fd until its closed but still
|
||||
f.take(MAXSIZE).read_to_end(&mut buf).await?;
|
||||
Ok(buf)
|
||||
}
|
||||
|
||||
/// # Errors
|
||||
///
|
||||
/// On any underlaying file i/o error.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// If a file's [`u64`] doesn't fit in memory.
|
||||
pub async fn read_limited_path_str<const MAXSIZE: u64>(path: &Path) -> io::Result<String> {
|
||||
let f = File::open(path).await?;
|
||||
let size = f.metadata().await?.size();
|
||||
|
||||
if size > MAXSIZE {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::FileTooLarge,
|
||||
"filesize is bigger than MAXSIZE",
|
||||
));
|
||||
}
|
||||
let mut buf = String::with_capacity(size.try_into().expect("u64 to fit in usize"));
|
||||
// `.take()` just in case an open fd happens to grow, `.metadata()` SHOULD take
|
||||
// properties from the fd and lock the read fd until its closed but still
|
||||
f.take(MAXSIZE).read_to_string(&mut buf).await?;
|
||||
Ok(buf)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user