use prikk_error::{PrikkError, Result};
use crate::canonical::WireType;
use crate::{CanonicalEncode, CanonicalWriter, ObjectId};
pub const RECOGNITION_CLAIM_MAX_PATCH_IDS: usize = 100_000;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RecognitionClaimPayload {
pub block_id: ObjectId,
pub patch_ids: Vec<ObjectId>,
pub parent_block_ids: Vec<ObjectId>,
}
impl CanonicalEncode for RecognitionClaimPayload {
fn encode_canonical(&self, writer: &mut CanonicalWriter) -> Result<()> {
if self.patch_ids.is_empty() {
return Err(PrikkError::CanonicalEncoding(
"RecognitionClaim patch_ids must not be empty".to_string(),
));
}
writer.field_object_id(1, &self.block_id)?;
writer.repeated_object_id(2, &self.patch_ids)?;
writer.repeated_object_id(3, &self.parent_block_ids)?;
Ok(())
}
}
impl RecognitionClaimPayload {
pub fn decode_canonical(bytes: &[u8]) -> Result<Self> {
let mut cursor = RecognitionClaimCursor::new(bytes);
let mut block_id = None;
let mut patch_ids = Vec::new();
let mut parent_block_ids = Vec::new();
while let Some(field) = cursor.next_field()? {
match field.tag {
1 => block_id = Some(field.read_object_id()?),
2 => {
if patch_ids.len() >= RECOGNITION_CLAIM_MAX_PATCH_IDS {
return Err(PrikkError::MalformedData(format!(
"RecognitionClaim patch_ids exceeds the limit of \
{RECOGNITION_CLAIM_MAX_PATCH_IDS}"
)));
}
patch_ids.push(field.read_object_id()?);
}
3 => {
if parent_block_ids.len() >= RECOGNITION_CLAIM_MAX_PATCH_IDS {
return Err(PrikkError::MalformedData(format!(
"RecognitionClaim parent_block_ids exceeds the limit of \
{RECOGNITION_CLAIM_MAX_PATCH_IDS}"
)));
}
parent_block_ids.push(field.read_object_id()?);
}
other => {
return Err(PrikkError::MalformedData(format!(
"unknown RecognitionClaim field tag: {other}"
)));
}
}
}
let payload = Self {
block_id: block_id.ok_or_else(|| {
PrikkError::MalformedData("RecognitionClaim missing block_id".to_string())
})?,
patch_ids,
parent_block_ids,
};
if payload.patch_ids.is_empty() {
return Err(PrikkError::MalformedData(
"RecognitionClaim patch_ids must not be empty".to_string(),
));
}
Ok(payload)
}
}
struct RecognitionClaimCursor<'a> {
bytes: &'a [u8],
pos: usize,
last_tag: Option<u16>,
}
impl<'a> RecognitionClaimCursor<'a> {
const fn new(bytes: &'a [u8]) -> Self {
Self {
bytes,
pos: 0,
last_tag: None,
}
}
fn next_field(&mut self) -> Result<Option<RecognitionClaimField<'a>>> {
if self.pos == self.bytes.len() {
return Ok(None);
}
let tag = u16::from_be_bytes(self.read_array::<2>()?);
if tag == 0 {
return Err(PrikkError::MalformedData(
"field tag 0 is reserved".to_string(),
));
}
if let Some(last) = self.last_tag {
if tag < last {
return Err(PrikkError::MalformedData(format!(
"field tag order violation: {tag} after {last}"
)));
}
}
self.last_tag = Some(tag);
let wire_type = self.read_u8()?;
let len = usize::try_from(u64::from_be_bytes(self.read_array::<8>()?)).map_err(|_| {
PrikkError::MalformedData("canonical field length does not fit usize".to_string())
})?;
let value = self.read_exact(len)?;
Ok(Some(RecognitionClaimField {
tag,
wire_type,
value,
}))
}
fn read_u8(&mut self) -> Result<u8> {
let value = self.read_exact(1)?;
let Some(byte) = value.first() else {
return Err(PrikkError::MalformedData(
"unexpected empty byte".to_string(),
));
};
Ok(*byte)
}
fn read_array<const N: usize>(&mut self) -> Result<[u8; N]> {
let bytes = self.read_exact(N)?;
let mut out = [0_u8; N];
out.copy_from_slice(bytes);
Ok(out)
}
fn read_exact(&mut self, len: usize) -> Result<&'a [u8]> {
let end = self
.pos
.checked_add(len)
.ok_or_else(|| PrikkError::MalformedData("canonical range overflow".to_string()))?;
let Some(slice) = self.bytes.get(self.pos..end) else {
return Err(PrikkError::MalformedData(
"unexpected end of canonical payload".to_string(),
));
};
self.pos = end;
Ok(slice)
}
}
struct RecognitionClaimField<'a> {
tag: u16,
wire_type: u8,
value: &'a [u8],
}
impl<'a> RecognitionClaimField<'a> {
fn read_object_id(&self) -> Result<ObjectId> {
self.require_wire(WireType::ObjectId)?;
Ok(ObjectId::from_bytes(self.read_array::<32>()?))
}
fn require_wire(&self, expected: WireType) -> Result<()> {
if self.wire_type == expected as u8 {
return Ok(());
}
Err(PrikkError::MalformedData(format!(
"field {} has wrong wire type: expected {}, got {}",
self.tag, expected as u8, self.wire_type
)))
}
fn read_array<const N: usize>(&self) -> Result<[u8; N]> {
if self.value.len() != N {
return Err(PrikkError::MalformedData(format!(
"field {} expected {N} bytes, got {}",
self.tag,
self.value.len()
)));
}
let mut out = [0_u8; N];
out.copy_from_slice(self.value);
Ok(out)
}
}