#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BoundedBody {
pub bytes: Vec<u8>,
pub truncated: bool,
pub full_len: u64,
}
impl BoundedBody {
#[must_use]
pub fn capture(full: &[u8], max_bytes: usize) -> Self {
let full_len = full.len() as u64;
if max_bytes == 0 || full.len() <= max_bytes {
return Self {
bytes: full.to_vec(),
truncated: false,
full_len,
};
}
Self {
bytes: full[..max_bytes].to_vec(),
truncated: true,
full_len,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn body_under_bound_is_not_truncated() {
let full = b"hello";
let result = BoundedBody::capture(full, 10);
assert!(!result.truncated);
assert_eq!(result.bytes, full.to_vec());
assert_eq!(result.full_len, full.len() as u64);
}
#[test]
fn body_over_bound_is_truncated_to_prefix() {
let full = b"hello world";
let max_bytes = 5;
let result = BoundedBody::capture(full, max_bytes);
assert!(result.truncated);
assert_eq!(result.bytes.len(), max_bytes);
assert_eq!(result.bytes, full[..max_bytes].to_vec());
assert_eq!(result.full_len, full.len() as u64);
}
#[test]
fn body_exactly_at_bound_is_not_truncated() {
let full = b"hello";
let result = BoundedBody::capture(full, full.len());
assert!(!result.truncated);
assert_eq!(result.bytes, full.to_vec());
assert_eq!(result.full_len, full.len() as u64);
}
#[test]
fn max_bytes_zero_is_unbounded() {
let full = vec![0xAB; 10_000];
let result = BoundedBody::capture(&full, 0);
assert!(!result.truncated);
assert_eq!(result.bytes, full);
assert_eq!(result.full_len, full.len() as u64);
}
#[test]
fn bounding_uses_raw_length_not_base64_encoded_length() {
use base64::Engine as _;
use base64::engine::general_purpose::STANDARD as BASE64;
let full = vec![0x42; 40];
let encoded = BASE64.encode(&full);
let max_bytes = 40;
assert!(
encoded.len() > max_bytes,
"test setup: base64 form ({}) must exceed max_bytes ({max_bytes}) \
to exercise the raw-vs-encoded distinction",
encoded.len()
);
let result = BoundedBody::capture(&full, max_bytes);
assert!(
!result.truncated,
"raw body fits under max_bytes; must not be truncated even though \
its base64 encoding would have exceeded max_bytes"
);
assert_eq!(result.bytes, full);
assert_eq!(result.full_len, full.len() as u64);
}
#[test]
fn empty_body_is_not_truncated() {
let result = BoundedBody::capture(b"", 10);
assert!(!result.truncated);
assert!(result.bytes.is_empty());
assert_eq!(result.full_len, 0);
}
}