mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 04:04:25 +00:00
raw: opcodes::parse_list/write_list use the opcode_raw envelope walker and encoder
One opcode-list envelope implementation: opcode_raw::Records walks the records (stopping at a truncated one) for both the strict opcode_raw::parse and the typed opcodes::parse_list, and opcodes::write_list encodes through opcode_raw::encode instead of truncating lengths with as.
This commit is contained in:
@@ -27,31 +27,54 @@ impl Opcode {
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Malformed;
|
||||
|
||||
/// The records of a big-endian opcode list in order, as `(id, version, flags, params)`, ending at
|
||||
/// the declared count or at the first truncated record. The envelope walk shared by [`parse`] and
|
||||
/// the typed [`crate::opcodes::parse_list`].
|
||||
pub(crate) struct Records<'a> {
|
||||
bytes: &'a [u8],
|
||||
at: usize,
|
||||
/// Records the list header still promises.
|
||||
pub(crate) left: u32,
|
||||
}
|
||||
|
||||
impl<'a> Records<'a> {
|
||||
/// The record walker of a list; `None` when even the count is missing.
|
||||
pub(crate) fn new(bytes: &'a [u8]) -> Option<Self> {
|
||||
let left = u32::from_be_bytes(bytes.get(..4)?.try_into().ok()?);
|
||||
Some(Self { bytes, at: 4, left })
|
||||
}
|
||||
fn u32(&mut self) -> Option<u32> {
|
||||
let end = self.at.checked_add(4)?;
|
||||
let value = u32::from_be_bytes(self.bytes.get(self.at..end)?.try_into().ok()?);
|
||||
self.at = end;
|
||||
Some(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Iterator for Records<'a> {
|
||||
type Item = (u32, u32, u32, &'a [u8]);
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.left == 0 {
|
||||
return None;
|
||||
}
|
||||
let (id, version, flags, len) = (self.u32()?, self.u32()?, self.u32()?, self.u32()? as usize);
|
||||
let end = self.at.checked_add(len)?;
|
||||
let params = self.bytes.get(self.at..end)?;
|
||||
self.at = end;
|
||||
self.left -= 1;
|
||||
Some((id, version, flags, params))
|
||||
}
|
||||
}
|
||||
|
||||
/// Parse a big-endian opcode list with an explicit maximum record count.
|
||||
pub fn parse(bytes: &[u8], max_opcodes: usize) -> Result<Vec<Opcode>, Malformed> {
|
||||
let mut at = 0usize;
|
||||
let read = |at: &mut usize| -> Result<u32, Malformed> {
|
||||
let end = at.checked_add(4).ok_or(Malformed)?;
|
||||
let value = bytes.get(*at..end).and_then(|b| b.try_into().ok()).map(u32::from_be_bytes).ok_or(Malformed)?;
|
||||
*at = end;
|
||||
Ok(value)
|
||||
};
|
||||
let count = read(&mut at)? as usize;
|
||||
let records = Records::new(bytes).ok_or(Malformed)?;
|
||||
let count = records.left as usize;
|
||||
if count > bytes.len() / 16 || count > max_opcodes {
|
||||
return Err(Malformed);
|
||||
}
|
||||
let mut out = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let id = read(&mut at)?;
|
||||
let version = read(&mut at)?;
|
||||
let flags = read(&mut at)?;
|
||||
let len = read(&mut at)? as usize;
|
||||
let end = at.checked_add(len).ok_or(Malformed)?;
|
||||
let params = bytes.get(at..end).ok_or(Malformed)?.to_vec();
|
||||
at = end;
|
||||
out.push(Opcode { id, version, flags, params });
|
||||
}
|
||||
Ok(out)
|
||||
let out: Vec<Opcode> = records.map(|(id, version, flags, params)| Opcode { id, version, flags, params: params.to_vec() }).collect();
|
||||
if out.len() == count { Ok(out) } else { Err(Malformed) }
|
||||
}
|
||||
|
||||
/// An opcode list cannot be represented in the DNG wire format or allocated.
|
||||
@@ -104,4 +127,20 @@ mod tests {
|
||||
assert!(parse(&bytes[..bytes.len() - 1], 1).is_err());
|
||||
assert!(records[0].optional() && records[0].preview_skippable());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_lists_share_the_envelope() {
|
||||
use crate::opcodes::{self, Opcode as Typed};
|
||||
let typed = vec![Typed::TrimBounds { top: 1, left: 2, bottom: 3, right: 4 }, Typed::Unknown { id: 900, flags: 1, params: vec![5, 6] }];
|
||||
let bytes = opcodes::write_list(&typed);
|
||||
let raw = parse(&bytes, 8).unwrap();
|
||||
assert_eq!(raw.iter().map(|o| (o.id, o.version)).collect::<Vec<_>>(), [(6, 0x0103_0000), (900, 0x0103_0000)]);
|
||||
assert_eq!(encode(&raw).unwrap(), bytes);
|
||||
assert_eq!(opcodes::parse_list(&bytes), typed);
|
||||
// a truncated last record: the typed reader keeps what came before, the raw one refuses
|
||||
assert_eq!(opcodes::parse_list(&bytes[..bytes.len() - 1]), typed[..1]);
|
||||
assert!(parse(&bytes[..bytes.len() - 1], 8).is_err());
|
||||
assert!(opcodes::parse_list(&[0, 0]).is_empty());
|
||||
assert!(parse(&[0, 0], 8).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
+16
-20
@@ -480,31 +480,27 @@ fn params(op: &Opcode) -> (u32, u32, Vec<u8>) {
|
||||
(id, 0, o)
|
||||
}
|
||||
|
||||
/// Serialise an opcode list (inverse of [`parse_list`]).
|
||||
/// Serialise an opcode list (inverse of [`parse_list`]) through the shared envelope encoder
|
||||
/// ([`crate::opcode_raw::encode`]). A list the wire format cannot hold (a count or parameter block
|
||||
/// past 4 GiB) yields an empty blob rather than a truncated one.
|
||||
pub fn write_list(list: &[Opcode]) -> Vec<u8> {
|
||||
let mut out = (list.len() as u32).to_be_bytes().to_vec();
|
||||
for op in list {
|
||||
let (id, flags, p) = params(op);
|
||||
for v in [id, if id == 14 { 0x0106_0000 } else { 0x0103_0000 }, flags, p.len() as u32] {
|
||||
out.extend_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
out.extend_from_slice(&p);
|
||||
}
|
||||
out
|
||||
let records: Vec<crate::opcode_raw::Opcode> = list
|
||||
.iter()
|
||||
.map(|op| {
|
||||
let (id, flags, params) = params(op);
|
||||
crate::opcode_raw::Opcode { id, version: if id == 14 { 0x0106_0000 } else { 0x0103_0000 }, flags, params }
|
||||
})
|
||||
.collect();
|
||||
crate::opcode_raw::encode(&records).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Parse an opcode list blob. Malformed opcodes become [`Opcode::Unknown`]; a truncated list stops early.
|
||||
pub fn parse_list(d: &[u8]) -> Vec<Opcode> {
|
||||
let mut r = Rd { d, p: 0 };
|
||||
let Some(count) = r.u32() else { return vec![] };
|
||||
let mut out = Vec::new();
|
||||
for _ in 0..count.min(4096) {
|
||||
let (Some(id), Some(_ver), Some(flags), Some(size)) = (r.u32(), r.u32(), r.u32(), r.u32()) else { break };
|
||||
let Some(params) = d.get(r.p..r.p.saturating_add(size as usize)) else { break };
|
||||
r.p += size as usize;
|
||||
out.push(parse_one(id, flags, params).unwrap_or(Opcode::Unknown { id, flags, params: params.to_vec() }));
|
||||
}
|
||||
out
|
||||
let Some(records) = crate::opcode_raw::Records::new(d) else { return vec![] };
|
||||
records
|
||||
.take(4096)
|
||||
.map(|(id, _version, flags, params)| parse_one(id, flags, params).unwrap_or(Opcode::Unknown { id, flags, params: params.to_vec() }))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Radius normaliser: distance from the centre to the farthest image corner.
|
||||
|
||||
Reference in New Issue
Block a user