use crate::{
cursor::{ChunkIter, Ctx, Cursor},
diag::DiagKind,
engine::Engine,
sink::Sink,
wire,
};
use alloc::{borrow::Cow, vec::Vec};
#[derive(Clone, Debug, Default, Eq, Hash, Ord, PartialEq, PartialOrd)]
pub struct DbStr<'a>(Cow<'a, [u8]>);
impl<'a> DbStr<'a> {
#[must_use]
#[inline]
pub const fn from_bytes(bytes: &'a [u8]) -> Self {
Self(Cow::Borrowed(bytes))
}
#[must_use]
#[inline]
pub const fn from_vec(bytes: Vec<u8>) -> Self {
Self(Cow::Owned(bytes))
}
#[must_use]
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
pub fn into_owned(self) -> DbStr<'static> {
DbStr(Cow::Owned(self.0.into_owned()))
}
#[must_use]
#[inline]
pub fn as_utf8(&self) -> Option<&str> {
core::str::from_utf8(&self.0).ok()
}
}
impl<'a> From<&'a [u8]> for DbStr<'a> {
#[inline]
fn from(bytes: &'a [u8]) -> Self {
Self::from_bytes(bytes)
}
}
pub trait Strings<'a> {
fn visit_strings(&self, f: &mut dyn FnMut(&'static str, &DbStr<'a>));
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct BitArray<'a>(Cow<'a, [u8]>);
impl<'a> BitArray<'a> {
#[must_use]
#[inline]
pub const fn from_bytes(bytes: &'a [u8]) -> Self {
Self(Cow::Borrowed(bytes))
}
#[must_use]
#[inline]
pub const fn from_vec(bytes: Vec<u8>) -> Self {
Self(Cow::Owned(bytes))
}
#[must_use]
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
#[inline]
pub fn get(&self, index: usize) -> Option<bool> {
self.0.get(index).map(|&b| b != 0)
}
pub fn iter(&self) -> impl Iterator<Item = bool> + '_ {
self.0.iter().map(|&b| b != 0)
}
#[must_use]
#[inline]
pub fn as_bytes(&self) -> &[u8] {
&self.0
}
#[must_use]
pub fn into_owned(self) -> BitArray<'static> {
BitArray(Cow::Owned(self.0.into_owned()))
}
}
pub trait LcfField<'a>: Sized {
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self;
fn field_default(engine: Engine) -> Self;
fn lcf_size(&self, engine: Engine) -> u32;
#[inline]
fn lcf_differs(&self, other: &Self) -> bool
where
Self: PartialEq,
{
self != other
}
#[inline]
fn element_count(&self) -> u32 {
0
}
fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error>;
}
#[inline]
fn check_consumed(cur: &Cursor<'_>, ctx: &mut Ctx<'_>, owner: &'static str, id: u32) {
if !cur.is_empty() {
ctx.report(owner, id, cur.offset(), DiagKind::TrailingBytes);
}
}
impl<'a> LcfField<'a> for i32 {
#[inline]
fn field_default(_engine: Engine) -> Self {
0
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let mut cur = Cursor::new(data);
let value = cur.varint_lenient(ctx, owner, id);
check_consumed(&cur, ctx, owner, id);
value
}
#[inline]
fn lcf_size(&self, _engine: Engine) -> u32 {
wire::varint_len(*self as u32)
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
wire::write_varint(sink, *self as u32)
}
}
impl<'a> LcfField<'a> for bool {
#[inline]
fn field_default(_engine: Engine) -> Self {
false
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
<i32 as LcfField>::read(data, ctx, owner, id) > 0
}
#[inline]
fn lcf_size(&self, _engine: Engine) -> u32 {
1
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&[u8::from(*self)])
}
}
macro_rules! impl_fixed_field {
($ty:ty, $size:literal, $read:ident) => {
impl<'a> LcfField<'a> for $ty {
#[inline]
fn field_default(_engine: Engine) -> Self {
<$ty>::default()
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let mut cur = Cursor::new(data);
match cur.$read() {
Some(value) => {
check_consumed(&cur, ctx, owner, id);
value
}
None => {
ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
Self::default()
}
}
}
#[inline]
fn lcf_size(&self, _engine: Engine) -> u32 {
$size
}
#[inline]
fn lcf_differs(&self, other: &Self) -> bool {
self.to_le_bytes() != other.to_le_bytes()
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&self.to_le_bytes())
}
}
};
}
impl_fixed_field!(i16, 2, i16_le);
impl_fixed_field!(u32, 4, u32_le);
impl_fixed_field!(f64, 8, f64_le);
impl<'a> LcfField<'a> for u8 {
#[inline]
fn field_default(_engine: Engine) -> Self {
0
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
match data.first() {
Some(&byte) => byte,
None => {
ctx.report(owner, id, 0, DiagKind::ShortChunk);
0
}
}
}
#[inline]
fn lcf_size(&self, _engine: Engine) -> u32 {
1
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&[*self])
}
}
impl<'a> LcfField<'a> for i8 {
#[inline]
fn field_default(_engine: Engine) -> Self {
0
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
<u8 as LcfField>::read(data, ctx, owner, id) as Self
}
#[inline]
fn lcf_size(&self, _engine: Engine) -> u32 {
1
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&[*self as u8])
}
}
impl<'a> LcfField<'a> for DbStr<'a> {
#[inline]
fn field_default(_engine: Engine) -> Self {
Self::from_bytes(&[])
}
#[inline]
fn read(data: &'a [u8], _ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
Self::from_bytes(data)
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn lcf_size(&self, _engine: Engine) -> u32 {
self.0.len() as u32
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn element_count(&self) -> u32 {
self.0.len() as u32
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&self.0)
}
}
impl<'a> LcfField<'a> for BitArray<'a> {
#[inline]
fn field_default(_engine: Engine) -> Self {
Self::from_bytes(&[])
}
#[inline]
fn read(data: &'a [u8], _ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
Self::from_bytes(data)
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn lcf_size(&self, _engine: Engine) -> u32 {
self.0.len() as u32
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn element_count(&self) -> u32 {
self.0.len() as u32
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
sink.write(&self.0)
}
}
pub trait PackedPrim: Sized + Copy {
const SIZE: usize;
fn decode(bytes: &[u8]) -> Self;
fn encode(self, out: &mut [u8; 8]) -> usize;
}
impl PackedPrim for u8 {
const SIZE: usize = 1;
#[inline]
fn decode(bytes: &[u8]) -> Self {
bytes[0]
}
#[inline]
fn encode(self, out: &mut [u8; 8]) -> usize {
out[0] = self;
1
}
}
impl PackedPrim for i16 {
const SIZE: usize = 2;
#[inline]
fn decode(bytes: &[u8]) -> Self {
Self::from_le_bytes([bytes[0], bytes[1]])
}
#[inline]
fn encode(self, out: &mut [u8; 8]) -> usize {
out[..2].copy_from_slice(&self.to_le_bytes());
2
}
}
impl PackedPrim for i32 {
const SIZE: usize = 4;
#[inline]
fn decode(bytes: &[u8]) -> Self {
Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
}
#[inline]
fn encode(self, out: &mut [u8; 8]) -> usize {
out[..4].copy_from_slice(&self.to_le_bytes());
4
}
}
impl PackedPrim for u32 {
const SIZE: usize = 4;
#[inline]
fn decode(bytes: &[u8]) -> Self {
Self::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])
}
#[inline]
fn encode(self, out: &mut [u8; 8]) -> usize {
out[..4].copy_from_slice(&self.to_le_bytes());
4
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct Packed<T>(pub Vec<T>);
impl<T> core::ops::Deref for Packed<T> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Vec<T> {
&self.0
}
}
impl<'a, T: PackedPrim> LcfField<'a> for Packed<T> {
#[inline]
fn field_default(_engine: Engine) -> Self {
Self(Vec::new())
}
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let count = data.len() / T::SIZE;
if data.len() % T::SIZE != 0 {
ctx.report(owner, id, 0, DiagKind::RaggedArray);
}
let mut out = Vec::with_capacity(count);
for i in 0..count {
out.push(T::decode(&data[i * T::SIZE..]));
}
Self(out)
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn lcf_size(&self, _engine: Engine) -> u32 {
(self.0.len() * T::SIZE) as u32
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn element_count(&self) -> u32 {
self.0.len() as u32
}
fn write<S: Sink>(&self, sink: &mut S, _engine: Engine) -> Result<(), S::Error> {
let mut buf = [0u8; 8];
for &value in &self.0 {
let n = value.encode(&mut buf);
sink.write(&buf[..n])?;
}
Ok(())
}
}
pub trait LcfStruct<'a>: Sized {
const NAME: &'static str;
fn defaults(engine: Engine) -> Self;
fn apply_chunk(&mut self, id: u32, data: &'a [u8], ctx: &mut Ctx<'_>) -> Option<u32>;
fn unknown_chunks(&self) -> &UnknownChunks;
fn unknown_chunks_mut(&mut self) -> &mut UnknownChunks;
fn body_size(&self, engine: Engine) -> u32 {
let mut counter = crate::sink::CountSink::new();
let _ = self.write_body(&mut counter, engine);
counter.len() as u32
}
fn write_body<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error>;
fn read_stream(chunks: &mut ChunkIter<'a>, ctx: &mut Ctx<'_>) -> Self {
let mut obj = Self::defaults(ctx.engine);
let mut anchor = 0u32;
while let Some(chunk) = chunks.next(ctx, Self::NAME) {
match obj.apply_chunk(chunk.id, chunk.data, ctx) {
Some(field_id) => anchor = field_id,
None => {
ctx.report(Self::NAME, chunk.id, chunk.offset, DiagKind::UnknownChunk);
obj.unknown_chunks_mut().0.push(UnknownChunk {
data: chunk.data.to_vec(),
id: chunk.id,
anchor,
});
}
}
if ctx.should_abort() {
break;
}
}
obj
}
}
impl<'a, T: LcfStruct<'a>> LcfField<'a> for T {
#[inline]
fn field_default(engine: Engine) -> Self {
T::defaults(engine)
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, _owner: &'static str, _id: u32) -> Self {
let mut chunks = ChunkIter::new(data, 0);
T::read_stream(&mut chunks, ctx)
}
#[inline]
fn lcf_size(&self, engine: Engine) -> u32 {
self.body_size(engine) + 1
}
#[inline]
fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
self.write_body(sink, engine)?;
sink.write(&[0])
}
}
pub trait LcfIndexed<'a>: LcfStruct<'a> {
fn id(&self) -> i32;
fn set_id(&mut self, id: i32);
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct List<T>(pub Vec<T>);
impl<T> core::ops::Deref for List<T> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Vec<T> {
&self.0
}
}
impl<T> core::ops::DerefMut for List<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Vec<T> {
&mut self.0
}
}
impl<'a, T: LcfIndexed<'a>> List<T> {
pub fn read_inline(cur: &mut Cursor<'a>, ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let count = cur.varint_lenient(ctx, owner, id);
let max_possible = cur.remaining_len() / 2 + 1;
let count = (count.max(0) as usize).min(max_possible);
let mut out = Vec::with_capacity(count);
for _ in 0..count {
if cur.is_empty() {
ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
break;
}
let elem_id = cur.varint_lenient(ctx, owner, id);
let mut chunks = ChunkIter::from_cursor(cur.clone());
let mut elem = T::read_stream(&mut chunks, ctx);
elem.set_id(elem_id);
*cur = chunks.into_cursor();
out.push(elem);
if ctx.should_abort() {
break;
}
}
Self(out)
}
}
impl<'a, T: LcfIndexed<'a>> LcfField<'a> for List<T> {
#[inline]
fn field_default(_engine: Engine) -> Self {
Self(Vec::new())
}
#[inline]
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let mut cur = Cursor::new(data);
Self::read_inline(&mut cur, ctx, owner, id)
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn element_count(&self) -> u32 {
self.0.len() as u32
}
#[allow(clippy::cast_possible_truncation)]
fn lcf_size(&self, engine: Engine) -> u32 {
let mut total = wire::varint_len(self.0.len() as u32);
for elem in &self.0 {
total += wire::varint_len(elem.id() as u32) + elem.body_size(engine) + 1;
}
total
}
#[allow(clippy::cast_possible_truncation)]
fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
wire::write_varint(sink, self.0.len() as u32)?;
for elem in &self.0 {
wire::write_varint(sink, elem.id() as u32)?;
elem.write_body(sink, engine)?;
sink.write(&[0])?;
}
Ok(())
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
pub struct UnindexedList<T>(pub Vec<T>);
impl<T> core::ops::Deref for UnindexedList<T> {
type Target = Vec<T>;
#[inline]
fn deref(&self) -> &Vec<T> {
&self.0
}
}
impl<T> core::ops::DerefMut for UnindexedList<T> {
#[inline]
fn deref_mut(&mut self) -> &mut Vec<T> {
&mut self.0
}
}
impl<'a, T: LcfStruct<'a>> LcfField<'a> for UnindexedList<T> {
#[inline]
fn field_default(_engine: Engine) -> Self {
Self(Vec::new())
}
fn read(data: &'a [u8], ctx: &mut Ctx<'_>, owner: &'static str, id: u32) -> Self {
let mut cur = Cursor::new(data);
let count = cur.varint_lenient(ctx, owner, id);
let count = (count.max(0) as usize).min(cur.remaining_len() + 1);
let mut out = Vec::with_capacity(count);
for _ in 0..count {
if cur.is_empty() {
ctx.report(owner, id, cur.offset(), DiagKind::ShortChunk);
break;
}
let mut chunks = ChunkIter::from_cursor(cur);
out.push(T::read_stream(&mut chunks, ctx));
cur = chunks.into_cursor();
if ctx.should_abort() {
break;
}
}
Self(out)
}
#[allow(clippy::cast_possible_truncation)]
fn lcf_size(&self, engine: Engine) -> u32 {
let mut total = wire::varint_len(self.0.len() as u32);
for elem in &self.0 {
total += elem.body_size(engine) + 1;
}
total
}
#[allow(clippy::cast_possible_truncation)]
fn write<S: Sink>(&self, sink: &mut S, engine: Engine) -> Result<(), S::Error> {
wire::write_varint(sink, self.0.len() as u32)?;
for elem in &self.0 {
elem.write_body(sink, engine)?;
sink.write(&[0])?;
}
Ok(())
}
#[inline]
#[allow(clippy::cast_possible_truncation)]
fn element_count(&self) -> u32 {
self.0.len() as u32
}
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
pub struct UnknownChunk {
pub data: Vec<u8>,
pub id: u32,
pub anchor: u32,
}
#[derive(Clone, Debug, Default, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
pub struct UnknownChunks(pub Vec<UnknownChunk>);
impl UnknownChunks {
#[must_use]
#[inline]
pub const fn new() -> Self {
Self(Vec::new())
}
#[must_use]
#[inline]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
#[must_use]
#[inline]
pub fn len(&self) -> usize {
self.0.len()
}
#[allow(clippy::cast_possible_truncation)]
pub fn write_anchored<S: Sink>(&self, sink: &mut S, anchor: u32) -> Result<(), S::Error> {
if self.0.is_empty() {
return Ok(());
}
for chunk in self.0.iter().filter(|chunk| chunk.anchor == anchor) {
wire::write_varint(sink, chunk.id)?;
wire::write_varint(sink, chunk.data.len() as u32)?;
sink.write(&chunk.data)?;
}
Ok(())
}
}
impl core::ops::Deref for UnknownChunks {
type Target = Vec<UnknownChunk>;
#[inline]
fn deref(&self) -> &Vec<UnknownChunk> {
&self.0
}
}
impl core::ops::DerefMut for UnknownChunks {
#[inline]
fn deref_mut(&mut self) -> &mut Vec<UnknownChunk> {
&mut self.0
}
}