refactor: deny unwrap, expect and panic in library and binary code

The library and the binary now deny clippy's unwrap_used, expect_used,
panic, unimplemented, todo and unreachable lints outside unit tests, and
forbid unsafe code. Malformed input must give an error or a warning,
never a panic.

The 36 offending calls are replaced without changing behaviour:

- Byte reads that converted a slice of checked length to an array now
  use the `Encoding::*_at` decoders, `first_chunk`, or a `Cursor`
  helper that returns `Result`; the fallbacks are the existing results
  for data of the wrong length (`Value::Other`, a skipped value, a
  short-data error).
- The fixed-offset readers of the header and the master pages build the
  array with `array::from_fn`; they index as before.
- `Node::set` returns the node it set, so `TextFramePreference` insets
  no longer look it up again with `expect`.
- The embedded value files fall back to no values if one fails to
  parse, and a block with a version bound that is not a number does not
  apply. A new unit test checks that every committed file parses and
  that every bound is a number.
- `Xml::end` without an open element fails a debug assertion and
  writes nothing in a release build.

diff_outputs.py over the corpus (without own/): 0 differing outputs,
0 changed failures, 0 changed warnings.

Idea from storytold/designcraft#98.
This commit is contained in:
aiongg committed 2026-10-08 04:18:22 +00:00
1 parent 261e378d07
commit 8b4e4a8e90
12 files changed
+162 -84

No files matched your search

