use std::{
fs,
io::{Read, Seek, SeekFrom},
};
use crate::errors::{
BlockingToolError, DomainError, ERROR_FILE_TOO_LARGE, ERROR_NOT_FILE, ERROR_NOT_UTF8,
ERROR_READ_FAILED,
};
pub(crate) fn read_bounded(
file: &mut fs::File,
max_bytes: usize,
is_cancelled: &dyn Fn() -> bool,
) -> Result<Vec<u8>, BlockingToolError> {
if is_cancelled() {
return Err(BlockingToolError::Cancelled);
}
let metadata = file.metadata().map_err(|_| {
DomainError::new(
ERROR_READ_FAILED,
"could not inspect workspace file metadata",
)
})?;
if !metadata.is_file() {
return Err(
DomainError::new(ERROR_NOT_FILE, "workspace path is not a regular file").into(),
);
}
let size = usize::try_from(metadata.len()).map_err(|_| {
DomainError::new(
ERROR_FILE_TOO_LARGE,
"workspace file exceeds the configured read limit",
)
})?;
if size > max_bytes {
return Err(DomainError::new(
ERROR_FILE_TOO_LARGE,
"workspace file exceeds the configured read limit",
)
.into());
}
if file.seek(SeekFrom::Start(0)).is_err() {
return Err(DomainError::new(ERROR_READ_FAILED, "could not seek workspace file").into());
}
if is_cancelled() {
return Err(BlockingToolError::Cancelled);
}
let mut bytes = Vec::with_capacity(size);
Read::by_ref(file)
.take(metadata.len())
.read_to_end(&mut bytes)
.map_err(|_| DomainError::new(ERROR_READ_FAILED, "could not read workspace file"))?;
Ok(bytes)
}
pub(crate) fn decode_utf8(bytes: Vec<u8>) -> Result<String, DomainError> {
String::from_utf8(bytes)
.map_err(|_| DomainError::new(ERROR_NOT_UTF8, "workspace file is not valid UTF-8"))
}