Skip to content

Commit

Permalink
Don't panic if close_tag() is called without tags to close
Browse files Browse the repository at this point in the history
This can happen when a tag is opened after the length limit is reached;
the tag will not end up being added to `unclosed_tags` because the queue
will never be flushed. So, now, if the `unclosed_tags` stack is empty,
`close_tag()` does nothing.

This change fixes a panic in the `limit_0` unit test.
  • Loading branch information
camelid committed Aug 26, 2021
1 parent d932e62 commit 4478ecc
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
12 changes: 10 additions & 2 deletions src/librustdoc/html/length_limit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,16 @@ impl HtmlWithLimit {

/// Close the most recently opened HTML tag.
pub(super) fn close_tag(&mut self) {
let tag_name = self.unclosed_tags.pop().unwrap();
write!(self.buf, "</{}>", tag_name).unwrap();
match self.unclosed_tags.pop() {
// Close the most recently opened tag.
Some(tag_name) => write!(self.buf, "</{}>", tag_name).unwrap(),
// There are valid cases where `close_tag()` is called without
// there being any tags to close. For example, this occurs when
// a tag is opened after the length limit is exceeded;
// `flush_queue()` will never be called, and thus, the tag will
// not end up being added to `unclosed_tags`.
None => {}
}
}

/// Write all queued tags and add them to the `unclosed_tags` list.
Expand Down
5 changes: 4 additions & 1 deletion src/librustdoc/html/length_limit/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -107,11 +107,14 @@ fn quickly_past_the_limit() {
}

#[test]
#[should_panic = "called `Option::unwrap()` on a `None` value"]
fn close_too_many() {
let mut buf = HtmlWithLimit::new(60);
buf.open_tag("p");
buf.push("Hello");
buf.close_tag();
// This call does not panic because there are valid cases
// where `close_tag()` is called with no tags left to close.
// So `close_tag()` does nothing in this case.
buf.close_tag();
assert_eq!(buf.finish(), "<p>Hello</p>");
}

0 comments on commit 4478ecc

Please sign in to comment.