use super::super::{Extensions, ExtensionsWriter};
use super::*;
use crate::evolution::encode_value_into;
#[test]
fn retry_charges_preparation_to_the_same_node_allowance() {
let budget = Budget::new(Limits {
bytes: 512,
allocation: 4096,
nodes: 1,
depth: 1,
});
let result = with_scratch(true, &budget, |scratch| {
if !budget.enter_scope(1) {
return Err(budget.error());
}
if scratch.len() == STACK_SCRATCH {
return Err(budget.refuse_with(LimitKind::Scratch));
}
Ok(())
});
assert_eq!(result, Err(Error::Limit(LimitKind::Nodes)));
}
use crate::LimitKind;
#[derive(Debug, PartialEq, Eq)]
struct Nested {
fixed: u8,
added: u8,
}
impl<'de> Inline<'de> for Nested {
type Encoded<'s> = (u8, Extensions<'s>);
type Decoded = (u8, Extensions<'de>);
fn prepare<'s>(
&'s self,
context: &WriteContext<'_>,
scratch: &'s mut [u8],
) -> Result<(Self::Encoded<'s>, &'s mut [u8]), Error> {
context.admit_preparation()?;
let mut block = ExtensionsWriter::new(scratch);
block.push(context, 2, &self.added)?;
let (block, tail) = block.finish_and_tail();
Ok(((self.fixed, block), tail))
}
fn project((fixed, block): Self::Decoded, context: &ReadContext<'_>) -> Result<Self, Error> {
let mut added = None;
block.visit(context, |id, value| {
if id == 2 {
added = Some(value.decode()?);
}
Ok(())
})?;
Ok(Self {
fixed,
added: added.ok_or(Error::Incompatible)?,
})
}
}
#[test]
fn staged_child_bytes_are_reused_by_following_extension() {
const LIMITS: Limits = Limits {
bytes: 32,
allocation: 2048,
nodes: 64,
depth: 8,
};
let child = Nested {
fixed: 42,
added: 17,
};
let mut output = Vec::new();
let mut scratch = [0; 10];
fn stage<'out>(
output: &'out mut Vec<u8>,
child: &Nested,
scratch: &mut [u8],
) -> Result<&'out [u8], Error> {
encode_value_into(output, Encoding::Payload, LIMITS, |context| {
let mut block = ExtensionsWriter::new(scratch);
block.push_projected(context, 1, child)?;
block.push(context, 5, &9_u8)?;
Ok(block.finish())
})
}
assert_eq!(
stage(&mut output, &child, &mut scratch),
Ok([10, 1, 5, 42, 3, 2, 1, 17, 5, 1, 9].as_slice()),
);
let actual = decode_value(
&output,
Encoding::Payload,
LIMITS,
|block: Extensions<'_>, context| {
let mut child = None;
let mut sibling = None;
block.visit(context, |id, field| {
match id {
1 => child = Some(field.project_inline::<Nested>()?),
5 => sibling = Some(field.decode::<u8>()?),
_ => (),
}
Ok(())
})?;
Ok((child, sibling))
},
);
assert_eq!(
actual,
Ok((
Some(Nested {
fixed: 42,
added: 17
}),
Some(9)
))
);
assert_eq!(
stage(&mut output, &child, &mut scratch[..9]),
Err(Error::Limit(LimitKind::Scratch)),
);
assert!(output.is_empty());
}
pub(super) fn encode_inline<'de, T: Inline<'de>>(
value: &T,
output: &mut Vec<u8>,
encoding: Encoding,
limits: Limits,
scratch: &mut [u8],
) -> Result<(), Error> {
encode_value_into(output, encoding, limits, |context| {
let (value, _) = value.prepare(context, scratch)?;
Ok(value)
})
.map(|_| ())
}