Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(fonts): a composite /W run past the last CID stops there (#1313) (#1389)

Marco Arnulfoaf1c997affde
diff --git a/crates/fonts/src/pdf.rs b/crates/fonts/src/pdf.rs
index c418a03b8..5b471c55d 100644
--- a/crates/fonts/src/pdf.rs
+++ b/crates/fonts/src/pdf.rs
@@ -598,8 +598,10 @@ impl Metrics {
match w.get(i + 1).map(|o| doc.resolve(o)) {
Some(a) if a.as_array().is_some() => {
for (k, x) in a.as_array().into_iter().flatten().enumerate() {
+ // A run past the last CID ends there: wrapping would give CID 0 its width.
+ let Some(cid) = u32::try_from(k).ok().and_then(|k| c0.checked_add(k)) else { break };
if let Some(v) = doc.resolve(x).as_f64() {
- m.cid_widths.insert(c0 + k as u32, v);
+ m.cid_widths.insert(cid, v);
}
}
i += 2;
@@ -1255,6 +1257,31 @@ mod tests {
assert_eq!(m.encode("Z"), None);
}
+ /// A `/W` run that starts at the last CID stops there instead of overflowing onto CID 0.
+ #[test]
+ fn composite_width_run_past_the_last_cid_is_dropped() {
+ let widths = |first: i64| {
+ let mut doc = Document::new_empty();
+ let mut desc = Dict::new();
+ desc.set(b"Subtype".to_vec(), Object::name("CIDFontType2"));
+ desc.set(b"DW".to_vec(), Object::Int(1000));
+ desc.set(b"W".to_vec(), Object::Array(vec![Object::Int(first), Object::Array(vec![Object::Int(100), Object::Int(200)])]));
+ let f = font(
+ &mut doc,
+ vec![
+ ("Subtype", Object::name("Type0")),
+ ("Encoding", Object::name("Identity-H")),
+ ("DescendantFonts", Object::Array(vec![Object::Dict(desc)])),
+ ],
+ );
+ Metrics::from_dict(&doc, &f)
+ };
+ let ordinary = widths(0);
+ assert_eq!((ordinary.width(0), ordinary.width(1)), (0.1, 0.2));
+ let last = widths(i64::from(u32::MAX));
+ assert_eq!((last.width(0), last.width(u32::MAX)), (1.0, 0.1));
+ }
+
#[test]
fn glyph_names() {
assert_eq!(glyph_unicode("quotedblleft"), Some('“'));