#![allow(clippy::unwrap_used)]
use std::io::{self, Cursor, Read, Seek, SeekFrom};
use crate::CodecError;
use super::u64_from_index;
use super::{
ByteRange, DecodeArena, DecodeContext, DecodeDepth, DecodePolicy, ExpandSpec,
ResourceDimension, ResourceLimits, WorkBudget,
};
fn policy_with(mut edit: impl FnMut(&mut ResourceLimits)) -> DecodePolicy {
let mut policy = DecodePolicy::default();
edit(&mut policy.limits);
policy
}
#[test]
fn allocation_failed_constructor_sets_refusal_fields() {
let limit =
super::ResourceLimit::allocation_failed(ResourceDimension::RetainedBytes, 12, 5, "test");
assert_eq!(limit.dimension, ResourceDimension::RetainedBytes);
assert_eq!(limit.reason, super::ResourceFailure::AllocationFailed);
assert_eq!(limit.limit, 12);
assert_eq!(limit.used, 0);
assert_eq!(limit.additional, 5);
assert_eq!(limit.operation, "test");
}
#[test]
fn root_limit_is_enforced() {
let bytes = [0_u8; 5];
let arena = DecodeArena::new();
let policy = policy_with(|limits| limits.max_input_bytes = 4);
assert!(matches!(
DecodeContext::from_root_bytes(&bytes, &arena, &policy),
Err(CodecError::ResourceLimit(limit))
if limit.dimension == ResourceDimension::InputBytes
));
}
#[test]
fn read_root_uses_sized_and_fallback_read_paths() {
let bytes = vec![0_u8; 32];
let policy = policy_with(|limits| limits.max_input_bytes = u64_from_index(bytes.len()));
let arena = DecodeArena::new();
let mut seekable = Cursor::new(bytes.clone());
let (_, root) =
DecodeContext::read_root(&mut seekable, &arena, &policy, DecodeDepth::Full).unwrap();
assert_eq!(root.window(), bytes.as_slice());
let arena = DecodeArena::new();
let mut fallback = Unseekable::new(bytes.clone());
let (_, root) =
DecodeContext::read_root(&mut fallback, &arena, &policy, DecodeDepth::Full).unwrap();
assert_eq!(root.window(), bytes.as_slice());
}
struct Unseekable {
input: Cursor<Vec<u8>>,
}
impl Unseekable {
fn new(bytes: Vec<u8>) -> Self {
Self {
input: Cursor::new(bytes),
}
}
}
impl Read for Unseekable {
fn read(&mut self, bytes: &mut [u8]) -> io::Result<usize> {
self.input.read(bytes)
}
}
impl Seek for Unseekable {
fn seek(&mut self, _: SeekFrom) -> io::Result<u64> {
Err(io::Error::other("seek unavailable"))
}
}
#[test]
fn views_bound_reads_and_children() {
let bytes = [0, 1, 2, 3, 4];
let arena = DecodeArena::new();
let (_, root) =
DecodeContext::from_root_bytes(&bytes, &arena, &DecodePolicy::default()).unwrap();
let mut child = root.child(1, 4).unwrap();
assert_eq!(child.take(3), Some(&bytes[1..4]));
assert!(child.take(1).is_none());
assert!(root.child(3, 6).is_none());
}
#[test]
fn counted_requires_a_physically_possible_count() {
let bytes = [0_u8; 8];
let arena = DecodeArena::new();
let (_, root) =
DecodeContext::from_root_bytes(&bytes, &arena, &DecodePolicy::default()).unwrap();
assert!(root.counted(3, 4).is_none());
assert_eq!(root.counted(2, 4).unwrap().get(), 2);
}
#[test]
fn exact_expansion_enforces_size_and_limit() {
let bytes = [0_u8; 4];
let arena = DecodeArena::new();
let policy = policy_with(|limits| {
limits.max_decompressed_bytes_total = 8;
limits.max_decompressed_bytes_per_expand = 8;
});
let (ctx, _) = DecodeContext::from_root_bytes(&bytes, &arena, &policy).unwrap();
let mut writer = ctx.begin_expand(ExpandSpec::Exact(4)).unwrap();
writer.write(&[1, 2, 3, 4]).unwrap();
let view = writer.finalize().unwrap();
assert_eq!(view.window(), &[1, 2, 3, 4]);
let mut writer = ctx.begin_expand(ExpandSpec::Unknown).unwrap();
assert!(matches!(
writer.write(&[0; 9]),
Err(CodecError::ResourceLimit(_))
));
}
#[test]
fn concatenation_and_stored_slices_have_distinct_spaces() {
let bytes = [0, 1, 2, 3, 4, 5];
let arena = DecodeArena::new();
let (ctx, root) =
DecodeContext::from_root_bytes(&bytes, &arena, &DecodePolicy::default()).unwrap();
let first = root.child(0, 2).unwrap();
let second = root.child(4, 6).unwrap();
assert!(matches!(
ctx.concat_views(&[]),
Err(CodecError::Malformed(_))
));
let concat = ctx.concat_views(&[first, second]).unwrap();
assert_eq!(concat.window(), &[0, 1, 4, 5]);
let slice = ctx
.register_slice(root, ByteRange { start: 1, end: 3 })
.unwrap();
assert_eq!(slice.window(), &[1, 2]);
assert_ne!(concat.space(), slice.space());
}
#[test]
fn every_session_dimension_refuses_and_fuses() {
fn assert_dimension(
edit: impl FnMut(&mut ResourceLimits),
charge: impl FnOnce(&DecodeContext<'_>) -> Result<(), CodecError>,
expected: ResourceDimension,
) {
let arena = DecodeArena::new();
let policy = policy_with(edit);
let (ctx, _) = DecodeContext::from_root_bytes(&[0], &arena, &policy).unwrap();
assert!(
matches!(charge(&ctx), Err(CodecError::ResourceLimit(limit)) if limit.dimension == expected)
);
assert!(matches!(
ctx.charge_entities(0, "after_fuse"),
Err(CodecError::ResourceLimit(_))
));
}
assert_dimension(
|limits| limits.max_retained_bytes = 1,
|ctx| ctx.retain_bytes(2, "retain"),
ResourceDimension::RetainedBytes,
);
assert_dimension(
|limits| limits.max_entities = 1,
|ctx| ctx.charge_entities(2, "entities"),
ResourceDimension::Entities,
);
assert_dimension(
|limits| limits.max_entities = 1,
|ctx| {
let mut admitted = 0;
ctx.admit_entities(1, &mut admitted, "admit")?;
ctx.admit_entities(2, &mut admitted, "admit")
},
ResourceDimension::Entities,
);
assert_dimension(
|limits| limits.max_recursion_depth = 0,
|ctx| ctx.enter_nested("nested").map(drop),
ResourceDimension::RecursionDepth,
);
}
#[test]
fn committed_reads_preserve_truncation_location_and_operation() {
let arena = DecodeArena::new();
let (_, mut root) =
DecodeContext::from_root_bytes(&[1, 2], &arena, &DecodePolicy::default()).unwrap();
let error: CodecError = root
.req_u32_le()
.unwrap_err()
.during("read header size")
.into();
assert!(matches!(
error,
CodecError::Truncated {
location,
operation
}
if location == root.location_at(0)
&& operation == "read header size"
));
}
#[test]
fn forced_child_exhaustion_charges_its_full_slice() {
let parent = WorkBudget::new(10);
let child = parent.child_slice(4);
assert!(child.charge());
child.exhaust();
assert!(matches!(parent.consume_child(&child), Ok(())));
assert_eq!(parent.remaining(), 6);
assert!(!child.charge_by(0));
}
#[test]
fn stored_expanded_and_concatenated_spaces_have_distinct_zero_based_locations() {
let arena = DecodeArena::new();
let policy = DecodePolicy::default();
let (ctx, root) = DecodeContext::from_root_bytes(b"abcd", &arena, &policy).unwrap();
let stored = ctx
.register_slice(root, ByteRange { start: 0, end: 4 })
.unwrap();
let expanded = ctx
.begin_expand(ExpandSpec::Exact(0))
.unwrap()
.finalize()
.unwrap();
let concat = ctx.concat_views(&[root, stored]).unwrap();
for (index, view) in [root, stored, expanded, concat].into_iter().enumerate() {
assert_eq!(view.space().index(), index);
assert_eq!(view.location().offset, 0);
}
}