1use crate::{
15 cursor::{ChunkIter, Ctx, Cursor},
16 diag::DiagKind,
17 engine::Engine,
18 sink::Sink,
19 wire,
20};
21use alloc::{borrow::Cow, vec::Vec};
22
23#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
31pub struct DbStr<'a>(Cow<'a, [u8]>);
32
33impl<'a> DbStr<'a> {
34 #[must_use]
36 #[inline]
37 pub const fn from_bytes(bytes: &'a [u8]) -> Self {
38 Self(Cow::Borrowed(bytes))
39 }
40
41 #[must_use]
43 #[inline]
44 pub const fn from_vec(bytes: Vec<u8>) -> Self {
45 Self(Cow::Owned(bytes))
46 }
47
48 #[must_use]
50 #[inline]
51 pub fn as_bytes(&self) -> &[u8] {
52 &self.0
53 }
54
55 #[must_use]
57 #[inline]
58 pub fn len(&self) -> usize {
59 self.0.len()
60 }
61
62 #[must_use]
64 #[inline]
65 pub fn is_empty(&self) -> bool {
66 self.0.is_empty()
67 }
68
69 #[must_use]
71 pub fn into_owned(self) -> DbStr<'static> {
72 DbStr(Cow::Owned(self.0.into_owned()))
73 }
74
75 #[must_use]
80 #[inline]
81 pub fn as_utf8(&self) -> Option<&str> {
82 core::str::from_utf8(&self.0).ok()
83 }
84}
85
86impl<'a> From<&'a [u8]> for DbStr<'a> {
87 #[inline]
88 fn from(bytes: &'a [u8]) -> Self {
89 Self::from_bytes(bytes)
90 }
91}
92
93pub trait Strings<'a> {
100 fn visit_strings(&self, f: &mut dyn FnMut(&'static str, &DbStr<'a>));
102}
103
104#[derive(Clone, Debug, Default, Eq, PartialEq)]
108pub struct BitArray<'a>(Cow<'a, [u8]>);
109
110impl<'a> BitArray<'a> {
111 #[must_use]
113 #[inline]
114 pub const fn from_bytes(bytes: &'a [u8]) -> Self {
115 Self(Cow::Borrowed(bytes))
116 }
117
118 #[must_use]
120 #[inline]
121 pub const fn from_vec(bytes: Vec<u8>) -> Self {
122 Self(Cow::Owned(bytes))
123 }
124
125 #[must_use]
127 #[inline]
128 pub fn len(&self) -> usize {
129 self.0.len()
130 }
131
132 #[must_use]
134 #[inline]
135 pub fn is_empty(&self) -> bool {
136 self.0.is_empty()
137 }
138
139 #[must_use]
141 #[inline]
142 pub fn get(&self, index: usize) -> Option<bool> {
143 self.0.get(index).map(|&b| b != 0)
144 }
145
146 pub fn iter(&self) -> impl Iterator<Item = bool> + '_ {
148 self.0.iter().map(|&b| b != 0)
149 }
150
151 #[must_use]
153 #[inline]
154 pub fn as_bytes(&self) -> &[u8] {
155 &self.0
156 }
157
158 #[must_use]
160 pub fn into_owned(self) -> BitArray<'static> {
161 BitArray(Cow::Owned(self.0.into_owned()))
162 }
163}
164
165pub trait LcfField<'a>: Sized {
167 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self;
171
172 fn field_default(engine: Engine) -> Self;
178
179 fn lcf_size(&self, engine: Engine) -> u32;
181
182 #[inline]
186 fn lcf_differs(&self, other: &Self) -> bool
187 where
188 Self: PartialEq,
189 {
190 self != other
191 }
192
193 #[inline]
198 fn element_count(&self) -> u32 {
199 0
200 }
201
202 fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error>;
208}
209
210#[inline]
212fn check_consumed(cur: &Cursor<'_>, ctx: &mut Ctx<'_>, owner: &'static str, id: u32) {
213 if !cur.is_empty() {
214 ctx.report(owner, id, cur.offset(), DiagKind::TrailingBytes);
215 }
216}
217
218impl<'a> LcfField<'a> for i32 {
219 #[inline]
220 fn field_default(_engine: Engine) -> Self {
221 0
222 }
223
224 #[inline]
225 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
226 let mut cur = Cursor::new(data);
227 let value = cur.varint_lenient(ctx, owner, id);
228 check_consumed(&cur, ctx, owner, id);
229 value
230 }
231
232 #[inline]
233 fn lcf_size(&self, _engine: Engine) -> u32 {
234 wire::varint_len(*self as u32)
235 }
236
237 #[inline]
238 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
239 wire::write_varint(sink, *self as u32)
240 }
241}
242
243impl<'a> LcfField<'a> for bool {
244 #[inline]
245 fn field_default(_engine: Engine) -> Self {
246 false
247 }
248
249 #[inline]
250 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
251 <i32 as LcfField>::read(data, ctx, owner, id) > 0
252 }
253
254 #[inline]
255 fn lcf_size(&self, _engine: Engine) -> u32 {
256 1
257 }
258
259 #[inline]
260 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
261 sink.write(&[u8::from(*self)])
262 }
263}
264
265macro_rules! impl_fixed_field {
267 ($ty:ty, $size:literal, $read:ident) => {
268 impl<'a> LcfField<'a> for $ty {
269 #[inline]
270 fn field_default(_engine: Engine) -> Self {
271 <$ty>::default()
272 }
273
274 #[inline]
275 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
276 let mut cur = Cursor::new(data);
277 match cur.$read() {
278 Some(value) => {
279 check_consumed(&cur, ctx, owner, id);
280 value
281 }
282 None => {
283 ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
284 Self::default()
285 }
286 }
287 }
288
289 #[inline]
290 fn lcf_size(&self, _engine: Engine) -> u32 {
291 $size
292 }
293
294 #[inline]
295 fn lcf_differs(&self, other: &Self) -> bool {
296 self.to_le_bytes() != other.to_le_bytes()
297 }
298
299 #[inline]
300 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
301 sink.write(&self.to_le_bytes())
302 }
303 }
304 };
305}
306
307impl_fixed_field!(i16, 2, i16_le);
308impl_fixed_field!(u32, 4, u32_le);
309impl_fixed_field!(f64, 8, f64_le);
310
311impl<'a> LcfField<'a> for u8 {
312 #[inline]
313 fn field_default(_engine: Engine) -> Self {
314 0
315 }
316
317 #[inline]
318 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
319 match data.first() {
320 Some(&byte) => byte,
321 None => {
322 ctx.report(owner, id, 0, DiagKind::ShortChunk);
323 0
324 }
325 }
326 }
327
328 #[inline]
329 fn lcf_size(&self, _engine: Engine) -> u32 {
330 1
331 }
332
333 #[inline]
334 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
335 sink.write(&[*self])
336 }
337}
338
339impl<'a> LcfField<'a> for i8 {
340 #[inline]
341 fn field_default(_engine: Engine) -> Self {
342 0
343 }
344
345 #[inline]
346 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
347 <u8 as LcfField>::read(data, ctx, owner, id) as Self
348 }
349
350 #[inline]
351 fn lcf_size(&self, _engine: Engine) -> u32 {
352 1
353 }
354
355 #[inline]
356 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
357 sink.write(&[*self as u8])
358 }
359}
360
361impl<'a> LcfField<'a> for DbStr<'a> {
362 #[inline]
363 fn field_default(_engine: Engine) -> Self {
364 Self::from_bytes(&[])
365 }
366
367 #[inline]
368 fn read(data: &'a [u8], _ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
369 Self::from_bytes(data)
371 }
372
373 #[inline]
374 #[allow(clippy::cast_possible_truncation)]
375 fn lcf_size(&self, _engine: Engine) -> u32 {
376 self.0.len() as u32
377 }
378
379 #[inline]
380 #[allow(clippy::cast_possible_truncation)]
381 fn element_count(&self) -> u32 {
382 self.0.len() as u32
383 }
384
385 #[inline]
386 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
387 sink.write(&self.0)
388 }
389}
390
391impl<'a> LcfField<'a> for BitArray<'a> {
392 #[inline]
393 fn field_default(_engine: Engine) -> Self {
394 Self::from_bytes(&[])
395 }
396
397 #[inline]
398 fn read(data: &'a [u8], _ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
399 Self::from_bytes(data)
400 }
401
402 #[inline]
403 #[allow(clippy::cast_possible_truncation)]
404 fn lcf_size(&self, _engine: Engine) -> u32 {
405 self.0.len() as u32
406 }
407
408 #[inline]
409 #[allow(clippy::cast_possible_truncation)]
410 fn element_count(&self) -> u32 {
411 self.0.len() as u32
412 }
413
414 #[inline]
415 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
416 sink.write(&self.0)
417 }
418}
419
420pub trait PackedPrim: Sized + Copy {
425 const SIZE: usize;
427 fn decode(bytes: &[u8]) -> Self;
429 fn encode(self, out: &mut [u8; 8]) -> usize;
431}
432
433impl PackedPrim for u8 {
434 const SIZE: usize = 1;
435 #[inline]
436 fn decode(bytes: &[u8]) -> Self {
437 bytes[0]
438 }
439 #[inline]
440 fn encode(self, out: &mut [u8; 8]) -> usize {
441 out[0] = self;
442 1
443 }
444}
445
446impl PackedPrim for i16 {
447 const SIZE: usize = 2;
448 #[inline]
449 fn decode(bytes: &[u8]) -> Self {
450 Self::from_le_bytes([bytes[0], bytes[1]])
451 }
452 #[inline]
453 fn encode(self, out: &mut [u8; 8]) -> usize {
454 out[..2].copy_from_slice(&self.to_le_bytes());
455 2
456 }
457}
458
459impl PackedPrim for i32 {
460 const SIZE: usize = 4;
461 #[inline]
462 fn decode(bytes: &[u8]) -> Self {
463 Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
464 }
465 #[inline]
466 fn encode(self, out: &mut [u8; 8]) -> usize {
467 out[..4].copy_from_slice(&self.to_le_bytes());
468 4
469 }
470}
471
472impl PackedPrim for u32 {
473 const SIZE: usize = 4;
474 #[inline]
475 fn decode(bytes: &[u8]) -> Self {
476 Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
477 }
478 #[inline]
479 fn encode(self, out: &mut [u8; 8]) -> usize {
480 out[..4].copy_from_slice(&self.to_le_bytes());
481 4
482 }
483}
484
485#[derive(Clone, Debug, Default, Eq, PartialEq)]
491pub struct Packed<T>(pub Vec<T>);
492
493impl<T> core::ops::Deref for Packed<T> {
494 type Target = Vec<T>;
495 #[inline]
496 fn deref(&self) -> &Vec<T> {
497 &self.0
498 }
499}
500
501impl<'a, T: PackedPrim> LcfField<'a> for Packed<T> {
502 #[inline]
503 fn field_default(_engine: Engine) -> Self {
504 Self(Vec::new())
505 }
506
507 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
508 let count = data.len() / T::SIZE;
509 if data.len() % T::SIZE != 0 {
510 ctx.report(owner, id, 0, DiagKind::RaggedArray);
511 }
512 let mut out = Vec::with_capacity(count);
513 for i in 0..count {
514 out.push(T::decode(&data[i * T::SIZE..]));
515 }
516 Self(out)
517 }
518
519 #[inline]
520 #[allow(clippy::cast_possible_truncation)]
521 fn lcf_size(&self, _engine: Engine) -> u32 {
522 (self.0.len() * T::SIZE) as u32
523 }
524
525 #[inline]
526 #[allow(clippy::cast_possible_truncation)]
527 fn element_count(&self) -> u32 {
528 self.0.len() as u32
529 }
530
531 fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
532 let mut buf = [0u8; 8];
533 for &value in &self.0 {
534 let n = value.encode(&mut buf);
535 sink.write(&buf[..n])?;
536 }
537 Ok(())
538 }
539}
540
541pub trait LcfStruct<'a>: Sized {
545 const NAME: &'static str;
547
548 fn defaults(engine: Engine) -> Self;
553
554 fn apply_chunk(&mut self, id: u32, data: &'a [u8], ctx: &mut Ctx<'_>) -> Option<u32>;
560
561 fn unknown_chunks(&self) -> &UnknownChunks;
563
564 fn unknown_chunks_mut(&mut self) -> &mut UnknownChunks;
566
567 fn body_size(&self, engine: Engine) -> u32 {
571 let mut counter = crate::sink::CountSink::new();
572 let _ = self.write_body(&mut counter, engine);
574 counter.len() as u32
575 }
576
577 fn write_body<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error>;
583
584 fn read_stream(chunks: &mut ChunkIter<'a>, ctx: &mut Ctx<'_>) -> Self {
586 let mut obj = Self::defaults(ctx.engine);
587 let mut anchor = 0u32;
590 while let Some(chunk) = chunks.next(ctx, Self::NAME) {
591 match obj.apply_chunk(chunk.id, chunk.data, ctx) {
592 Some(field_id) => anchor = field_id,
593 None => {
594 ctx.report(Self::NAME, chunk.id, chunk.offset, DiagKind::UnknownChunk);
596 obj.unknown_chunks_mut().0.push(UnknownChunk {
597 data: chunk.data.to_vec(),
598 id: chunk.id,
599 anchor,
600 });
601 }
602 }
603 if ctx.should_abort() {
604 break;
605 }
606 }
607 obj
608 }
609}
610
611impl<'a, T: LcfStruct<'a>> LcfField<'a> for T {
613 #[inline]
614 fn field_default(engine: Engine) -> Self {
615 T::defaults(engine)
616 }
617
618 #[inline]
619 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
620 let mut chunks = ChunkIter::new(data, 0);
621 T::read_stream(&mut chunks, ctx)
622 }
623
624 #[inline]
625 fn lcf_size(&self, engine: Engine) -> u32 {
626 self.body_size(engine) + 1
628 }
629
630 #[inline]
631 fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
632 self.write_body(sink, engine)?;
633 sink.write(&[0])
634 }
635}
636
637pub trait LcfIndexed<'a>: LcfStruct<'a> {
642 fn id(&self) -> i32;
644 fn set_id(&mut self, id: i32);
646}
647
648#[derive(Clone, Debug, Default, Eq, PartialEq)]
654pub struct List<T>(pub Vec<T>);
655
656impl<T> core::ops::Deref for List<T> {
657 type Target = Vec<T>;
658 #[inline]
659 fn deref(&self) -> &Vec<T> {
660 &self.0
661 }
662}
663
664impl<T> core::ops::DerefMut for List<T> {
665 #[inline]
666 fn deref_mut(&mut self) -> &mut Vec<T> {
667 &mut self.0
668 }
669}
670
671impl<'a, T: LcfIndexed<'a>> List<T> {
672 pub fn read_inline(cur: &mut Cursor<'a>, ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
676 let count = cur.varint_lenient(ctx, owner, id);
677
678 let max_possible = cur.remaining_len() / 2 + 1;
682 let count = (count.max(0) as usize).min(max_possible);
683 let mut out = Vec::with_capacity(count);
684
685 for _ in 0..count {
686 if cur.is_empty() {
687 ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
688 break;
689 }
690 let elem_id = cur.varint_lenient(ctx, owner, id);
691 let mut chunks = ChunkIter::from_cursor(cur.clone());
692 let mut elem = T::read_stream(&mut chunks, ctx);
693 elem.set_id(elem_id);
694 *cur = chunks.into_cursor();
695 out.push(elem);
696 if ctx.should_abort() {
697 break;
698 }
699 }
700
701 Self(out)
702 }
703}
704
705impl<'a, T: LcfIndexed<'a>> LcfField<'a> for List<T> {
706 #[inline]
707 fn field_default(_engine: Engine) -> Self {
708 Self(Vec::new())
709 }
710
711 #[inline]
712 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
713 let mut cur = Cursor::new(data);
714 Self::read_inline(&mut cur, ctx, owner, id)
715 }
716
717 #[inline]
718 #[allow(clippy::cast_possible_truncation)]
719 fn element_count(&self) -> u32 {
720 self.0.len() as u32
721 }
722
723 #[allow(clippy::cast_possible_truncation)]
724 fn lcf_size(&self, engine: Engine) -> u32 {
725 let mut total = wire::varint_len(self.0.len() as u32);
726 for elem in &self.0 {
727 total += wire::varint_len(elem.id() as u32) + elem.body_size(engine) + 1;
729 }
730 total
731 }
732
733 #[allow(clippy::cast_possible_truncation)]
734 fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
735 wire::write_varint(sink, self.0.len() as u32)?;
736 for elem in &self.0 {
737 wire::write_varint(sink, elem.id() as u32)?;
738 elem.write_body(sink, engine)?;
739 sink.write(&[0])?;
740 }
741 Ok(())
742 }
743}
744
745#[derive(Clone, Debug, Default, Eq, PartialEq)]
752pub struct UnindexedList<T>(pub Vec<T>);
753
754impl<T> core::ops::Deref for UnindexedList<T> {
755 type Target = Vec<T>;
756 #[inline]
757 fn deref(&self) -> &Vec<T> {
758 &self.0
759 }
760}
761
762impl<T> core::ops::DerefMut for UnindexedList<T> {
763 #[inline]
764 fn deref_mut(&mut self) -> &mut Vec<T> {
765 &mut self.0
766 }
767}
768
769impl<'a, T: LcfStruct<'a>> LcfField<'a> for UnindexedList<T> {
770 #[inline]
771 fn field_default(_engine: Engine) -> Self {
772 Self(Vec::new())
773 }
774
775 fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
776 let mut cur = Cursor::new(data);
777 let count = cur.varint_lenient(ctx, owner, id);
778
779 let count = (count.max(0) as usize).min(cur.remaining_len() + 1);
782 let mut out = Vec::with_capacity(count);
783
784 for _ in 0..count {
785 if cur.is_empty() {
786 ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
787 break;
788 }
789 let mut chunks = ChunkIter::from_cursor(cur);
790 out.push(T::read_stream(&mut chunks, ctx));
791 cur = chunks.into_cursor();
792 if ctx.should_abort() {
793 break;
794 }
795 }
796
797 Self(out)
798 }
799
800 #[allow(clippy::cast_possible_truncation)]
801 fn lcf_size(&self, engine: Engine) -> u32 {
802 let mut total = wire::varint_len(self.0.len() as u32);
803 for elem in &self.0 {
804 total += elem.body_size(engine) + 1;
805 }
806 total
807 }
808
809 #[allow(clippy::cast_possible_truncation)]
810 fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
811 wire::write_varint(sink, self.0.len() as u32)?;
812 for elem in &self.0 {
813 elem.write_body(sink, engine)?;
814 sink.write(&[0])?;
815 }
816 Ok(())
817 }
818
819 #[inline]
820 #[allow(clippy::cast_possible_truncation)]
821 fn element_count(&self) -> u32 {
822 self.0.len() as u32
823 }
824}
825
826#[derive(Clone, Debug, Default, Eq, PartialEq)]
841#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
842pub struct UnknownChunk {
843 pub data: Vec<u8>,
845 pub id: u32,
847 pub anchor: u32,
856}
857
858#[derive(Clone, Debug, Default, Eq, PartialEq)]
863#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
864#[cfg_attr(feature = "serde", serde(transparent))]
865pub struct UnknownChunks(pub Vec<UnknownChunk>);
866
867impl UnknownChunks {
868 #[must_use]
870 #[inline]
871 pub const fn new() -> Self {
872 Self(Vec::new())
873 }
874
875 #[must_use]
880 #[inline]
881 pub fn is_empty(&self) -> bool {
882 self.0.is_empty()
883 }
884
885 #[must_use]
887 #[inline]
888 pub fn len(&self) -> usize {
889 self.0.len()
890 }
891
892 #[allow(clippy::cast_possible_truncation)]
902 pub fn write_anchored<S: Sink>(&self, sink: &mut S, anchor: u32) -> Result<(), S::Error> {
903 if self.0.is_empty() {
904 return Ok(());
905 }
906 for chunk in self.0.iter().filter(|chunk| chunk.anchor == anchor) {
907 wire::write_varint(sink, chunk.id)?;
908 wire::write_varint(sink, chunk.data.len() as u32)?;
909 sink.write(&chunk.data)?;
910 }
911 Ok(())
912 }
913}
914
915impl core::ops::Deref for UnknownChunks {
916 type Target = Vec<UnknownChunk>;
917 #[inline]
918 fn deref(&self) -> &Vec<UnknownChunk> {
919 &self.0
920 }
921}
922
923impl core::ops::DerefMut for UnknownChunks {
924 #[inline]
925 fn deref_mut(&mut self) -> &mut Vec<UnknownChunk> {
926 &mut self.0
927 }
928}