use crate::{
diag::{DiagKind, DiagSink, Diagnostic},
engine::Engine,
wire::{self, Varint, Varint64},
};
pub struct Ctx<'d> {
pub engine: Engine,
diag: &'d mut dyn DiagSink,
entries: EntryBudget<'d>,
}
pub(crate) const ENTRY_BUDGET: u64 = 1 << 20;
enum EntryBudget<'d> {
Root(u64),
Nested(&'d mut u64),
}
impl EntryBudget<'_> {
fn left(&mut self) -> &mut u64 {
match self {
Self::Root(left) => left,
Self::Nested(left) => left,
}
}
}
impl<'d> Ctx<'d> {
pub fn new(engine: Engine, diag: &'d mut dyn DiagSink) -> Self {
Self {
engine,
diag,
entries: EntryBudget::Root(ENTRY_BUDGET),
}
}
#[cfg(feature = "alloc")]
#[inline]
pub(crate) fn take_entries(&mut self, count: u64) -> bool {
let left = self.entries.left();
if count > *left {
return false;
}
*left -= count;
true
}
#[inline]
pub fn reborrow(&mut self) -> Ctx<'_> {
Ctx {
engine: self.engine,
diag: &mut *self.diag,
entries: EntryBudget::Nested(self.entries.left()),
}
}
#[inline]
pub fn report(&mut self, struct_name: &'static str, chunk_id: u32, offset: u32, kind: DiagKind) {
self.diag.push(Diagnostic {
offset,
chunk_id,
struct_name,
kind,
});
}
#[must_use]
#[inline]
pub fn should_abort(&self) -> bool {
self.diag.should_abort()
}
#[must_use]
#[inline]
pub fn latched(&self) -> Option<Diagnostic> {
self.diag.first()
}
}
impl core::fmt::Debug for Ctx<'_> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_struct("Ctx")
.field("engine", &self.engine)
.finish_non_exhaustive()
}
}
#[derive(Clone, Debug)]
pub struct Cursor<'a> {
buf: &'a [u8],
pos: usize,
base: u32,
}
impl<'a> Cursor<'a> {
#[must_use]
#[inline]
pub const fn new(buf: &'a [u8]) -> Self {
Self { buf, pos: 0, base: 0 }
}
#[must_use]
#[inline]
pub const fn with_base(buf: &'a [u8], base: u32) -> Self {
Self { buf, pos: 0, base }
}
#[must_use]
#[inline]
pub const fn pos(&self) -> usize {
self.pos
}
#[must_use]
#[inline]
pub const fn offset(&self) -> u32 {
self.base.wrapping_add(self.pos as u32)
}
#[must_use]
#[inline]
pub const fn buf(&self) -> &'a [u8] {
self.buf
}
#[must_use]
#[inline]
pub fn remaining(&self) -> &'a [u8] {
self.buf.get(self.pos..).unwrap_or(&[])
}
#[must_use]
#[inline]
pub const fn remaining_len(&self) -> usize {
self.buf.len() - self.pos
}
#[must_use]
#[inline]
pub const fn is_empty(&self) -> bool {
self.pos >= self.buf.len()
}
#[must_use]
#[inline]
pub fn take(&mut self, n: usize) -> Option<&'a [u8]> {
let end = self.pos.checked_add(n)?;
let out = self.buf.get(self.pos..end)?;
self.pos = end;
Some(out)
}
#[must_use]
#[inline]
pub fn take_rest(&mut self) -> &'a [u8] {
let out = self.remaining();
self.pos = self.buf.len();
out
}
#[inline]
pub fn skip(&mut self, n: usize) {
self.pos = self.pos.saturating_add(n).min(self.buf.len());
}
#[must_use]
#[inline]
pub fn varint(&mut self) -> Option<Varint> {
let v = wire::decode_varint(self.remaining())?;
self.pos += v.consumed;
Some(v)
}
#[inline]
pub fn varint_lenient(&mut self, ctx: &mut Ctx<'_>, struct_name: &'static str, chunk_id: u32) -> i32 {
let offset = self.offset();
match self.varint() {
Some(v) => {
if v.overflow {
ctx.report(struct_name, chunk_id, offset, DiagKind::BadVarint);
}
v.value as i32
}
None => {
self.pos = self.buf.len();
ctx.report(struct_name, chunk_id, offset, DiagKind::ShortChunk);
0
}
}
}
#[must_use]
#[inline]
pub fn varint64(&mut self) -> Option<Varint64> {
let v = wire::decode_varint64(self.remaining())?;
self.pos += v.consumed;
Some(v)
}
#[must_use]
#[inline]
pub fn u8(&mut self) -> Option<u8> {
self.take(1).map(|b| b[0])
}
#[must_use]
#[inline]
pub fn i16_le(&mut self) -> Option<i16> {
self.take(2).map(|b| i16::from_le_bytes([b[0], b[1]]))
}
#[must_use]
#[inline]
pub fn u32_le(&mut self) -> Option<u32> {
self.take(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
#[must_use]
#[inline]
pub fn i32_le(&mut self) -> Option<i32> {
self.take(4).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
}
#[must_use]
#[inline]
pub fn f64_le(&mut self) -> Option<f64> {
self.take(8)
.map(|b| f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
}
#[must_use]
#[inline]
pub fn peek(&self) -> Option<u8> {
self.buf.get(self.pos).copied()
}
#[must_use]
#[inline]
pub fn lstring(&mut self) -> Option<&'a [u8]> {
let len = self.varint()?;
self.take(len.value as usize)
}
}
#[derive(Clone, Copy, Debug)]
pub struct Chunk<'a> {
pub id: u32,
pub data: &'a [u8],
pub offset: u32,
}
impl<'a> Chunk<'a> {
#[must_use]
#[inline]
pub const fn cursor(&self) -> Cursor<'a> {
Cursor::with_base(self.data, self.offset)
}
}
#[derive(Clone, Debug)]
pub struct ChunkIter<'a> {
cur: Cursor<'a>,
done: bool,
}
impl<'a> ChunkIter<'a> {
#[must_use]
#[inline]
pub const fn new(buf: &'a [u8], base: u32) -> Self {
Self {
cur: Cursor::with_base(buf, base),
done: false,
}
}
#[must_use]
#[inline]
pub const fn from_cursor(cur: Cursor<'a>) -> Self {
Self { cur, done: false }
}
#[must_use]
#[inline]
pub const fn cursor(&self) -> &Cursor<'a> {
&self.cur
}
#[must_use]
#[inline]
pub const fn into_cursor(self) -> Cursor<'a> {
self.cur
}
#[must_use]
#[inline]
pub fn tail(&self) -> &'a [u8] {
self.cur.remaining()
}
#[must_use]
pub fn consume(cur: &mut Cursor<'a>, ctx: &mut Ctx<'_>, struct_name: &'static str) -> &'a [u8] {
let start = cur.pos();
let mut chunks = Self::from_cursor(cur.clone());
while chunks.next(ctx, struct_name).is_some() {}
*cur = chunks.into_cursor();
cur.buf().get(start..cur.pos()).unwrap_or(&[])
}
#[must_use]
pub fn find(body: &'a [u8], base: u32, id: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
let mut chunks = Self::new(body, base);
while let Some(chunk) = chunks.next(ctx, struct_name) {
if chunk.id == id {
return Some(chunk);
}
}
None
}
#[must_use]
pub fn next(&mut self, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
if self.done || self.cur.is_empty() {
return None;
}
let id_offset = self.cur.offset();
let id = match self.cur.varint() {
Some(v) if v.overflow => {
ctx.report(struct_name, 0, id_offset, DiagKind::BadVarint);
self.done = true;
return None;
}
Some(v) => v.value,
None => {
self.done = true;
return None;
}
};
if id == 0 {
self.done = true;
return None;
}
let len_offset = self.cur.offset();
let len = match self.cur.varint() {
Some(v) if v.overflow => {
ctx.report(struct_name, id, len_offset, DiagKind::BadVarint);
self.done = true;
return None;
}
Some(v) => v.value as usize,
None => {
ctx.report(struct_name, id, len_offset, DiagKind::ShortChunk);
self.done = true;
return None;
}
};
let offset = self.cur.offset();
let data = match self.cur.take(len) {
Some(data) => data,
None => {
ctx.report(struct_name, id, offset, DiagKind::ChunkOverrun);
self.done = true;
self.cur.take_rest()
}
};
Some(Chunk { id, data, offset })
}
}
#[derive(Clone, Copy, Debug)]
pub struct ListItem<'a> {
pub id: i32,
pub body: &'a [u8],
pub offset: u32,
}
impl<'a> ListItem<'a> {
#[must_use]
#[inline]
pub const fn chunks(&self) -> ChunkIter<'a> {
ChunkIter::new(self.body, self.offset)
}
#[must_use]
#[inline]
pub fn find(&self, id: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
ChunkIter::find(self.body, self.offset, id, ctx, struct_name)
}
}
#[derive(Clone, Debug)]
pub struct ListWalker<'a> {
cur: Cursor<'a>,
left: u32,
name: &'static str,
}
impl<'a> ListWalker<'a> {
#[must_use]
pub fn new(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Self {
let mut cur = Cursor::with_base(body, base);
let count = cur.varint_lenient(ctx, struct_name, 0);
let left = (count.max(0) as usize).min(cur.remaining_len() / 2 + 1) as u32;
Self {
cur,
left,
name: struct_name,
}
}
#[must_use]
#[inline]
pub const fn remaining(&self) -> u32 {
self.left
}
#[must_use]
pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<ListItem<'a>> {
if self.left == 0 || self.cur.is_empty() {
return None;
}
self.left -= 1;
let id = self.cur.varint_lenient(ctx, self.name, 0);
let offset = self.cur.offset();
let body = ChunkIter::consume(&mut self.cur, ctx, self.name);
Some(ListItem { id, body, offset })
}
}