Skip to content

Find offset of link in broken link callback #165

@euclio

Description

@euclio

I'd like to be able to distinguish the location of two broken links with the same text.

In rustdoc, we attempt to do this with a callback not unlike the test case below, where we compare the offsets of the pointer of the non-normalized reference and the markdown pointer itself:

#[test]
fn test_duplicate_broken_links() {
    use ::{Parser, Options};

    let links = RefCell::new(vec![]);

    let md = "[link] [link]";

    let locate = |s: &str| unsafe {
        let s_start = s.as_ptr();
        let s_end = s_start.add(s.len());
        let md_start = md.as_ptr();
        let start = s_start as usize - md_start as usize;
        let end = s_end as usize - md_start as usize;
        start..end
    };

    {
        let callback = |_: &str, s: &str| {
            links.borrow_mut().push((s.to_owned(), locate(s)));
            None
        };

        let p = Parser::new_with_broken_link_callback(md, Options::empty(), Some(&callback));
        for _ in p {}
    }

    assert_eq!(links.into_inner(), vec![
        (String::from("link"), 1..5),
        (String::from("link"), 8..12),
    ]);
}

In addition to being unsafe, it doesn't appear to actually work!

---- parse::tests::test_duplicate_broken_links stdout ----
thread 'parse::tests::test_duplicate_broken_links' panicked at 'assertion failed: `(left == right)`
  left: `[("link", 8..12), ("link", 8..12)]`,
 right: `[("link", 1..5), ("link", 8..12)]`', src/parse.rs:1829:9

While it would be nice to fix this bug, I think it would less error prone if the callback was passed the location of the current broken link, perhaps as a byte range?

Metadata

Metadata

Assignees

Labels

No labels
No labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions