Skip to content

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

fix(annot): check a whole link batch before creating any link object

aiongg6394779b81f7
diff --git a/crates/annot/src/links.rs b/crates/annot/src/links.rs
index f11eecbd8..95d408058 100644
--- a/crates/annot/src/links.rs
+++ b/crates/annot/src/links.rs
@@ -420,6 +420,16 @@ pub fn find_urls(chars: &[char]) -> Vec<(std::ops::Range<usize>, String)> {
/// line rectangle). Returns how many links were added.
pub fn add_many(doc: &mut Document, links: &[(usize, Vec<[f64; 4]>, String)], style: &LinkStyle) -> Result<usize, AnnotError> {
let pages = page_refs(doc)?;
+ // Check the whole batch first, so a bad entry fails it before any link object is created.
+ for (page, rects, uri) in links {
+ pages.get(*page).ok_or(AnnotError::NoSuchPage(*page))?;
+ if uri.trim().is_empty() {
+ return Err(AnnotError::Invalid("type the web address first".into()));
+ }
+ for r in rects {
+ checked_rect(*r)?;
+ }
+ }
// Each page's `/Annots` is extended once, with its new links in the order given.
let mut added: Vec<(ObjRef, Vec<Object>)> = Vec::new();
let mut slot: std::collections::HashMap<ObjRef, usize> = std::collections::HashMap::new();
diff --git a/crates/annot/src/tests.rs b/crates/annot/src/tests.rs
index cfd80093e..017e06671 100644
--- a/crates/annot/src/tests.rs
+++ b/crates/annot/src/tests.rs
@@ -1541,3 +1541,21 @@ fn many_links_extend_a_page_annotation_list_once() {
assert_eq!(annots(&doc, page_refs(&doc).unwrap()[0]).len(), before + n);
assert!(copied <= 4 * n, "{copied} annotation entries copied for {n} links");
}
+
+/// A batch with one bad entry adds nothing: no link objects are left behind unattached.
+#[test]
+fn a_link_batch_with_a_bad_entry_creates_no_objects() {
+ let mut doc = fixture();
+ let page = page_refs(&doc).unwrap()[0];
+ let before = (annots(&doc, page).len(), doc.scan_objects().count());
+ let good = [10.0, 10.0, 50.0, 20.0];
+ let style = links::LinkStyle::default();
+ for bad in [
+ vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good, [f64::NAN, 0.0, 10.0, 10.0]], "https://example.com".into())],
+ vec![(0, vec![good], "https://example.com".to_string()), (0, vec![good], " ".into())],
+ vec![(0, vec![good], "https://example.com".to_string()), (99, vec![good], "https://example.com".into())],
+ ] {
+ assert!(links::add_many(&mut doc, &bad, &style).is_err());
+ assert_eq!((annots(&doc, page).len(), doc.scan_objects().count()), before);
+ }
+}