roll

Rolled my own static website builder 💻

Commit
6ba72f271562b2edbe8da9c78720969ea07b2c56
Parent
0ea2572f450fda0892ffa4133d2398ab3814f782
Author
Pablo <pablo-pie@riseup.net>
Date

Optimized temporary allocations

Made it so that temporary strings are re-used throughout Markdown rendering, avoiding re-allocations

Lists of temporary strings are now stored in an arena-like structure that re-uses the allocated space whenever possible

Diffstats

4 files changed, 558 insertions, 482 deletions

Status Name Changes Insertions Deletions
Modified exemple/posts/a-post.md 2 files changed 7 27
Modified src/html.rs 2 files changed 464 454
Modified src/main.rs 2 files changed 2 1
Added src/string_store.rs 1 file changed 85 0
diff --git a/exemple/posts/a-post.md b/exemple/posts/a-post.md
@@ -26,31 +26,11 @@ arcu. Fusce massa quam, condimentum eu odio nec, malesuada porta elit.
 Curabitur mollis interdum blandit. Duis eu lacus tincidunt, malesuada est sit
 amet, tincidunt nisi.
 
-Ut fringilla bibendum dolor, id dapibus lorem venenatis in. Maecenas accumsan
-ipsum eu maximus posuere. Donec mollis sit amet ligula et aliquet. Vestibulum
-iaculis est sed elit dapibus, vel efficitur lorem pulvinar. Sed sodales, diam
-eget facilisis consequat, lorem massa euismod mauris, sagittis gravida mauris
-justo at risus. Aenean nec tristique elit, quis aliquet elit. Nunc aliquet
-ultrices viverra. Phasellus sed gravida mauris, nec consequat enim. Etiam
-dictum quam id facilisis venenatis. Curabitur fringilla, est sit amet porta
-malesuada, velit felis pretium enim, euismod gravida urna lacus eget nibh.
+Some code:
 
