1use crate::{
12 diag::{DiagKind, DiagSink, Diagnostic},
13 engine::Engine,
14 wire::{self, Varint, Varint64},
15};
16
17pub struct Ctx<'d> {
27 pub engine: Engine,
28 diag: &'d mut dyn DiagSink,
29 entries: EntryBudget<'d>,
30}
31
32pub(crate) const ENTRY_BUDGET: u64 = 1 << 20;
36
37enum EntryBudget<'d> {
40 Root(u64),
41 Nested(&'d mut u64),
42}
43
44impl EntryBudget<'_> {
45 fn left(&mut self) -> &mut u64 {
46 match self {
47 Self::Root(left) => left,
48 Self::Nested(left) => left,
49 }
50 }
51}
52
53impl<'d> Ctx<'d> {
54 pub fn new(engine: Engine, diag: &'d mut dyn DiagSink) -> Self {
55 Self {
56 engine,
57 diag,
58 entries: EntryBudget::Root(ENTRY_BUDGET),
59 }
60 }
61
62 #[cfg(feature = "alloc")]
65 #[inline]
66 pub(crate) fn take_entries(&mut self, count: u64) -> bool {
67 let left = self.entries.left();
68 if count > *left {
69 return false;
70 }
71 *left -= count;
72 true
73 }
74
75 #[inline]
81 pub fn reborrow(&mut self) -> Ctx<'_> {
82 Ctx {
83 engine: self.engine,
84 diag: &mut *self.diag,
85 entries: EntryBudget::Nested(self.entries.left()),
86 }
87 }
88
89 #[inline]
91 pub fn report(&mut self, struct_name: &'static str, chunk_id: u32, offset: u32, kind: DiagKind) {
92 self.diag.push(Diagnostic {
93 offset,
94 chunk_id,
95 struct_name,
96 kind,
97 });
98 }
99
100 #[must_use]
102 #[inline]
103 pub fn should_abort(&self) -> bool {
104 self.diag.should_abort()
105 }
106
107 #[must_use]
109 #[inline]
110 pub fn latched(&self) -> Option<Diagnostic> {
111 self.diag.first()
112 }
113}
114
115impl core::fmt::Debug for Ctx<'_> {
116 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
117 f.debug_struct("Ctx")
118 .field("engine", &self.engine)
119 .finish_non_exhaustive()
120 }
121}
122
123#[derive(Clone, Debug)]
128pub struct Cursor<'a> {
129 buf: &'a [u8],
130 pos: usize,
131 base: u32,
132}
133
134impl<'a> Cursor<'a> {
135 #[must_use]
137 #[inline]
138 pub const fn new(buf: &'a [u8]) -> Self {
139 Self { buf, pos: 0, base: 0 }
140 }
141
142 #[must_use]
144 #[inline]
145 pub const fn with_base(buf: &'a [u8], base: u32) -> Self {
146 Self { buf, pos: 0, base }
147 }
148
149 #[must_use]
151 #[inline]
152 pub const fn pos(&self) -> usize {
153 self.pos
154 }
155
156 #[must_use]
158 #[inline]
159 pub const fn offset(&self) -> u32 {
160 self.base.wrapping_add(self.pos as u32)
161 }
162
163 #[must_use]
168 #[inline]
169 pub const fn buf(&self) -> &'a [u8] {
170 self.buf
171 }
172
173 #[must_use]
175 #[inline]
176 pub fn remaining(&self) -> &'a [u8] {
177 self.buf.get(self.pos..).unwrap_or(&[])
179 }
180
181 #[must_use]
183 #[inline]
184 pub const fn remaining_len(&self) -> usize {
185 self.buf.len() - self.pos
186 }
187
188 #[must_use]
190 #[inline]
191 pub const fn is_empty(&self) -> bool {
192 self.pos >= self.buf.len()
193 }
194
195 #[must_use]
197 #[inline]
198 pub fn take(&mut self, n: usize) -> Option<&'a [u8]> {
199 let end = self.pos.checked_add(n)?;
200 let out = self.buf.get(self.pos..end)?;
201 self.pos = end;
202 Some(out)
203 }
204
205 #[must_use]
207 #[inline]
208 pub fn take_rest(&mut self) -> &'a [u8] {
209 let out = self.remaining();
210 self.pos = self.buf.len();
211 out
212 }
213
214 #[inline]
216 pub fn skip(&mut self, n: usize) {
217 self.pos = self.pos.saturating_add(n).min(self.buf.len());
218 }
219
220 #[must_use]
225 #[inline]
226 pub fn varint(&mut self) -> Option<Varint> {
227 let v = wire::decode_varint(self.remaining())?;
228 self.pos += v.consumed;
229 Some(v)
230 }
231
232 #[inline]
237 pub fn varint_lenient(&mut self, ctx: &mut Ctx<'_>, struct_name: &'static str, chunk_id: u32) -> i32 {
238 let offset = self.offset();
239 match self.varint() {
240 Some(v) => {
241 if v.overflow {
242 ctx.report(struct_name, chunk_id, offset, DiagKind::BadVarint);
243 }
244 v.value as i32
245 }
246 None => {
247 self.pos = self.buf.len();
248 ctx.report(struct_name, chunk_id, offset, DiagKind::ShortChunk);
249 0
250 }
251 }
252 }
253
254 #[must_use]
256 #[inline]
257 pub fn varint64(&mut self) -> Option<Varint64> {
258 let v = wire::decode_varint64(self.remaining())?;
259 self.pos += v.consumed;
260 Some(v)
261 }
262
263 #[must_use]
265 #[inline]
266 pub fn u8(&mut self) -> Option<u8> {
267 self.take(1).map(|b| b[0])
268 }
269
270 #[must_use]
272 #[inline]
273 pub fn i16_le(&mut self) -> Option<i16> {
274 self.take(2).map(|b| i16::from_le_bytes([b[0], b[1]]))
275 }
276
277 #[must_use]
279 #[inline]
280 pub fn u32_le(&mut self) -> Option<u32> {
281 self.take(4).map(|b| u32::from_le_bytes([b[0], b[1], b[2], b[3]]))
282 }
283
284 #[must_use]
286 #[inline]
287 pub fn i32_le(&mut self) -> Option<i32> {
288 self.take(4).map(|b| i32::from_le_bytes([b[0], b[1], b[2], b[3]]))
289 }
290
291 #[must_use]
293 #[inline]
294 pub fn f64_le(&mut self) -> Option<f64> {
295 self.take(8)
296 .map(|b| f64::from_le_bytes([b[0], b[1], b[2], b[3], b[4], b[5], b[6], b[7]]))
297 }
298
299 #[must_use]
301 #[inline]
302 pub fn peek(&self) -> Option<u8> {
303 self.buf.get(self.pos).copied()
304 }
305
306 #[must_use]
312 #[inline]
313 pub fn lstring(&mut self) -> Option<&'a [u8]> {
314 let len = self.varint()?;
315 self.take(len.value as usize)
316 }
317}
318
319#[derive(Clone, Copy, Debug)]
321pub struct Chunk<'a> {
322 pub id: u32,
323 pub data: &'a [u8],
324 pub offset: u32,
325}
326
327impl<'a> Chunk<'a> {
328 #[must_use]
330 #[inline]
331 pub const fn cursor(&self) -> Cursor<'a> {
332 Cursor::with_base(self.data, self.offset)
333 }
334}
335
336#[derive(Clone, Debug)]
340pub struct ChunkIter<'a> {
341 cur: Cursor<'a>,
342 done: bool,
343}
344
345impl<'a> ChunkIter<'a> {
346 #[must_use]
348 #[inline]
349 pub const fn new(buf: &'a [u8], base: u32) -> Self {
350 Self {
351 cur: Cursor::with_base(buf, base),
352 done: false,
353 }
354 }
355
356 #[must_use]
358 #[inline]
359 pub const fn from_cursor(cur: Cursor<'a>) -> Self {
360 Self { cur, done: false }
361 }
362
363 #[must_use]
365 #[inline]
366 pub const fn cursor(&self) -> &Cursor<'a> {
367 &self.cur
368 }
369
370 #[must_use]
376 #[inline]
377 pub const fn into_cursor(self) -> Cursor<'a> {
378 self.cur
379 }
380
381 #[must_use]
383 #[inline]
384 pub fn tail(&self) -> &'a [u8] {
385 self.cur.remaining()
386 }
387
388 #[must_use]
394 pub fn consume(cur: &mut Cursor<'a>, ctx: &mut Ctx<'_>, struct_name: &'static str) -> &'a [u8] {
395 let start = cur.pos();
396 let mut chunks = Self::from_cursor(cur.clone());
397 while chunks.next(ctx, struct_name).is_some() {}
398 *cur = chunks.into_cursor();
399 cur.buf().get(start..cur.pos()).unwrap_or(&[])
400 }
401
402 #[must_use]
408 pub fn find(body: &'a [u8], base: u32, id: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
409 let mut chunks = Self::new(body, base);
410 while let Some(chunk) = chunks.next(ctx, struct_name) {
411 if chunk.id == id {
412 return Some(chunk);
413 }
414 }
415 None
416 }
417
418 #[must_use]
424 pub fn next(&mut self, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
425 if self.done || self.cur.is_empty() {
426 return None;
427 }
428
429 let id_offset = self.cur.offset();
430 let id = match self.cur.varint() {
431 Some(v) if v.overflow => {
432 ctx.report(struct_name, 0, id_offset, DiagKind::BadVarint);
433 self.done = true;
434 return None;
435 }
436 Some(v) => v.value,
437 None => {
438 self.done = true;
439 return None;
440 }
441 };
442
443 if id == 0 {
445 self.done = true;
446 return None;
447 }
448
449 let len_offset = self.cur.offset();
450 let len = match self.cur.varint() {
451 Some(v) if v.overflow => {
452 ctx.report(struct_name, id, len_offset, DiagKind::BadVarint);
453 self.done = true;
454 return None;
455 }
456 Some(v) => v.value as usize,
457 None => {
458 ctx.report(struct_name, id, len_offset, DiagKind::ShortChunk);
459 self.done = true;
460 return None;
461 }
462 };
463
464 let offset = self.cur.offset();
465 let data = match self.cur.take(len) {
466 Some(data) => data,
467 None => {
468 ctx.report(struct_name, id, offset, DiagKind::ChunkOverrun);
469 self.done = true;
470 self.cur.take_rest()
471 }
472 };
473
474 Some(Chunk { id, data, offset })
475 }
476}
477
478#[derive(Clone, Copy, Debug)]
480pub struct ListItem<'a> {
481 pub id: i32,
483 pub body: &'a [u8],
485 pub offset: u32,
487}
488
489impl<'a> ListItem<'a> {
490 #[must_use]
492 #[inline]
493 pub const fn chunks(&self) -> ChunkIter<'a> {
494 ChunkIter::new(self.body, self.offset)
495 }
496
497 #[must_use]
499 #[inline]
500 pub fn find(&self, id: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Option<Chunk<'a>> {
501 ChunkIter::find(self.body, self.offset, id, ctx, struct_name)
502 }
503}
504
505#[derive(Clone, Debug)]
511pub struct ListWalker<'a> {
512 cur: Cursor<'a>,
513 left: u32,
514 name: &'static str,
515}
516
517impl<'a> ListWalker<'a> {
518 #[must_use]
522 pub fn new(body: &'a [u8], base: u32, ctx: &mut Ctx<'_>, struct_name: &'static str) -> Self {
523 let mut cur = Cursor::with_base(body, base);
524 let count = cur.varint_lenient(ctx, struct_name, 0);
525 let left = (count.max(0) as usize).min(cur.remaining_len() / 2 + 1) as u32;
528 Self {
529 cur,
530 left,
531 name: struct_name,
532 }
533 }
534
535 #[must_use]
537 #[inline]
538 pub const fn remaining(&self) -> u32 {
539 self.left
540 }
541
542 #[must_use]
544 pub fn next(&mut self, ctx: &mut Ctx<'_>) -> Option<ListItem<'a>> {
545 if self.left == 0 || self.cur.is_empty() {
546 return None;
547 }
548 self.left -= 1;
549
550 let id = self.cur.varint_lenient(ctx, self.name, 0);
551 let offset = self.cur.offset();
552 let body = ChunkIter::consume(&mut self.cur, ctx, self.name);
553 Some(ListItem { id, body, offset })
554 }
555}