PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust
fix(annot): count web-address text after its UTF-8 conversion
aiongg02f0f7396f6b
diff --git a/crates/annot/src/links.rs b/crates/annot/src/links.rsindex b6a2c7575..657488137 100644--- a/crates/annot/src/links.rs+++ b/crates/annot/src/links.rs@@ -78,7 +78,8 @@ pub struct LinkItem {pub style: LinkStyle,}-/// Web-address text one listing keeps; past it a link lists as [`LinkAction::Other`].+/// Bytes of web-address text one listing keeps, counted after conversion to UTF-8; past it a link+/// lists as [`LinkAction::Other`].pub(crate) const MAX_URI_BYTES: usize = 16 << 20;fn nums(doc: &Document, o: Option<&Object>) -> Vec<f64> {@@ -103,10 +104,13 @@ fn action_of(doc: &Document, d: &Dict, pages: &[ObjRef], uri_budget: &mut usize)Some(b"URI") => {let uri = a.get(b"URI").map(|u| doc.resolve(u));let bytes = uri.as_ref().and_then(|u| u.as_string()).map_or(&[][..], |s| &s.bytes[..]);- match uri_budget.checked_sub(bytes.len()) {- Some(left) => {+ // The raw length first, so an address already over the budget is never converted; then the+ // converted text, which is up to three times longer where the bytes are not UTF-8.+ let text = (bytes.len() <= *uri_budget).then(|| String::from_utf8_lossy(bytes));+ match text.and_then(|t| Some((uri_budget.checked_sub(t.len())?, t))) {+ Some((left, text)) => {*uri_budget = left;- LinkAction::Uri(String::from_utf8_lossy(bytes).into_owned())+ LinkAction::Uri(text.into_owned())}None => LinkAction::Other("web address too long".into()),}diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rsindex c52732ea8..6eb94b830 100644--- a/crates/annot/src/tests.rs+++ b/crates/annot/src/tests.rs@@ -1541,6 +1541,25 @@ fn link_listing_skips_repeated_refs_and_caps_web_address_text() {assert!(matches!(&all[0].action, links::LinkAction::Uri(u) if u.len() == 64 << 10));}+#[test]+fn web_address_cap_counts_the_text_kept_after_conversion() {+ // 200 links sharing a 64 KiB address of invalid UTF-8: 12.5 MiB of bytes, each byte kept as a+ // three-byte replacement character.+ let annots = "<< /Subtype /Link /Rect [0 0 1 1] /A 4 0 R >>".repeat(200);+ let doc = doc_of(&[+ "<< /Type /Catalog /Pages 2 0 R >>".into(),+ "<< /Type /Pages /Kids [3 0 R] /Count 1 /MediaBox [0 0 612 792] >>".into(),+ format!("<< /Type /Page /Parent 2 0 R /Annots [{annots}] >>"),+ "<< /S /URI /URI 5 0 R >>".into(),+ format!("<{}>", "FF".repeat(64 << 10)),+ ]);+ let all = links::list(&doc);+ assert_eq!(all.len(), 200);+ let kept: usize = all.iter().map(|l| if let links::LinkAction::Uri(u) = &l.action { u.len() } else { 0 }).sum();+ assert!(kept <= links::MAX_URI_BYTES, "{kept} bytes of web addresses kept");+ assert!(kept > 0);+}+#[test]fn cloud_outline_has_a_bump_budget() {// 50 long edges would each ask for 10,000 bumps of radius 1.