From 2c83b0d97475d28000ca3757d0da43327cea6c14 Mon Sep 17 00:00:00 2001
From: Nokome Bentley <nokome@stenci.la>
Date: Fri, 9 Aug 2024 22:19:46 +1200
Subject: [PATCH] Fix panic on incomplete closing frontmatter fence

Closes GH-121.

Reviewed-by: Titus Wormer <tituswormer@gmail.com>
---
 src/construct/document.rs | 16 +++++++++-------
 tests/frontmatter.rs      |  6 ++++++
 2 files changed, 15 insertions(+), 7 deletions(-)

diff --git a/src/construct/document.rs b/src/construct/document.rs
index 204e9347..c8e351a2 100644
--- a/src/construct/document.rs
+++ b/src/construct/document.rs
@@ -565,14 +565,16 @@ fn resolve(tokenizer: &mut Tokenizer) {
                 inject_index = child_index + 1;
             }
 
-            if let Some(mut exits) = tokenizer.tokenize_state.document_exits[line].take() {
-                let mut exit_index = 0;
-                while exit_index < exits.len() {
-                    exits[exit_index].point = point.clone();
-                    exit_index += 1;
+            if line < tokenizer.tokenize_state.document_exits.len() {
+                if let Some(mut exits) = tokenizer.tokenize_state.document_exits[line].take() {
+                    let mut exit_index = 0;
+                    while exit_index < exits.len() {
+                        exits[exit_index].point = point.clone();
+                        exit_index += 1;
+                    }
+
+                    child.map.add(inject_index, 0, exits);
                 }
-
-                child.map.add(inject_index, 0, exits);
             }
 
             line += 1;
diff --git a/tests/frontmatter.rs b/tests/frontmatter.rs
index 68efd485..a1077f8a 100644
--- a/tests/frontmatter.rs
+++ b/tests/frontmatter.rs
@@ -61,6 +61,12 @@ fn frontmatter() -> Result<(), message::Message> {
         "should not support 2 markers in a closing fence"
     );
 
+    assert_eq!(
+        to_html_with_options("---\n--\n", &frontmatter)?,
+        "<hr />\n<p>--</p>\n",
+        "should not panic if newline after 2 marker closing fence"
+    );
+
     assert_eq!(
         to_html_with_options("---\n----", &frontmatter)?,
         "<hr />\n<hr />",