+5 -2
View File
@@ -21,12 +21,15 @@ const SEQUENCE_OFFSET: usize = 0x108;
const DB_PAGES_OFFSET: usize = 0x118;
const XMP_START: &[u8] = b"<?xpacket begin=";
/// The little-endian u32 at `offset`. The callers check the length first;
/// like slice indexing, this panics if `bytes` is too short.
fn le_u32(bytes: &[u8], offset: usize) -> u32 {
u32::from_le_bytes(bytes[offset..offset + 4].try_into().unwrap())
u32::from_le_bytes(std::array::from_fn(|i| bytes[offset + i]))
}
/// The little-endian u64 at `offset`; see [`le_u32`].
fn le_u64(bytes: &[u8], offset: usize) -> u64 {
u64::from_le_bytes(bytes[offset..offset + 8].try_into().unwrap())
u64::from_le_bytes(std::array::from_fn(|i| bytes[offset + i]))
}
/// One of the two master pages at the start of the file.
+10 -6
View File
@@ -131,15 +131,17 @@ impl<'a> Database<'a> {
fn u16(&self, offset: usize) -> Result<u16, Error> {
self.bytes
.get(offset..offset + 2)
.map(|b| u16::from_le_bytes(b.try_into().unwrap()))
.get(offset..)
.and_then(<[u8]>::first_chunk)
.map(|&b| u16::from_le_bytes(b))
.ok_or_else(|| corrupt(format!("read past end of file at {offset:#x}")))
}
fn u32(&self, offset: usize) -> Result<u32, Error> {
self.bytes
.get(offset..offset + 4)
.map(|b| u32::from_le_bytes(b.try_into().unwrap()))
.get(offset..)
.and_then(<[u8]>::first_chunk)
.map(|&b| u32::from_le_bytes(b))
.ok_or_else(|| corrupt(format!("read past end of file at {offset:#x}")))
}
@@ -283,8 +285,10 @@ impl<'a> Database<'a> {
"continued record at {offset:#x} is too short"
)));
}
let next = u32::from_le_bytes(record[..4].try_into().unwrap());
let next_page = u32::from_le_bytes(record[4..8].try_into().unwrap());
// `record` starts at `offset + 4` and is at least 8 bytes long.
let next = self.u32(offset + 4)?;
let next_page = self.u32(offset + 8)?;
let here = &record[8..];
if here.is_empty() || here.len() >= len || next & 0xFFFF != 0 {
return Err(corrupt(format!("bad continuation at {offset:#x}")));
+8 -2
View File
@@ -28,8 +28,13 @@ pub enum ByteOrder {
}
impl ByteOrder {
/// The u32 at `offset` in this byte order.
///
/// # Panics
///
/// If `bytes` is shorter than `offset + 4`.
pub fn read_u32(self, bytes: &[u8], offset: usize) -> u32 {
let b: [u8; 4] = bytes[offset..offset + 4].try_into().unwrap();
let b: [u8; 4] = std::array::from_fn(|i| bytes[offset + i]);
match self {
ByteOrder::Little => u32::from_le_bytes(b),
ByteOrder::Big => u32::from_be_bytes(b),
@@ -78,7 +83,8 @@ impl Header {
other => return Err(Error::UnknownByteOrder(other)),
};
Ok(Header {
kind: bytes[KIND_OFFSET..KIND_OFFSET + 8].try_into().unwrap(),
kind: std::array::from_fn(|i| bytes[KIND_OFFSET + i]),
byte_order,
version: Version {
major: byte_order.read_u32(bytes, MAJOR_OFFSET),
+2 -7
View File
@@ -563,13 +563,8 @@ impl Writer<'_> {
&& b == c
&& c == e
{
node.set(&["TextFramePreference", "Properties"], Vec::new());
let props = node
.children
.iter_mut()
.find(|c| c.tag == "TextFramePreference")
.and_then(|t| t.children.iter_mut().find(|c| c.tag == "Properties"))
.expect("set above");
let props = node.set(&["TextFramePreference", "Properties"], Vec::new());
props.children.retain(|c| c.tag != "InsetSpacing");
props.children.push(Node {
tag: "InsetSpacing".into(),
+50 -32
View File
@@ -30,8 +30,9 @@ impl Node {
/// Set the attributes of the descendant at `path`, creating missing
/// elements (`Properties` as the first child), replacing values
/// already there in place and adding the others at the end.
pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) {
/// already there in place and adding the others at the end. Returns
/// the descendant.
pub fn set(&mut self, path: &[&str], attrs: Vec<(&str, String)>) -> &mut Node {
let mut node = self;
for tag in path {
let i = match node.children.iter().position(|c| c.tag == *tag) {
@@ -58,6 +59,7 @@ impl Node {
None => node.attrs.push((k.to_string(), v)),
}
}
node
}
/// Add the attributes and children of `other` that `self` lacks.
@@ -97,6 +99,25 @@ impl Node {
}
}
/// An embedded values file, parsed. The files are generated and committed,
/// and the test `embedded_files_parse` checks that each one parses and
/// that every version bound in it is a number. A file that did not parse
/// would give no observed values instead of stopping every conversion.
fn embedded(text: &str) -> Node {
parse(text).unwrap_or_default()
}
/// Whether a block of a values file applies to InDesign version `major`:
/// its `MinimumVersion` and `MaximumVersion`, where present, include
/// `major`. A bound that is not a number excludes the block (see
/// [`embedded`]).
fn applies(block: &Node, major: u32) -> bool {
// `None`: no bound; `Some(None)`: a bound that is not a number.
let bound = |name: &str| block.attr(name).map(|v| v.parse::<u32>().ok());
bound("MinimumVersion").is_none_or(|v| v.is_some_and(|v| v <= major))
&& bound("MaximumVersion").is_none_or(|v| v.is_some_and(|v| major <= v))
}
const ROOT_VALUES: &str = include_str!("root_values.xml");
/// The observed values of root style element `tag` (`ParagraphStyle`,
@@ -106,12 +127,9 @@ pub fn root_style(tag: &str, major: u32) -> Node {
tag: tag.to_string(),
..Node::default()
};
let root = parse(ROOT_VALUES).expect("root_values.xml is well-formed");
let root = embedded(ROOT_VALUES);
for block in &root.children {
let since = block
.attr("MinimumVersion")
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
if since <= major
if applies(block, major)
&& let Some(n) = block.child(tag)
{
out.merge(n);
@@ -131,14 +149,9 @@ pub fn object_style(major: u32) -> Node {
};
// Parsed once: the converter asks for these values for every page item.
static PARSED: std::sync::OnceLock<Node> = std::sync::OnceLock::new();
let root = PARSED.get_or_init(|| {
parse(OBJECT_STYLE_VALUES).expect("object_style_values.xml is well-formed")
});
let root = PARSED.get_or_init(|| embedded(OBJECT_STYLE_VALUES));
for block in &root.children {
let since = block
.attr("MinimumVersion")
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
if since <= major
if applies(block, major)
&& let Some(n) = block.child("ObjectStyle")
{
out.merge(n);
@@ -152,13 +165,10 @@ const PREFERENCE_VALUES: &str = include_str!("preference_values.xml");
/// The observed preference elements (`TextDefault`, ...) for a document of
/// InDesign version `major`, in the order the IDML files list them.
pub fn preferences(major: u32) -> Vec<Node> {
let root = parse(PREFERENCE_VALUES).expect("preference_values.xml is well-formed");
let root = embedded(PREFERENCE_VALUES);
let mut out: Vec<Node> = Vec::new();
for block in &root.children {
let since = block
.attr("MinimumVersion")
.map_or(0, |v| v.parse().expect("MinimumVersion is a number"));
if since > major {
if !applies(block, major) {
continue;
}
for n in &block.children {
@@ -175,19 +185,7 @@ const ELEMENT_VALUES: &str = include_str!("element_values.xml");
fn element_values() -> &'static Node {
static PARSED: std::sync::OnceLock<Node> = std::sync::OnceLock::new();
PARSED.get_or_init(|| parse(ELEMENT_VALUES).expect("element_values.xml is well-formed"))
}
/// Whether a block of `element_values.xml` applies to InDesign version
/// `major`.
fn applies(block: &Node, major: u32) -> bool {
let bound = |name: &str| {
block
.attr(name)
.map(|v| v.parse::<u32>().expect("version bounds are numbers"))
};
bound("MinimumVersion").is_none_or(|v| v <= major)
&& bound("MaximumVersion").is_none_or(|v| major <= v)
PARSED.get_or_init(|| embedded(ELEMENT_VALUES))
}
/// The observed values of the elements on `path` (a tag, or a tag and a
@@ -390,6 +388,26 @@ fn parse(s: &str) -> Option<Node> {
mod tests {
use super::*;
#[test]
fn embedded_files_parse() {
for (name, text) in [
("root_values.xml", ROOT_VALUES),
("object_style_values.xml", OBJECT_STYLE_VALUES),
("preference_values.xml", PREFERENCE_VALUES),
("element_values.xml", ELEMENT_VALUES),
] {
let root = parse(text).unwrap_or_else(|| panic!("{name} does not parse"));
assert!(!root.children.is_empty(), "{name} has no blocks");
for block in &root.children {
for bound in ["MinimumVersion", "MaximumVersion"] {
if let Some(v) = block.attr(bound) {
assert!(v.parse::<u32>().is_ok(), "{name}: {bound}=\"{v}\"");
}
}
}
}
}
#[test]
fn unescapes_numeric_references() {
assert_eq!(unescape("a&#9;b&#x3000;&amp;lt;&x"), "a\tb\u{3000}&lt;&x");
+9 -1
View File
@@ -186,8 +186,16 @@ impl Xml {
self
}
/// Close the current element. Every `end` follows its `start` in the
/// writer's code, whatever the input; an `end` with no open element
/// is a writer bug, fails a debug assertion, and writes nothing in a
/// release build.
pub fn end(&mut self) -> &mut Self {
let name = self.stack.pop().expect("end without start");
debug_assert!(!self.stack.is_empty(), "end without start");
let Some(name) = self.stack.pop() else {
return self;
};
if self.open {
self.flush_attrs();
self.out.push_str(" />");
+16
View File
@@ -29,7 +29,23 @@
//! that inspect files: [`Header`], [`Container`], [`Database`], [`Object`]
//! and the [`model`].
#![forbid(unsafe_code)]
// Malformed input gives an error or a warning, never a panic. Unit tests
// may unwrap and panic.
#![cfg_attr(
not(test),
deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unimplemented,
clippy::todo,
clippy::unreachable
)
)]
pub mod audit;
pub mod container;
pub mod database;
pub mod header;
+14
View File
@@ -2,7 +2,21 @@
//! inside an INDD file (header, objects, chunks, XMP, audit). Run it
//! without arguments for the list of subcommands.
#![forbid(unsafe_code)]
#![cfg_attr(
not(test),
deny(
clippy::unwrap_used,
clippy::expect_used,
clippy::panic,
clippy::unimplemented,
clippy::todo,
clippy::unreachable
)
)]
use std::io::Write;
use std::process::ExitCode;
const USAGE: &str = "usage:
+28 -25
View File
@@ -270,8 +270,9 @@ impl Attrs {
match (i, &first) {
(0, _) => first = Some(decode(enc, id, t, data)),
(1, Some(Value::Ref(r))) if t == ty::CODE && len == 4 => {
let code = enc.u32_from(data.try_into().unwrap());
first = Some(Value::RefOrCode(*r, code));
if let Some(code) = enc.u32_at(data, 0) {
first = Some(Value::RefOrCode(*r, code));
}
}
_ => {}
}
@@ -333,12 +334,13 @@ fn text_layout(id: u32) -> Option<Layout> {
/// fit it); the others are numbers of 8, 4 or 2 bytes.
fn decode_text(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
let Some(layout) = text_layout(id) else {
return match data.len() {
8 => Value::Double(enc.f64_from(data.try_into().unwrap())),
4 => Value::Ref(enc.u32_from(data.try_into().unwrap())),
2 => Value::Enum(enc.u16_from(data.try_into().unwrap())),
_ => Value::Other(t, data.to_vec()),
let number = match data.len() {
8 => enc.f64_at(data, 0).map(Value::Double),
4 => enc.u32_at(data, 0).map(Value::Ref),
2 => enc.u16_at(data, 0).map(Value::Enum),
_ => None,
};
return number.unwrap_or_else(|| Value::Other(t, data.to_vec()));
};
let mut c = enc.cursor(data);
let value = match layout {
@@ -432,31 +434,32 @@ fn nested_styles(c: &mut Cursor) -> Option<Vec<NestedStyle>> {
pub const OPACITY_STOPS: [u32; 3] = [0x1EB8C, 0x1EB95, 0x1EB9E];
fn decode(enc: Encoding, id: u32, t: u32, data: &[u8]) -> Value {
let f = |o: usize| enc.f64_from(data[o..o + 8].try_into().unwrap());
let f = |o: usize| enc.f64_at(data, o);
if OPACITY_STOPS.contains(&id)
&& let Some(n) = data
.get(..4)
.map(|b| enc.u32_from(b.try_into().unwrap()) as usize)
&& let Some(n) = enc.u32_at(data, 0).map(|n| n as usize)
&& n > 0
&& data.len() == 4 + n * 24
&& let Some(stops) = (0..n)
.map(|i| {
let at = |k: usize| f(4 + (3 * i + k) * 8);
Some([at(0)?, at(1)?, at(2)?])
})
.collect::<Option<Vec<_>>>()
{
return Value::Stops(
(0..n)
.map(|i| [0, 1, 2].map(|k| f(4 + (3 * i + k) * 8)))
.collect(),
);
return Value::Stops(stops);
}
match (t, data.len()) {
(ty::DOUBLE, 8) => Value::Double(f(0)),
(ty::INT, 4) => Value::Int(enc.i32_from(data.try_into().unwrap())),
(ty::ENUM, 2) => Value::Enum(enc.u16_from(data.try_into().unwrap())),
(ty::REF, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())),
(ty::POINT, 16) => Value::Point(f(0), f(8)),
let value = match (t, data.len()) {
(ty::DOUBLE, 8) => f(0).map(Value::Double),
(ty::INT, 4) => enc.i32_at(data, 0).map(Value::Int),
(ty::ENUM, 2) => enc.u16_at(data, 0).map(Value::Enum),
(ty::REF, 4) => enc.u32_at(data, 0).map(Value::Ref),
(ty::POINT, 16) => f(0).zip(f(8)).map(|(x, y)| Value::Point(x, y)),
// Other 4-byte types are references or codes (for example a
// corner effect ID); keep the number.
(_, 4) => Value::Ref(enc.u32_from(data.try_into().unwrap())),
_ => Value::Other(t, data.to_vec()),
}
(_, 4) => enc.u32_at(data, 0).map(Value::Ref),
_ => None,
};
value.unwrap_or_else(|| Value::Other(t, data.to_vec()))
}
#[cfg(test)]
+1 -2
View File
@@ -279,9 +279,8 @@ impl<'a> Reader<'a> {
}
if self.class(strand) == Some(hyperlink::class::RANGE_STRAND)
&& let Some(tree) = self.chunk(strand, hyperlink::chunk::RANGE_TREE)?
&& tree.len() >= 4
&& let Some(first) = self.enc().u32_at(&tree, 0)
{
let first = self.enc().u32_from(tree[..4].try_into().unwrap());
let pages = |uid| self.chunk(uid, hyperlink::chunk::RANGE_PAGE);
match hyperlink::source_ranges(self.enc(), first, pages) {
Ok(r) => sources.extend(r),
+2 -1
View File
@@ -80,7 +80,8 @@ fn parse(enc: Encoding, uid: u32, data: &[u8]) -> Result<TextVariable, Error> {
}
0xCAC0 => enc.u32_at(rest, 0) == Some(0x8C64) && zero(&rest[4..]),
0xCAAA => {
style = Some(enc.u32_from(rest[4..8].try_into().unwrap()));
style = enc.u32_at(rest, 4);
zero(&rest[..4]) && zero(&rest[8..])
}
_ => zero(rest) && text.is_empty(),
+17 -6
View File
@@ -94,8 +94,8 @@ impl Encoding {
let mut pos = 0;
while pos < bytes.len() {
let head = bytes.get(pos..pos + 8)?;
let id = self.u32_from(head[..4].try_into().unwrap());
let len = self.u32_from(head[4..].try_into().unwrap()) as usize;
let id = self.u32_at(head, 0)?;
let len = self.u32_at(head, 4)? as usize;
let data = bytes.get(pos + 8..(pos + 8).checked_add(len)?)?;
out.push(Chunk { id, data });
pos += 8 + len;
@@ -214,6 +214,17 @@ impl<'a> Cursor<'a> {
Ok(out)
}
/// The next `N` bytes, as an array.
fn array<const N: usize>(&mut self) -> Result<[u8; N], Error> {
let out = *self
.data
.get(self.pos..)
.and_then(<[u8]>::first_chunk)
.ok_or_else(|| short("bytes", self.pos))?;
self.pos += N;
Ok(out)
}
pub fn skip(&mut self, n: usize) -> Result<(), Error> {
self.bytes(n).map(|_| ())
}
@@ -223,19 +234,19 @@ impl<'a> Cursor<'a> {
}
pub fn u16(&mut self) -> Result<u16, Error> {
Ok(self.enc.u16_from(self.bytes(2)?.try_into().unwrap()))
Ok(self.enc.u16_from(self.array()?))
}
pub fn u32(&mut self) -> Result<u32, Error> {
Ok(self.enc.u32_from(self.bytes(4)?.try_into().unwrap()))
Ok(self.enc.u32_from(self.array()?))
}
pub fn i32(&mut self) -> Result<i32, Error> {
Ok(self.enc.i32_from(self.bytes(4)?.try_into().unwrap()))
Ok(self.enc.i32_from(self.array()?))
}
pub fn f64(&mut self) -> Result<f64, Error> {
Ok(self.enc.f64_from(self.bytes(8)?.try_into().unwrap()))
Ok(self.enc.f64_from(self.array()?))
}
/// A u32 count followed by that many u32 values.