From 1dde9e57e2b2a6a61c5c71b155e3be4d9724aed9 Mon Sep 17 00:00:00 2001 From: Noah Hellman Date: Wed, 18 Jan 2023 21:44:58 +0100 Subject: [PATCH] borrow link def url if on single line --- src/lib.rs | 9 ++++++--- src/tree.rs | 12 ++++++++++++ 2 files changed, 18 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index d3ed415..ce8dab0 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -268,7 +268,7 @@ pub struct Parser<'s> { tree: tree::Branch, inlines: span::InlineSpans<'s>, inline_parser: Option>>, - link_definitions: std::collections::HashMap<&'s str, String>, + link_definitions: std::collections::HashMap<&'s str, CowStr<'s>>, _tree_data: block::Tree, } @@ -286,8 +286,11 @@ impl<'s> Parser<'s> { e.kind { let tag = e.span.of(src); - // TODO borrow url string if single inline - let url = branch.take_inlines().map(|sp| sp.of(src).trim()).collect(); + let url = match branch.count_children() { + 0 => "".into(), + 1 => branch.take_inlines().next().unwrap().of(src).trim().into(), + _ => branch.take_inlines().map(|sp| sp.of(src).trim()).collect(), + }; defs.insert(tag, url); } } diff --git a/src/tree.rs b/src/tree.rs index eb53b4e..3f51897 100644 --- a/src/tree.rs +++ b/src/tree.rs @@ -50,6 +50,18 @@ pub struct Branch { } impl Branch { + /// Count number of direct children nodes. + pub fn count_children(&self) -> usize { + let mut head = self.head; + let mut count = 0; + while let Some(h) = head { + let n = &self.nodes[h.index()]; + head = n.next; + count += 1; + } + count + } + /// Retrieve all inlines until the end of the current container. Panics if any upcoming node is /// not an inline node. pub fn take_inlines(&mut self) -> impl Iterator + '_ {