use std::fs::{self, File};
use std::io::{self, Read as _, Write as _};
use std::path::{Path, PathBuf};
#[cfg(test)]
mod tests;
pub(crate) fn read_capped(path: &Path, limit: usize) -> io::Result<Vec<u8>> {
let limit = u64::try_from(limit).unwrap_or(u64::MAX);
let mut bytes = Vec::new();
File::open(path)?.take(limit).read_to_end(&mut bytes)?;
Ok(bytes)
}
pub(crate) fn rust_files(dir: &Path) -> io::Result<Vec<PathBuf>> {
let mut found = Vec::new();
let mut dirs = vec![dir.to_path_buf()];
while let Some(dir) = dirs.pop() {
for entry in fs::read_dir(&dir)? {
let entry = entry?;
let kind = entry.file_type()?;
let path = entry.path();
if kind.is_dir() {
dirs.push(path);
} else if kind.is_file() && path.extension().is_some_and(|ext| ext == "rs") {
found.push(path);
}
}
}
found.sort();
Ok(found)
}
pub(crate) fn write_new(path: &Path, text: &str) -> io::Result<()> {
let mut file = File::options().write(true).create_new(true).open(path)?;
file.write_all(text.as_bytes()).inspect_err(|_| {
drop(file);
let _ = fs::remove_file(path);
})
}
pub(crate) fn exists(path: &Path) -> bool {
path.exists()
}
pub(crate) fn canonical(path: &Path) -> io::Result<PathBuf> {
fs::canonicalize(path)
}