-
Notifications
You must be signed in to change notification settings - Fork 13.4k
Refactor Markdown length-limited summary implementation #88173
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
bors
merged 7 commits into
rust-lang:master
from
camelid:refactor-markdown-length-limit
Aug 29, 2021
Merged
Changes from all commits
Commits
Show all changes
7 commits
Select commit
Hold shift + click to select a range
39ef8ea
Refactor Markdown length-limited summary implementation
camelid 09f0876
Clarify wording in docs
camelid 74147b8
Use the length limit as the initial capacity
camelid d18936a
Use `write!`
camelid f8ca576
Add tests for `HtmlWithLimit`
camelid d932e62
Assert that `tag_name` is alphabetic
camelid 4478ecc
Don't panic if `close_tag()` is called without tags to close
camelid File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,119 @@ | ||
//! See [`HtmlWithLimit`]. | ||
|
||
use std::fmt::Write; | ||
use std::ops::ControlFlow; | ||
|
||
use crate::html::escape::Escape; | ||
|
||
/// A buffer that allows generating HTML with a length limit. | ||
/// | ||
/// This buffer ensures that: | ||
/// | ||
/// * all tags are closed, | ||
/// * tags are closed in the reverse order of when they were opened (i.e., the correct HTML order), | ||
/// * no tags are left empty (e.g., `<em></em>`) due to the length limit being reached, | ||
/// * all text is escaped. | ||
#[derive(Debug)] | ||
pub(super) struct HtmlWithLimit { | ||
buf: String, | ||
len: usize, | ||
limit: usize, | ||
/// A list of tags that have been requested to be opened via [`Self::open_tag()`] | ||
/// but have not actually been pushed to `buf` yet. This ensures that tags are not | ||
/// left empty (e.g., `<em></em>`) due to the length limit being reached. | ||
queued_tags: Vec<&'static str>, | ||
/// A list of all tags that have been opened but not yet closed. | ||
unclosed_tags: Vec<&'static str>, | ||
} | ||
|
||
impl HtmlWithLimit { | ||
/// Create a new buffer, with a limit of `length_limit`. | ||
pub(super) fn new(length_limit: usize) -> Self { | ||
let buf = if length_limit > 1000 { | ||
// If the length limit is really large, don't preallocate tons of memory. | ||
String::new() | ||
} else { | ||
// The length limit is actually a good heuristic for initial allocation size. | ||
// Measurements showed that using it as the initial capacity ended up using less memory | ||
// than `String::new`. | ||
// See https://github.com/rust-lang/rust/pull/88173#discussion_r692531631 for more. | ||
String::with_capacity(length_limit) | ||
}; | ||
Self { | ||
buf, | ||
len: 0, | ||
limit: length_limit, | ||
unclosed_tags: Vec::new(), | ||
queued_tags: Vec::new(), | ||
} | ||
} | ||
|
||
/// Finish using the buffer and get the written output. | ||
/// This function will close all unclosed tags for you. | ||
pub(super) fn finish(mut self) -> String { | ||
self.close_all_tags(); | ||
self.buf | ||
} | ||
|
||
/// Write some plain text to the buffer, escaping as needed. | ||
/// | ||
/// This function skips writing the text if the length limit was reached | ||
/// and returns [`ControlFlow::Break`]. | ||
pub(super) fn push(&mut self, text: &str) -> ControlFlow<(), ()> { | ||
if self.len + text.len() > self.limit { | ||
return ControlFlow::BREAK; | ||
} | ||
|
||
self.flush_queue(); | ||
write!(self.buf, "{}", Escape(text)).unwrap(); | ||
self.len += text.len(); | ||
|
||
ControlFlow::CONTINUE | ||
} | ||
|
||
/// Open an HTML tag. | ||
/// | ||
/// **Note:** HTML attributes have not yet been implemented. | ||
/// This function will panic if called with a non-alphabetic `tag_name`. | ||
pub(super) fn open_tag(&mut self, tag_name: &'static str) { | ||
camelid marked this conversation as resolved.
Show resolved
Hide resolved
|
||
assert!( | ||
tag_name.chars().all(|c| ('a'..='z').contains(&c)), | ||
"tag_name contained non-alphabetic chars: {:?}", | ||
tag_name | ||
); | ||
self.queued_tags.push(tag_name); | ||
} | ||
|
||
/// Close the most recently opened HTML tag. | ||
pub(super) fn close_tag(&mut self) { | ||
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. | ||
fn flush_queue(&mut self) { | ||
for tag_name in self.queued_tags.drain(..) { | ||
write!(self.buf, "<{}>", tag_name).unwrap(); | ||
|
||
self.unclosed_tags.push(tag_name); | ||
} | ||
} | ||
|
||
/// Close all unclosed tags. | ||
fn close_all_tags(&mut self) { | ||
while !self.unclosed_tags.is_empty() { | ||
self.close_tag(); | ||
} | ||
} | ||
} | ||
|
||
#[cfg(test)] | ||
mod tests; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,120 @@ | ||
use super::*; | ||
|
||
#[test] | ||
fn empty() { | ||
assert_eq!(HtmlWithLimit::new(0).finish(), ""); | ||
assert_eq!(HtmlWithLimit::new(60).finish(), ""); | ||
} | ||
|
||
#[test] | ||
fn basic() { | ||
let mut buf = HtmlWithLimit::new(60); | ||
buf.push("Hello "); | ||
buf.open_tag("em"); | ||
buf.push("world"); | ||
buf.close_tag(); | ||
buf.push("!"); | ||
assert_eq!(buf.finish(), "Hello <em>world</em>!"); | ||
} | ||
|
||
#[test] | ||
fn no_tags() { | ||
let mut buf = HtmlWithLimit::new(60); | ||
buf.push("Hello"); | ||
buf.push(" world!"); | ||
assert_eq!(buf.finish(), "Hello world!"); | ||
} | ||
|
||
#[test] | ||
fn limit_0() { | ||
let mut buf = HtmlWithLimit::new(0); | ||
buf.push("Hello "); | ||
buf.open_tag("em"); | ||
buf.push("world"); | ||
buf.close_tag(); | ||
buf.push("!"); | ||
assert_eq!(buf.finish(), ""); | ||
} | ||
|
||
#[test] | ||
fn exactly_limit() { | ||
let mut buf = HtmlWithLimit::new(12); | ||
buf.push("Hello "); | ||
buf.open_tag("em"); | ||
buf.push("world"); | ||
buf.close_tag(); | ||
buf.push("!"); | ||
assert_eq!(buf.finish(), "Hello <em>world</em>!"); | ||
} | ||
|
||
#[test] | ||
fn multiple_nested_tags() { | ||
let mut buf = HtmlWithLimit::new(60); | ||
buf.open_tag("p"); | ||
buf.push("This is a "); | ||
buf.open_tag("em"); | ||
buf.push("paragraph"); | ||
buf.open_tag("strong"); | ||
buf.push("!"); | ||
buf.close_tag(); | ||
buf.close_tag(); | ||
buf.close_tag(); | ||
assert_eq!(buf.finish(), "<p>This is a <em>paragraph<strong>!</strong></em></p>"); | ||
} | ||
|
||
#[test] | ||
fn forgot_to_close_tags() { | ||
let mut buf = HtmlWithLimit::new(60); | ||
buf.open_tag("p"); | ||
buf.push("This is a "); | ||
buf.open_tag("em"); | ||
buf.push("paragraph"); | ||
buf.open_tag("strong"); | ||
buf.push("!"); | ||
assert_eq!(buf.finish(), "<p>This is a <em>paragraph<strong>!</strong></em></p>"); | ||
} | ||
|
||
#[test] | ||
fn past_the_limit() { | ||
let mut buf = HtmlWithLimit::new(20); | ||
buf.open_tag("p"); | ||
(0..10).try_for_each(|n| { | ||
buf.open_tag("strong"); | ||
buf.push("word#")?; | ||
buf.push(&n.to_string())?; | ||
buf.close_tag(); | ||
ControlFlow::CONTINUE | ||
}); | ||
buf.close_tag(); | ||
assert_eq!( | ||
buf.finish(), | ||
"<p>\ | ||
<strong>word#0</strong>\ | ||
<strong>word#1</strong>\ | ||
<strong>word#2</strong>\ | ||
</p>" | ||
); | ||
} | ||
|
||
#[test] | ||
fn quickly_past_the_limit() { | ||
let mut buf = HtmlWithLimit::new(6); | ||
buf.open_tag("p"); | ||
buf.push("Hello"); | ||
buf.push(" World"); | ||
// intentionally not closing <p> before finishing | ||
assert_eq!(buf.finish(), "<p>Hello</p>"); | ||
} | ||
|
||
#[test] | ||
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>"); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.