-Sed ullamcorper efficitur odio at fringilla. Integer eget viverra eros, et
-cursus lorem. Fusce mattis pulvinar eros, a ultrices mi semper eget. Duis
-luctus cursus metus, sed consectetur dolor dignissim in. Sed a lectus cursus,
-tincidunt diam at, ornare nisi. Etiam vestibulum purus quis dolor efficitur
-tristique. Aliquam non eleifend purus, ut convallis ligula.
-
-Maecenas et semper sapien, ac molestie velit. Phasellus vulputate, lorem in
-consectetur pharetra, felis magna lacinia nisl, non facilisis erat est at nisl.
-Praesent mattis sapien in vestibulum tempus. Pellentesque convallis erat nunc,
-at porttitor lectus pellentesque in. Nunc felis ex, convallis vel diam non,
-accumsan faucibus urna. Praesent sit amet dignissim lectus, ut facilisis dolor.
-Donec et neque tristique, consequat felis nec, malesuada nisi. Etiam ac
-sollicitudin tellus. Duis pharetra rutrum odio ac venenatis. Nulla blandit,
-orci eget finibus interdum, risus lectus finibus enim, vel euismod massa velit
-sit amet massa. Cras congue rhoncus velit, sed vehicula sem sodales sed. Nunc
-egestas rhoncus nunc, sit amet consequat augue venenatis et. Nulla at nulla
-finibus, elementum dui in, imperdiet massa. Nullam porta congue pellentesque.
-Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere
-cubilia curae; Donec vel bibendum tortor, eu ornare ex.
+```c
+size_t factorial(size_t n) {
+  if (n == 0) return 1;
+  return n * factorial(n-1);
+}
+```
diff --git a/src/html.rs b/src/html.rs
@@ -3,7 +3,7 @@ use std::{
   fmt::{self, Display},
   iter::Peekable,
   collections::HashMap,
-  cell::{RefCell, LazyCell},
+  cell::LazyCell,
 };
 
 use pulldown_cmark::{
@@ -26,14 +26,30 @@ use crate::{
   Page,
   Date,
   PostInfo,
+  string_store::StringStore,
 };
 
 use crate::config::*;
 
 #[derive(Debug)]
 pub struct Renderer {
-  buff:       RefCell<Vec<u8>>,
+  buff:       Vec<u8>,
   syntax_set: LazyCell<SyntaxSet>,
+
+  head_info:     HeadInfo,
+  in_table_head: bool,
+  tmp_str:       String,
+}
+
+#[derive(Debug, Default)]
+struct HeadInfo {
+  needs_katex:        bool,
+  needs_highlighting: bool,
+
+  preload_imgs: StringStore,
+  script_tags:  StringStore,
+  style_tags:   StringStore,
+  link_tags:    StringStore,
 }
 
 /// Wrapper for displaying a date in the "%Y-%m-%d" format
@@ -44,15 +60,15 @@ struct RssDateTime(Date);
 
 impl Renderer {
   pub fn render_post<W: Write>(
-    &self,
+    &mut self,
     w:          &mut W,
     post:       &Post,
     post_index: &HashMap<String, PostInfo>,
   ) -> io::Result<()> {
-    self.render_md_page(
+    self.render_md_document(
       w,
-      &post.info.title,
       &post.contents,
+      &post.info.title,
       Some(&post.info.excerpt),
       Some(post.info.date),
       post_index,
@@ -60,24 +76,64 @@ impl Renderer {
   }
 
   pub fn render_page<W: Write>(
-    &self,
+    &mut self,
     w:          &mut W,
     page:       &Page,
     post_index: &HashMap<String, PostInfo>,
   ) -> io::Result<()> {
-    self.render_md_page(w, &page.title, &page.contents, None, None, post_index)
+    self.render_md_document(
+      w,
+      &page.contents,
+      &page.title,
+      None,
+      None,
+      post_index,
+    )
   }
 
   #[allow(clippy::too_many_arguments)]
-  fn render_md_page<W: Write>(
-    &self,
+  /// Generic adapter for rendering MD into HTML
+  fn render_md_document<W: Write>(
+    &mut self,
     w:           &mut W,
-    title:       &str,
     contents:    &str,
+    title:       &str,
     description: Option<&str>,
     date:        Option<Date>,
     post_index:  &HashMap<String, PostInfo>,
   ) -> io::Result<()> {
+    self.buff.clear();
+    self.render_md_body_and_collect_head_info(contents, post_index)?;
+
+    render_copyright(w)?;
+    writeln!(w, "<!DOCTYPE html>")?;
+    writeln!(w, "<html lang=\"en\">")?;
+    render_head(w, title, description, Some(&self.head_info))?;
+    writeln!(w, "<body>")?;
+    render_nav(w)?;
+    writeln!(w, "<main>")?;
+    writeln!(w, "<h1>{}</h1>", Escaped(title))?;
+    if let Some(date) = date {
+      writeln!(w, "<time datetime=\"{}\">{}</time>", DateTime(date), date)?;
+    }
+    w.write_all(&self.buff)?;
+    writeln!(w, "</main>")?;
+    render_footer(w)?;
+    writeln!(w, "</body>")?;
+    writeln!(w, "</html>")?;
+
+    Ok(())
+  }
+
+  // Addapted from pulldown_cmark/html.rs
+  // <https://github.com/pulldown-cmark/pulldown-cmark/>
+  /// Renders the body of the MD document to HTML into [`self.buff`],
+  /// collecting data into [`self.head_info`] along the way
+  fn render_md_body_and_collect_head_info(
+    &mut self,
+    contents: &str,
+    post_index: &HashMap<String, PostInfo>,
+  ) -> io::Result<()> {
     let mut opt = Options::empty();
     opt.insert(Options::ENABLE_TABLES);
     opt.insert(Options::ENABLE_STRIKETHROUGH);
@@ -90,34 +146,392 @@ impl Renderer {
     opt.insert(Options::ENABLE_WIKILINKS);
 
     let mut p = Parser::new_ext(contents, opt).peekable();
+    self.head_info.needs_katex        = false;
+    self.head_info.needs_highlighting = false;
+    self.head_info.preload_imgs.clear();
+    self.head_info.script_tags.clear();
+    self.head_info.style_tags.clear();
+    self.head_info.link_tags.clear();
 
     // ========================================================================
-    let head_info = {
-      let mut buff = self.buff.borrow_mut();
-      buff.clear();
-      render_md_to_html(&mut *buff, post_index, &self.syntax_set, &mut p)?
-    };
+    self.in_table_head = true;
+
+    while let Some(event) = p.next() {
+      match event {
+        Event::Start(tag) => {
+          self.start_tag(
+            tag,
+            post_index,
+            &mut p,
+          )?
+        }
+        Event::End(tag)   => self.end_tag(tag)?,
+        Event::Text(text) => write!(&mut self.buff, "{}", Escaped(&text))?,
+        Event::Code(text) => {
+          write!(&mut self.buff, "<code>{}</code>", Escaped(&text))?;
+        }
+        Event::InlineMath(math) => {
+          self.head_info.needs_katex = true;
+          katex::render_inline(&mut self.buff, &math)?;
+        }
+        Event::DisplayMath(math) => {
+          self.head_info.needs_katex = true;
+          writeln!(&mut self.buff, "<figure class=\"equation\">")?;
+          katex::render_display(&mut self.buff, &math)?;
+          writeln!(&mut self.buff, "</figure>")?;
+        }
+        Event::SoftBreak => writeln!(&mut self.buff)?,
+        Event::HardBreak => writeln!(&mut self.buff, "<br/>")?,
+        Event::Rule      => writeln!(&mut self.buff, "<hr/>")?,
+        Event::InlineHtml(html) | Event::Html(html) => {
+          write!(&mut self.buff, "{html}")?
+        }
+        Event::TaskListMarker(_) => {
+          unreachable!("task lists are not supported");
+        }
+        Event::FootnoteReference(_) => {
+          unreachable!("footnotes are not supported");
+        }
+      }
+    }
+    Ok(())
+  }
 
-    // ========================================================================
-    render_copyright(w)?;
-    writeln!(w, "<!DOCTYPE html>")?;
-    writeln!(w, "<html lang=\"en\">")?;
-    render_head(w, title, description, &head_info)?;
-    writeln!(w, "<body>")?;
-    render_nav(w)?;
-    writeln!(w, "<main>")?;
-    writeln!(w, "<h1>{}</h1>", Escaped(title))?;
-    if let Some(date) = date {
-      writeln!(w, "<time datetime=\"{}\">{}</time>", DateTime(date), date)?;
+  // Addapted from pulldown_cmark/html.rs
+  // <https://github.com/pulldown-cmark/pulldown-cmark/>
+  fn start_tag<'h>(
+    &mut self,
+    tag:        Tag<'h>,
+    post_index: &HashMap<String, PostInfo>,
+    p:          &mut Peekable<Parser<'h>>,
+  ) -> io::Result<()> {
+    match tag {
+      Tag::HtmlBlock => {
+        // TODO(2): simplify this?
+        //          we could try to fork the parser and tuck some of this
+        //          complexity inside of it
+        while let Some(Event::Text(text)) = p.peek() {
+          write!(&mut self.buff, "{}", Escaped(text))?;
+          p.next();
+        }
+        let first_line = match p.next() {
+          Some(Event::Html(line)) => line,
+          None | Some(Event::End(TagEnd::HtmlBlock)) => return Ok(()),
+          Some(e) => {
+            unreachable!("should not get event {e:?} in the middle of an HTML block");
+          }
+        };
+
+        #[derive(Debug, Clone, Copy)]
+        enum Kind {
+          Script,
+          Style,
+          Link,
+        }
+
+        let kind = if first_line.starts_with("<script") {
+          Kind::Script
+        } else if first_line.starts_with("<style") {
+            Kind::Style
+        } else if first_line.starts_with("<link") {
+          Kind::Link
+        } else {
+          write!(&mut self.buff, "{}", first_line)?;
+          return Ok(());
+        };
+
+        self.tmp_str.clear();
+        self.tmp_str.push_str(&first_line);
+        for e in p {
+          match e {
+            Event::End(TagEnd::HtmlBlock)         => break,
+            Event::Text(line) | Event::Html(line) => {
+              self.tmp_str.push_str(&line);
+            }
+            e => {
+              unreachable!("should not get event {e:?} in the middle of HTML block");
+            }
+          }
+        }
+
+        match kind {
+          Kind::Script => {
+            let script = self.head_info.script_tags.alloc();
+
+            if let Some((start, _)) = self.tmp_str.rsplit_once("</script") {
+              script.push_str(start);
+            } else {
+              script.push_str(&self.tmp_str);
+            }
+            script.push_str("</script>");
+          }
+          Kind::Style => {
+            let style = self.head_info.style_tags.alloc();
+            if let Some((start, _)) = self.tmp_str.rsplit_once("</style") {
+              style.push_str(start);
+            } else {
+              style.push_str(&self.tmp_str);
+            }
+            style.push_str("</style>");
+          }
+          Kind::Link => {
+            let link = self.head_info.link_tags.alloc();
+            if let Some((start, _)) = self.tmp_str.split_once(">") {
+              link.push_str(start);
+            } else {
+              link.push_str(&self.tmp_str);
+            }
+            link.push('>');
+          }
+        };
+      }
+      Tag::Paragraph => {
+        // horrible hack to wrap block images with <figure>
+        if !matches!(p.peek(), Some(Event::Start(Tag::Image { .. }))) {
+          writeln!(&mut self.buff, "<p>")?;
+          return Ok(());
+        }
+
+        let (dest_url, caption) = match p.next() {
+          Some(Event::Start(Tag::Image { dest_url, title: caption, .. })) => {
+            (dest_url, caption)
+          }
+          _ => unreachable!(),
+        };
+
+        writeln!(&mut self.buff, "<figure>")?;
+        self.process_image(p, dest_url)?;
+        if !caption.is_empty() {
+          writeln!(&mut self.buff, "<figcaption>")?;
+          writeln!(&mut self.buff, "{}", Escaped(&caption))?;
+          writeln!(&mut self.buff, "</figcaption>")?;
+        }
+        writeln!(&mut self.buff, "</figure>")?;
+
+        assert_eq!(p.next(), Some(Event::End(TagEnd::Paragraph)));
+      }
+      Tag::Heading { level, .. } => write!(&mut self.buff, "<{level}>")?,
+      Tag::Subscript             => write!(&mut self.buff, "<sub>")?,
+      Tag::Superscript           => write!(&mut self.buff, "<sup>")?,
+      Tag::Table(_alignments)    => write!(&mut self.buff, "<table>")?,
+      Tag::TableHead => {
+        self.in_table_head = true;
+        write!(&mut self.buff, "<thead><tr>")?;
+      }
+      Tag::TableRow => write!(&mut self.buff, "<tr>")?,
+      Tag::TableCell => if self.in_table_head {
+        write!(&mut self.buff, "<th>")?;
+      } else {
+        write!(&mut self.buff, "<td>")?;
+      },
+      Tag::CodeBlock(block_kind) => {
+        use syntect::{
+          html::{ClassedHTMLGenerator, ClassStyle},
+          util::LinesWithEndings,
+        };
+
+        self.head_info.needs_highlighting = true;
+
+        self.tmp_str.clear();
+        for event in p {
+          match event {
+            Event::Text(text)             => self.tmp_str.push_str(&text),
+            Event::SoftBreak              => {},
+            Event::End(TagEnd::CodeBlock) => break,
+            _ => unreachable!("should not get {event:?} inside of code block"),
+          }
+        }
+
+        fn get_highlighted_code(
+          code:       &str,
+          block_kind: CodeBlockKind,
+          syntax_set: &LazyCell<SyntaxSet>,
+        ) -> Option<String> {
+          let lang = if let CodeBlockKind::Fenced(lang) = block_kind {
+            lang
+          } else {
+            return None;
+          };
+          if lang.is_empty() { return None; }
+
+          if let Some(syntax_ref) = syntax_set.find_syntax_by_token(&lang) {
+            let mut html_gen = ClassedHTMLGenerator::new_with_class_style(
+              syntax_ref,
+              syntax_set,
+              ClassStyle::Spaced,
+            );
+
+            for line in LinesWithEndings::from(code) {
+              // TODO: warn the user somehow?
+              if html_gen
+                .parse_html_for_line_which_includes_newline(line)
+                .is_err() {
+                  return None;
+              }
+            }
+
+            Some(html_gen.finalize())
+          } else {
+            None
+          }
+        }
+
+        writeln!(&mut self.buff, "<div class=\"code-block\">")?;
+        if let Some(code_html) = get_highlighted_code(&self.tmp_str,
+                                                      block_kind,
+                                                      &self.syntax_set) {
+          writeln!(&mut self.buff, "<pre>{code_html}</pre>")?;
+        } else {
+          writeln!(&mut self.buff, "<pre>{}</pre>", self.tmp_str)?;
+        }
+        writeln!(&mut self.buff, "</div>")?;
+      }
+      Tag::BlockQuote(None) => writeln!(&mut self.buff, "<blockquote>")?,
+      Tag::BlockQuote(Some(kind)) => { // admonitions
+        let label = match kind {
+          BlockQuoteKind::Note      => "note",
+          BlockQuoteKind::Tip       => "tip",
+          BlockQuoteKind::Important => "important",
+          BlockQuoteKind::Warning   => "warning",
+          BlockQuoteKind::Caution   => "caution",
+        };
+
+        writeln!(&mut self.buff, "<div class=\"admonition\" aria-label=\"{label}\" role=\"note\">")?;
+        writeln!(&mut self.buff, "<div aria-hidden=\"true\">")?;
+        writeln!(&mut self.buff, "<img class=\"icon\" src=\"/{ICONS_SUBDIR}/{label}.svg\" width=\"20\" height=\"20\" alt=\"{label} icon\">")?;
+        writeln!(&mut self.buff, "</div>")?;
+        writeln!(&mut self.buff, "<div>")?;
+      }
+      Tag::List(Some(1))            => writeln!(&mut self.buff, "<ol>")?,
+      Tag::List(Some(start))        => writeln!(&mut self.buff, "<ol start=\"{start}\">")?,
+      Tag::List(None)               => writeln!(&mut self.buff, "<ul>")?,
+      Tag::Item                     => writeln!(&mut self.buff, "<li>")?,
+      Tag::DefinitionList           => writeln!(&mut self.buff, "<dl>")?,
+      Tag::DefinitionListTitle      => write!(&mut self.buff, "<dt>")?,
+      Tag::DefinitionListDefinition => write!(&mut self.buff, "<dd>")?,
+      Tag::Emphasis                 => write!(&mut self.buff, "<em>")?,
+      Tag::Strong                   => write!(&mut self.buff, "<strong>")?,
+      Tag::Strikethrough            => write!(&mut self.buff, "<del>")?,
+      Tag::Link { link_type: LinkType::Email, dest_url, .. } => {
+        write!(&mut self.buff, "<a href=\"mailto:{url}\">",
+                               url = Escaped(&dest_url))?;
+      }
+      Tag::Link { link_type: LinkType::WikiLink { .. }, dest_url, .. } => {
+        write!(&mut self.buff, "<a href=\"/{POSTS_SUBDIR}/{}.html\">",
+                               Escaped(&dest_url))?;
+        if let Some(PostInfo { title, .. }) = post_index
+          .get(&dest_url.to_string()) {
+          write!(&mut self.buff, "{title}")?;
+          // NOTE: the next event should cotain the content that goes inside the
+          //       link tag, which in this case is just the post tag we already
+          //       know from `dest_url` (API quirck?)
+          let _ = p.next();
+        }
+      }
+      Tag::Link { dest_url, .. } => {
+        write!(&mut self.buff, "<a href=\"{}\">", Escaped(&dest_url))?;
+      }
+      Tag::Image { dest_url, .. } => {
+        self.process_image(p, dest_url)?;
+      }
+      Tag::FootnoteDefinition(_) => {
+        unreachable!("footnotes are not supported");
+      }
+      Tag::MetadataBlock(_) => {
+        unreachable!("metadata blocks should be at the beginning");
+      }
     }
-    w.write_all(&self.buff.borrow())?;
-    writeln!(w, "</main>")?;
-    render_footer(w)?;
-    writeln!(w, "</body>")?;
-    writeln!(w, "</html>")?;
 
     Ok(())
   }
+
+  // Addapted from pulldown_cmark/html.rs
+  // <https://github.com/pulldown-cmark/pulldown-cmark/>
+  fn end_tag(&mut self, tag: TagEnd) -> io::Result<()> {
+    match tag {
+      TagEnd::HtmlBlock      => {}
+      TagEnd::Paragraph      => writeln!(&mut self.buff, "\n</p>")?,
+      TagEnd::Heading(level) => writeln!(&mut self.buff, "</{level}>")?,
+      TagEnd::Subscript      => write!(&mut self.buff, "</sub>")?,
+      TagEnd::Superscript    => write!(&mut self.buff, "</sup>")?,
+      TagEnd::Table => {
+        writeln!(&mut self.buff, "</tbody>")?;
+        writeln!(&mut self.buff, "</table>")?;
+      }
+      TagEnd::TableHead => {
+        writeln!(&mut self.buff, "</tr>")?;
+        writeln!(&mut self.buff, "</thead>")?;
+        writeln!(&mut self.buff, "<tbody>")?;
+        self.in_table_head = false;
+      }
+      TagEnd::TableRow => writeln!(&mut self.buff, "</tr>")?,
+      TagEnd::TableCell => if self.in_table_head {
+        write!(&mut self.buff, "</th>")?;
+      } else {
+        write!(&mut self.buff, "</td>")?;
+      },
+      TagEnd::CodeBlock => {
+        unreachable!("should have been handled in `start_tag`");
+      }
+      TagEnd::BlockQuote(None) => {
+        writeln!(&mut self.buff, "</blockquote>")?;
+      }
+      TagEnd::BlockQuote(Some(_)) => {
+        writeln!(&mut self.buff, "</div>\n</div>")?;
+      }
+      TagEnd::List(true)               => writeln!(&mut self.buff, "</ol>")?,
+      TagEnd::List(false)              => writeln!(&mut self.buff, "</ul>")?,
+      TagEnd::Item                     => writeln!(&mut self.buff, "</li>")?,
+      TagEnd::DefinitionList           => writeln!(&mut self.buff, "</dl>")?,
+      TagEnd::DefinitionListTitle      => writeln!(&mut self.buff, "</dt>")?,
+      TagEnd::DefinitionListDefinition => writeln!(&mut self.buff, "</dd>")?,
+      TagEnd::Emphasis                 => write!(&mut self.buff, "</em>")?,
+      TagEnd::Strong                   => write!(&mut self.buff, "</strong>")?,
+      TagEnd::Strikethrough            => write!(&mut self.buff, "</del>")?,
+      TagEnd::Link                     => write!(&mut self.buff, "</a>")?,
+      TagEnd::Image                    => {} // handled in start_tag
+      TagEnd::FootnoteDefinition => {
+        unreachable!("footnotes are not supported");
+      }
+      TagEnd::MetadataBlock(_) => {
+        unreachable!("metadata blocks should be filtered in the begenning?");
+      }
+    }
+
+    Ok(())
+  }
+
+  fn process_image(
+    &mut self,
+    p: &mut Peekable<Parser<'_>>,
+    dest_url: CowStr<'_>,
+  ) -> io::Result<()> {
+    write!(&mut self.buff, "<img")?;
+
+    // TODO: support other link kinds?
+    if dest_url.starts_with("https://") || dest_url.starts_with("http://") {
+      write!(&mut self.buff, " src=\"{url}\"", url = Escaped(&dest_url))?;
+    } else { // relative URL
+      self.head_info.preload_imgs.push(&dest_url);
+      write!(&mut self.buff, " src=\"/{IMGS_SUBDIR}/{url}\"",
+             url = Escaped(&dest_url))?;
+    };
+
+    writeln!(&mut self.buff, " alt=\"")?;
+    for event in &mut *p {
+      match event {
+        Event::End(TagEnd::Image) => break,
+        Event::Text(alt_part) | Event::Code(alt_part) => {
+          write!(&mut self.buff, "{}", Escaped(&alt_part))?;
+        }
+        Event::SoftBreak                => {},
+        Event::Start(_) | Event::End(_) => {},
+        event => unreachable!("expeceted image alt, got {event:?}"),
+      }
+    }
+    writeln!(&mut self.buff, "\">")?;
+    Ok(())
+  }
 }
 
 impl Default for Renderer {
@@ -130,9 +544,11 @@ impl Default for Renderer {
       syntect::dumps::from_uncompressed_data(SYNTAX_SET_DUMP).unwrap()
     }
 
-    let buff       = RefCell::new(Vec::new());
+    let buff       = Vec::new();
     let syntax_set = LazyCell::new(load_syntax_set as fn() -> SyntaxSet);
-    Self { buff, syntax_set, }
+    let tmp_str    = String::new();
+    let head_info  = HeadInfo::default();
+    Self { buff, syntax_set, in_table_head: true, tmp_str, head_info, }
   }
 }
 
@@ -149,7 +565,7 @@ pub fn render_feed(
     w,
     FEED_TITLE,
     Some(DESCRIPTION),
-    &HeadInfo::default(),
+    None,
   )?;
   writeln!(w, "<body>")?;
   render_nav(w)?;
@@ -171,7 +587,8 @@ pub fn render_feed(
     writeln!(w, "<article>")?; // TODO: custom aria-label?
     writeln!(w, "<header>")?;
     writeln!(w, "<h6>")?;
-    writeln!(w, "<a href=\"/{POSTS_SUBDIR}/{post_name}.html\">{}</a>", Escaped(title))?;
+    writeln!(w, "<a href=\"/{POSTS_SUBDIR}/{post_name}.html\">{}</a>",
+                Escaped(title))?;
     writeln!(w, "</h6>")?;
     writeln!(w, "<time datetime=\"{}\">{}</time>", DateTime(*date), date)?;
     writeln!(w, "</header>")?;
@@ -228,427 +645,16 @@ pub fn render_rss(
   Ok(())
 }
 
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-struct State {
-  in_table_head: bool,
-}
-
-// Addapted from pulldown_cmark/html.rs
-// <https://github.com/pulldown-cmark/pulldown-cmark/>
-fn render_md_to_html<'h, W: Write>(
-  w:     &mut W,
-  post_index: &HashMap<String, PostInfo>,
-  syntax_set: &LazyCell<SyntaxSet>,
-  p:     &'h mut Peekable<Parser<'_>>,
-) -> io::Result<HeadInfo<'h>> {
-  let mut state     = State { in_table_head: true, };
-  let mut head_info = HeadInfo::default();
-
-  while let Some(event) = p.next() {
-    match event {
-      Event::Start(tag) => {
-        start_tag(
-          w,
-          tag,
-          post_index,
-          &mut head_info,
-          syntax_set,
-          &mut state,
-          p,
-        )?
-      }
-      Event::End(tag)   => end_tag(w, tag, &mut state)?,
-      Event::Text(text) => write!(w, "{}", Escaped(&text))?,
-      Event::Code(text) => {
-        write!(w, "<code>{}</code>", Escaped(&text))?;
-      }
-      Event::InlineMath(math) => {
-        head_info.needs_katex = true;
-        katex::render_inline(w, &math)?;
-      }
-      Event::DisplayMath(math) => {
-        head_info.needs_katex = true;
-        writeln!(w, "<figure class=\"equation\">")?;
-        katex::render_display(w, &math)?;
-        writeln!(w, "</figure>")?;
-      }
-      Event::SoftBreak                            => writeln!(w)?,
-      Event::HardBreak                            => writeln!(w, "<br/>")?,
-      Event::Rule                                 => writeln!(w, "<hr/>")?,
-      Event::InlineHtml(html) | Event::Html(html) => write!(w, "{html}")?,
-      Event::TaskListMarker(_) => {
-        unreachable!("task lists are not supported");
-      }
-      Event::FootnoteReference(_) => {
-        unreachable!("footnotes are not supported");
-      }
-    }
-  }
-  Ok(head_info)
-}
-
-// Addapted from pulldown_cmark/html.rs
-// <https://github.com/pulldown-cmark/pulldown-cmark/>
-fn start_tag<'h, W: Write>(
-  w:          &mut W,
-  tag:        Tag<'h>,
-  post_index: &HashMap<String, PostInfo>,
-  head_info:  &mut HeadInfo<'h>,
-  syntax_set: &LazyCell<SyntaxSet>,
-  state:      &mut State,
-  p:          &mut Peekable<Parser<'h>>,
-) -> io::Result<()> {
-  match tag {
-    Tag::HtmlBlock => {
-      // TODO(2): simplify this?
-      //          we could try to fork the parser and tuck some of this
-      //          complexity inside of it
-      while let Some(Event::Text(text)) = p.peek() {
-        write!(w, "{}", Escaped(text))?;
-        p.next();
-      }
-      let first_line = match p.next() {
-        Some(Event::Html(line)) => line,
-        None | Some(Event::End(TagEnd::HtmlBlock)) => return Ok(()),
-        Some(e) => {
-          unreachable!("should not get event {e:?} in the middle of an HTML block");
-        }
-      };
-
-      #[derive(Debug, Clone, Copy)]
-      enum Kind {
-        Script,
-        Style,
-        Link,
-      }
-
-      let kind = if first_line.starts_with("<script") {
-        Kind::Script
-      } else if first_line.starts_with("<style") {
-          Kind::Style
-      } else if first_line.starts_with("<link") {
-        Kind::Link
-      } else {
-        write!(w, "{}", first_line)?;
-        return Ok(());
-      };
-
-      // TODO(1): make this re-usable, maybe add a tmp_str field to State
-      let mut html = String::from(first_line);
-      for e in p {
-        match e {
-          Event::Text(line) | Event::Html(line) => html.push_str(&line),
-          Event::End(TagEnd::HtmlBlock)         => break,
-          e => {
-            unreachable!("should not get event {e:?} in the middle of HTML block");
-          }
-        }
-      }
-
-      match kind {
-        Kind::Script => {
-          let script = format!(
-            "{}</script>",
-            if let Some((start, _)) = html.rsplit_once("</script") {
-              start
-            } else {
-              &html
-            }
-          );
-          head_info.script_tags.push(script);
-        }
-        Kind::Style => {
-          let style = format!(
-            "{}</style>",
-            if let Some((start, _)) = html.rsplit_once("</style") {
-              start
-            } else {
-              &html
-            }
-          );
-          head_info.style_tags.push(style);
-        }
-        Kind::Link => {
-          let link = format!(
-            "{}>",
-            if let Some((start, _)) = html.split_once(">") {
-              start
-            } else {
-              &html
-            }
-          );
-          head_info.link_tags.push(link);
-        }
-      };
-    }
-    Tag::Paragraph => {
-      // horrible hack to wrap block images with <figure>
-      if !matches!(p.peek(), Some(Event::Start(Tag::Image { .. }))) {
-        writeln!(w, "<p>")?;
-        return Ok(());
-      }
-
-      let (dest_url, caption) = match p.next() {
-        Some(Event::Start(Tag::Image { dest_url, title: caption, .. })) => {
-          (dest_url, caption)
-        }
-        _ => unreachable!(),
-      };
-
-      writeln!(w, "<figure>")?;
-      process_image(w, p, dest_url, head_info)?;
-      if !caption.is_empty() {
-        writeln!(w, "<figcaption>")?;
-        writeln!(w, "{}", Escaped(&caption))?;
-        writeln!(w, "</figcaption>")?;
-      }
-      writeln!(w, "</figure>")?;
-
-      assert_eq!(p.next(), Some(Event::End(TagEnd::Paragraph)));
-    }
-    Tag::Heading { level, .. } => write!(w, "<{level}>")?,
-    Tag::Subscript             => write!(w, "<sub>")?,
-    Tag::Superscript           => write!(w, "<sup>")?,
-    Tag::Table(_alignments)    => write!(w, "<table>")?,
-    Tag::TableHead => {
-      state.in_table_head = true;
-      write!(w, "<thead><tr>")?;
-    }
-    Tag::TableRow => write!(w, "<tr>")?,
-    Tag::TableCell => if state.in_table_head {
-      write!(w, "<th>")?;
-    } else {
-      write!(w, "<td>")?;
-    },
-    Tag::CodeBlock(block_kind) => {
-      use syntect::{
-        html::{ClassedHTMLGenerator, ClassStyle},
-        util::LinesWithEndings,
-      };
-
-      head_info.needs_highlighting = true;
-
-      // TODO(1): make this re-usable, maybe add a tmp_str field to State
-      let mut code = String::new();
-      for event in p {
-        match event {
-          Event::Text(text)             => code.push_str(&text),
-          Event::SoftBreak              => {},
-          Event::End(TagEnd::CodeBlock) => break,
-          _ => unreachable!("should not get {event:?} inside of code block"),
-        }
-      }
-
-      let code_html = get_highlighted_code(code, block_kind, syntax_set);
-      fn get_highlighted_code(
-        code:       String,
-        block_kind: CodeBlockKind,
-        syntax_set: &LazyCell<SyntaxSet>,
-      ) -> String {
-        let lang = if let CodeBlockKind::Fenced(lang) = block_kind {
-          lang
-        } else {
-          return code;
-        };
-        if lang.is_empty() { return code; }
-
-        if let Some(syntax_ref) = syntax_set.find_syntax_by_token(&lang) {
-          let mut html_generator = ClassedHTMLGenerator::new_with_class_style(
-            syntax_ref,
-            syntax_set,
-            ClassStyle::Spaced,
-          );
-
-          for line in LinesWithEndings::from(&code) {
-            // TODO: warn the user somehow?
-            if html_generator
-              .parse_html_for_line_which_includes_newline(line)
-              .is_err() {
-                return code;
-            }
-          }
-
-          html_generator.finalize()
-        } else {
-          code
-        }
-      }
-
-      writeln!(w, "<div class=\"code-block\">")?;
-      writeln!(w, "<pre>{code_html}</pre>")?;
-      writeln!(w, "</div>")?;
-    }
-    Tag::BlockQuote(None) => writeln!(w, "<blockquote>")?,
-    Tag::BlockQuote(Some(kind)) => { // admonitions
-      let label = match kind {
-        BlockQuoteKind::Note      => "note",
-        BlockQuoteKind::Tip       => "tip",
-        BlockQuoteKind::Important => "important",
-        BlockQuoteKind::Warning   => "warning",
-        BlockQuoteKind::Caution   => "caution",
-      };
-
-      writeln!(w, "<div class=\"admonition\" aria-label=\"{label}\" role=\"note\">")?;
-      writeln!(w, "<div aria-hidden=\"true\">")?;
-      writeln!(w, "<img class=\"icon\" src=\"/{ICONS_SUBDIR}/{label}.svg\" width=\"20\" height=\"20\" alt=\"{label} icon\">")?;
-      writeln!(w, "</div>")?;
-      writeln!(w, "<div>")?;
-    }
-    Tag::List(Some(1))            => writeln!(w, "<ol>")?,
-    Tag::List(Some(start))        => writeln!(w, "<ol start=\"{start}\">")?,
-    Tag::List(None)               => writeln!(w, "<ul>")?,
-    Tag::Item                     => writeln!(w, "<li>")?,
-    Tag::DefinitionList           => writeln!(w, "<dl>")?,
-    Tag::DefinitionListTitle      => write!(w, "<dt>")?,
-    Tag::DefinitionListDefinition => write!(w, "<dd>")?,
-    Tag::Emphasis                 => write!(w, "<em>")?,
-    Tag::Strong                   => write!(w, "<strong>")?,
-    Tag::Strikethrough            => write!(w, "<del>")?,
-    Tag::Link { link_type: LinkType::Email, dest_url, .. } => {
-      write!(w, "<a href=\"mailto:{url}\">", url = Escaped(&dest_url))?;
-    }
-    Tag::Link { link_type: LinkType::WikiLink { .. }, dest_url, .. } => {
-      write!(w, "<a href=\"/{POSTS_SUBDIR}/{}.html\">", Escaped(&dest_url))?;
-      if let Some(PostInfo { title, .. }) = post_index
-        .get(&dest_url.to_string()) {
-        write!(w, "{title}")?;
-        // NOTE: the next event should cotain the content that goes inside the
-        //       link tag, which in this case is just the post tag we already
-        //       know from `dest_url` (API quirck?)
-        let _ = p.next();
-      }
-    }
-    Tag::Link { dest_url, .. } => {
-      write!(w, "<a href=\"{url}\">", url = Escaped(&dest_url))?;
-    }
-    Tag::Image { dest_url, .. } => {
-      process_image(w, p, dest_url, head_info)?;
-    }
-    Tag::FootnoteDefinition(_) => {
-      unreachable!("footnotes are not supported");
-    }
-    Tag::MetadataBlock(_) => {
-      unreachable!("metadata blocks should be at the beginning");
-    }
-  }
-
-  Ok(())
-}
-
-// Addapted from pulldown_cmark/html.rs
-// <https://github.com/pulldown-cmark/pulldown-cmark/>
-fn end_tag<W: Write>(
-  w: &mut W,
-  tag: TagEnd,
-  state: &mut State,
-) -> io::Result<()> {
-  match tag {
-    TagEnd::HtmlBlock      => {}
-    TagEnd::Paragraph      => writeln!(w, "\n</p>")?,
-    TagEnd::Heading(level) => writeln!(w, "</{level}>")?,
-    TagEnd::Subscript      => write!(w, "</sub>")?,
-    TagEnd::Superscript    => write!(w, "</sup>")?,
-    TagEnd::Table => {
-      writeln!(w, "</tbody>")?;
-      writeln!(w, "</table>")?;
-    }
-    TagEnd::TableHead => {
-      writeln!(w, "</tr>")?;
-      writeln!(w, "</thead>")?;
-      writeln!(w, "<tbody>")?;
-      state.in_table_head = false;
-    }
-    TagEnd::TableRow => writeln!(w, "</tr>")?,
-    TagEnd::TableCell => if state.in_table_head {
-      write!(w, "</th>")?;
-    } else {
-      write!(w, "</td>")?;
-    },
-    TagEnd::CodeBlock => {
-      unreachable!("should have been handled in `start_tag`");
-    }
-    TagEnd::BlockQuote(None)         => writeln!(w, "</blockquote>")?,
-    TagEnd::BlockQuote(Some(_))      => writeln!(w, "</div>\n</div>")?,
-    TagEnd::List(true)               => writeln!(w, "</ol>")?,
-    TagEnd::List(false)              => writeln!(w, "</ul>")?,
-    TagEnd::Item                     => writeln!(w, "</li>")?,
-    TagEnd::DefinitionList           => writeln!(w, "</dl>")?,
-    TagEnd::DefinitionListTitle      => writeln!(w, "</dt>")?,
-    TagEnd::DefinitionListDefinition => writeln!(w, "</dd>")?,
-    TagEnd::Emphasis                 => write!(w, "</em>")?,
-    TagEnd::Strong                   => write!(w, "</strong>")?,
-    TagEnd::Strikethrough            => write!(w, "</del>")?,
-    TagEnd::Link                     => write!(w, "</a>")?,
-    TagEnd::Image                    => {} // handled in start_tag
-    TagEnd::FootnoteDefinition => {
-      unreachable!("footnotes are not supported");
-    }
-    TagEnd::MetadataBlock(_) => {
-      unreachable!("metadata blocks should be filtered in the begenning?");
-    }
-  }
-
-  Ok(())
-}
-
-fn process_image<'h, W: Write>(
-  w:         &mut W,
-  p:         &mut Peekable<Parser<'_>>,
-  dest_url:  CowStr<'h>,
-  head_info: &mut HeadInfo<'h>,
-) -> io::Result<()> {
-  write!(w, "<img")?;
-
-  // TODO: support other link kinds?
-  if dest_url.starts_with("https://") || dest_url.starts_with("http://") {
-    write!(w, " src=\"{url}\"", url = Escaped(&dest_url))?;
-  } else { // relative URL
-    head_info.preload_imgs.push(dest_url.clone());
-    write!(w, " src=\"/{IMGS_SUBDIR}/{url}\"", url = Escaped(&dest_url))?;
-  };
-
-  writeln!(w, " alt=\"")?;
-  for event in &mut *p {
-    match event {
-      Event::End(TagEnd::Image) => break,
-      Event::Text(alt_part) | Event::Code(alt_part) => {
-        write!(w, "{}", Escaped(&alt_part))?;
-      }
-      Event::SoftBreak                => {},
-      Event::Start(_) | Event::End(_) => {},
-      event => unreachable!("expeceted image alt, got {event:?}"),
-    }
-  }
-  writeln!(w, "\">")?;
-  Ok(())
-}
-
 fn render_copyright<W: Write>(w: &mut W) -> io::Result<()> {
   const COPYRIGHT: &str = include_str!("html/copyright.html");
   writeln!(w, "{}", COPYRIGHT)
 }
 
-// TODO(1): get rid of this lifetime to make this re-usable by the renderer
-//
-//          we should also make it so that the entries of the vectors are
-//          re-usable: when clearing HeadInfo we should not discard the strings
-//          inside each vectors, but rather clear those strings and marked then
-//          as "unused"
-#[derive(Debug, Default)]
-struct HeadInfo<'h> {
-  needs_katex:        bool,
-  needs_highlighting: bool,
-  preload_imgs:       Vec<CowStr<'h>>,
-  script_tags: Vec<String>,
-  style_tags:  Vec<String>,
-  link_tags:   Vec<String>,
-}
-
 fn render_head<W: Write>(
   w:           &mut W,
   title:       &str,
   description: Option<&str>,
-  head_info:   &HeadInfo,
+  head_info:   Option<&HeadInfo>,
 ) -> io::Result<()> {
   const PRELOAD_MAX: usize = 2;
   writeln!(w, "<head>")?;
@@ -664,19 +670,23 @@ fn render_head(
   //       https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/meta/name
   writeln!(w, "<meta name=\"copyright\"   content=\"GPLv3\">")?;
   writeln!(w, "<link rel=\"stylesheet\" href=\"/css/styles.css\">")?;
-  if head_info.needs_katex {
+  if let Some(info) = head_info && info.needs_katex {
     writeln!(w, "<link rel=\"stylesheet\" href=\"/css/katex.css\">")?;
   }
-  if head_info.needs_highlighting {
+  if let Some(info) = head_info && info.needs_highlighting {
     writeln!(w, "<link rel=\"stylesheet\" href=\"/css/highlighting.css\">")?;
   }
-  for link in &head_info.link_tags   { writeln!(w, "{link}")?;  }
-  for style in &head_info.style_tags { writeln!(w, "{style}")?; }
+  if let Some(info) = head_info {
+    for link  in info.link_tags.iter()  { writeln!(w, "{link}")?;  }
+    for style in info.style_tags.iter() { writeln!(w, "{style}")?; }
+  }
   writeln!(w, "<link rel=\"icon\" type=\"image/svg+xml\" sizes=\"16x16 24x24 32x32 48x48 64x64 128x128 256x256 512x512\" href=\"/{IMGS_SUBDIR}/icons/favicon.svg\">")?;
   writeln!(w, "<script type=\"module\" src=\"/js/vim-controls.js\"></script>")?;
-  for script in &head_info.script_tags { writeln!(w, "{script}")?; }
-  for img_path in head_info.preload_imgs.iter().take(PRELOAD_MAX) {
-    writeln!(w, "<link rel=\"preload\" as=\"image\" href=\"/{IMGS_SUBDIR}/{img_path}\">")?;
+  if let Some(info) = head_info {
+    for script in info.script_tags.iter() { writeln!(w, "{script}")?; }
+    for img_path in info.preload_imgs.iter().take(PRELOAD_MAX) {
+      writeln!(w, "<link rel=\"preload\" as=\"image\" href=\"/{IMGS_SUBDIR}/{img_path}\">")?;
+    }
   }
   writeln!(w, "</head>")?;
 
diff --git a/src/main.rs b/src/main.rs
@@ -17,6 +17,7 @@ mod log;
 mod escape;
 mod html;
 mod katex;
+mod string_store;
 
 #[derive(Clone, Debug)]
 pub struct PostInfo {
@@ -170,7 +171,7 @@ fn do_it(input_dir: &str, full_build: bool) -> Result<(), ()> {
     }
   }
 
-  let r = html::Renderer::default();
+  let mut r = html::Renderer::default();
 
   for (job_name, output_path, post) in parsed_posts_to_render {
     let mut f = create_file(&output_path).map_err(|_| ())?;
diff --git /dev/null b/src/string_store.rs
@@ -0,0 +1,85 @@
+#[derive(Debug)]
+/// An arena of mutable strings.
+///
+/// [`StringStore`] provides an interface similar to that of [`Vec<String>`],
+/// the [`clear`] method is further optimized: instead of discarding all
+/// entries in the store, we simply mark them as re-usable, thus avoiding
+/// re-allocations.
+pub struct StringStore {
+  inner:     Vec<String>,
+  allocated: usize,
+}
+
+#[derive(Debug)]
+pub struct StringStoreIter<'a> {
+  store:   &'a StringStore,
+  current: usize,
+}
+
+impl StringStore {
+  pub const fn new() -> Self {
+    Self { inner: Vec::new(), allocated: 0, }
+  }
+
+  #[allow(dead_code)]
+  pub fn with_capacity(capacity: usize) -> Self {
+    let inner = vec![const { String::new() }; capacity];
+    Self { inner, allocated: 0, }
+  }
+
+  /// Allocates a new string in the store.
+  pub fn alloc(&mut self) -> &mut String {
+    assert!(self.allocated <= self.inner.len());
+    if self.allocated == self.inner.len() {
+      self.inner.push(String::new());
+    } else {
+      self.inner[self.allocated].clear();
+    }
+
+    let i = self.allocated;
+    self.allocated += 1;
+    &mut self.inner[i]
+  }
+
+  #[inline]
+  /// Allocates a new string in the store and sets its value to [`s`].
+  pub fn push(&mut self, s: &str) {
+    self.alloc().push_str(s);
+  }
+
+  #[inline]
+  pub fn len(&self) -> usize {
+    self.allocated
+  }
+
+  #[inline]
+  /// Marks all entries in the store as re-usable.
+  pub fn clear(&mut self) {
+    self.allocated = 0;
+  }
+
+  pub fn iter<'a>(&'a self) -> StringStoreIter<'a> {
+    StringStoreIter { store: self, current: 0, }
+  }
+}
+
+impl Default for StringStore {
+  fn default() -> Self {
+    Self::new()
+  }
+}
+
+impl<'a> Iterator for StringStoreIter<'a> {
+  type Item = &'a str;
+
+  fn next(&mut self) -> Option<Self::Item> {
+    assert!(self.current <= self.store.len());
+    if self.current == self.store.len() {
+      return None;
+    }
+
+    let result = &self.store.inner[self.current];
+    self.current += 1;
+    Some(result)
+  }
+}