use crate::error::{Failure, Result};
use std::io::Read;
use std::path::Path;
pub fn file_within(path: &Path, ceiling: usize) -> Result<String> {
let unreadable = |cause: std::io::Error| {
Failure::absence(
"absence.file",
format!("`{}` could not be read", path.display()),
)
.with_detail("detail", path.display().to_string())
.with_cause(cause.to_string())
};
let size = std::fs::metadata(path).map_err(unreadable)?.len();
if size > ceiling as u64 {
return Err(too_much(size, ceiling));
}
std::fs::read_to_string(path).map_err(unreadable)
}
pub fn standard_input_within(ceiling: usize) -> Result<String> {
let mut text = String::new();
let read = std::io::stdin()
.lock()
.take(ceiling as u64 + 1)
.read_to_string(&mut text)
.map_err(|cause| {
Failure::config(
"config.stdin_unreadable",
"the standard input could not be read",
)
.with_cause(cause.to_string())
})?;
if read > ceiling {
return Err(too_much(read as u64, ceiling));
}
Ok(text)
}
fn too_much(size: u64, ceiling: usize) -> Failure {
Failure::limit(
"limit.input_bytes",
format!("the input has {size} bytes and the reading ceiling is {ceiling}"),
)
.with_detail("detail", format!("{size} > {ceiling}"))
.with_hint("read less, or raise limits.max_input_bytes")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_file_within_the_ceiling_is_read_whole() {
let file = tempfile::NamedTempFile::new().expect("a temporary file");
std::fs::write(file.path(), "select 1").expect("writes");
let text = file_within(file.path(), 1024).expect("reads");
assert_eq!(text, "select 1");
}
#[test]
fn a_file_past_the_ceiling_is_refused_without_being_read() {
let file = tempfile::NamedTempFile::new().expect("a temporary file");
std::fs::write(file.path(), "select 1").expect("writes");
let failure = file_within(file.path(), 3).expect_err("refuses");
assert_eq!(failure.code(), "limit.input_bytes");
}
#[test]
fn a_file_exactly_at_the_ceiling_is_still_read() {
let file = tempfile::NamedTempFile::new().expect("a temporary file");
std::fs::write(file.path(), "select 1").expect("writes");
let text = file_within(file.path(), 8).expect("reads");
assert_eq!(text, "select 1");
}
#[test]
fn the_refusal_names_the_key_that_raises_the_ceiling() {
let failure = too_much(9, 8);
assert_eq!(failure.code(), "limit.input_bytes");
assert!(failure
.hint()
.is_some_and(|hint| hint.contains("limits.max_input_bytes")));
}
}