Skip to content

Commit 39ef8ea

Browse files
committed
Refactor Markdown length-limited summary implementation
This commit refactors the implementation of `markdown_summary_with_limit()`, separating the logic of determining when the limit has been reached from the actual rendering process. The main advantage of the new approach is that it guarantees that all HTML tags are closed, whereas the previous implementation could generate tags that were never closed. It also ensures that no empty tags are generated (e.g., `<em></em>`). The new implementation consists of a general-purpose struct `HtmlWithLimit` that manages the length-limiting logic and a function `markdown_summary_with_limit()` that renders Markdown to HTML using the struct.
1 parent 7960030 commit 39ef8ea

File tree

4 files changed

+125
-43
lines changed

4 files changed

+125
-43
lines changed

src/librustdoc/html/length_limit.rs

Lines changed: 94 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,94 @@
1+
//! See [`HtmlWithLimit`].
2+
3+
use std::fmt::Write;
4+
use std::ops::ControlFlow;
5+
6+
use crate::html::escape::Escape;
7+
8+
/// A buffer that allows generating HTML with a length limit.
9+
///
10+
/// This buffer ensures that:
11+
///
12+
/// * all tags are closed,
13+
/// * only the most recently opened tag is closed,
14+
/// * no tags are left empty (e.g., `<em></em>`) due to the length limit being reached,
15+
/// * all text is escaped.
16+
#[derive(Debug)]
17+
pub(super) struct HtmlWithLimit {
18+
buf: String,
19+
len: usize,
20+
limit: usize,
21+
/// A list of tags that have been requested to be opened via [`Self::open_tag()`]
22+
/// but have not actually been pushed to `buf` yet. This ensures that tags are not
23+
/// left empty (e.g., `<em></em>`) due to the length limit being reached.
24+
queued_tags: Vec<&'static str>,
25+
/// A list of all tags that have been opened but not yet closed.
26+
unclosed_tags: Vec<&'static str>,
27+
}
28+
29+
impl HtmlWithLimit {
30+
/// Create a new buffer, with a limit of `length_limit`.
31+
pub(super) fn new(length_limit: usize) -> Self {
32+
Self {
33+
buf: String::new(),
34+
len: 0,
35+
limit: length_limit,
36+
unclosed_tags: Vec::new(),
37+
queued_tags: Vec::new(),
38+
}
39+
}
40+
41+
/// Finish using the buffer and get the written output.
42+
/// This function will close all unclosed tags for you.
43+
pub(super) fn finish(mut self) -> String {
44+
self.close_all_tags();
45+
self.buf
46+
}
47+
48+
/// Write some plain text to the buffer, escaping as needed.
49+
///
50+
/// This function skips writing the text if the length limit was reached
51+
/// and returns [`ControlFlow::Break`].
52+
pub(super) fn push(&mut self, text: &str) -> ControlFlow<(), ()> {
53+
if self.len + text.len() > self.limit {
54+
return ControlFlow::BREAK;
55+
}
56+
57+
self.flush_queue();
58+
write!(self.buf, "{}", Escape(text)).unwrap();
59+
self.len += text.len();
60+
61+
ControlFlow::CONTINUE
62+
}
63+
64+
/// Open an HTML tag.
65+
pub(super) fn open_tag(&mut self, tag_name: &'static str) {
66+
self.queued_tags.push(tag_name);
67+
}
68+
69+
/// Close the most recently opened HTML tag.
70+
pub(super) fn close_tag(&mut self) {
71+
let tag_name = self.unclosed_tags.pop().unwrap();
72+
self.buf.push_str("</");
73+
self.buf.push_str(tag_name);
74+
self.buf.push('>');
75+
}
76+
77+
/// Write all queued tags and add them to the `unclosed_tags` list.
78+
fn flush_queue(&mut self) {
79+
for tag_name in self.queued_tags.drain(..) {
80+
self.buf.push('<');
81+
self.buf.push_str(tag_name);
82+
self.buf.push('>');
83+
84+
self.unclosed_tags.push(tag_name);
85+
}
86+
}
87+
88+
/// Close all unclosed tags.
89+
fn close_all_tags(&mut self) {
90+
while !self.unclosed_tags.is_empty() {
91+
self.close_tag();
92+
}
93+
}
94+
}

src/librustdoc/html/markdown.rs

Lines changed: 29 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -23,19 +23,21 @@ use rustc_hir::HirId;
2323
use rustc_middle::ty::TyCtxt;
2424
use rustc_span::edition::Edition;
2525
use rustc_span::Span;
26+
2627
use std::borrow::Cow;
2728
use std::cell::RefCell;
2829
use std::collections::VecDeque;
2930
use std::default::Default;
3031
use std::fmt::Write;
31-
use std::ops::Range;
32+
use std::ops::{ControlFlow, Range};
3233
use std::str;
3334

3435
use crate::clean::RenderedLink;
3536
use crate::doctest;
3637
use crate::html::escape::Escape;
3738
use crate::html::format::Buffer;
3839
use crate::html::highlight;
40+
use crate::html::length_limit::HtmlWithLimit;
3941
use crate::html::toc::TocBuilder;
4042

4143
use pulldown_cmark::{
@@ -1081,15 +1083,6 @@ fn markdown_summary_with_limit(
10811083
return (String::new(), false);
10821084
}
10831085

1084-
let mut s = String::with_capacity(md.len() * 3 / 2);
1085-
let mut text_length = 0;
1086-
let mut stopped_early = false;
1087-
1088-
fn push(s: &mut String, text_length: &mut usize, text: &str) {
1089-
write!(s, "{}", Escape(text)).unwrap();
1090-
*text_length += text.len();
1091-
}
1092-
10931086
let mut replacer = |broken_link: BrokenLink<'_>| {
10941087
if let Some(link) =
10951088
link_names.iter().find(|link| &*link.original_text == broken_link.reference)
@@ -1101,56 +1094,49 @@ fn markdown_summary_with_limit(
11011094
};
11021095

11031096
let p = Parser::new_with_broken_link_callback(md, opts(), Some(&mut replacer));
1104-
let p = LinkReplacer::new(p, link_names);
1097+
let mut p = LinkReplacer::new(p, link_names);
11051098

1106-
'outer: for event in p {
1099+
// FIXME: capacity
1100+
let mut buf = HtmlWithLimit::new(length_limit);
1101+
let mut stopped_early = false;
1102+
p.try_for_each(|event| {
11071103
match &event {
11081104
Event::Text(text) => {
1109-
for word in text.split_inclusive(char::is_whitespace) {
1110-
if text_length + word.len() >= length_limit {
1111-
stopped_early = true;
1112-
break 'outer;
1113-
}
1114-
1115-
push(&mut s, &mut text_length, word);
1105+
let r =
1106+
text.split_inclusive(char::is_whitespace).try_for_each(|word| buf.push(word));
1107+
if r.is_break() {
1108+
stopped_early = true;
11161109
}
1110+
return r;
11171111
}
11181112
Event::Code(code) => {
1119-
if text_length + code.len() >= length_limit {
1113+
buf.open_tag("code");
1114+
let r = buf.push(code);
1115+
if r.is_break() {
11201116
stopped_early = true;
1121-
break;
1117+
} else {
1118+
buf.close_tag();
11221119
}
1123-
1124-
s.push_str("<code>");
1125-
push(&mut s, &mut text_length, code);
1126-
s.push_str("</code>");
1120+
return r;
11271121
}
11281122
Event::Start(tag) => match tag {
1129-
Tag::Emphasis => s.push_str("<em>"),
1130-
Tag::Strong => s.push_str("<strong>"),
1131-
Tag::CodeBlock(..) => break,
1123+
Tag::Emphasis => buf.open_tag("em"),
1124+
Tag::Strong => buf.open_tag("strong"),
1125+
Tag::CodeBlock(..) => return ControlFlow::BREAK,
11321126
_ => {}
11331127
},
11341128
Event::End(tag) => match tag {
1135-
Tag::Emphasis => s.push_str("</em>"),
1136-
Tag::Strong => s.push_str("</strong>"),
1137-
Tag::Paragraph => break,
1138-
Tag::Heading(..) => break,
1129+
Tag::Emphasis | Tag::Strong => buf.close_tag(),
1130+
Tag::Paragraph | Tag::Heading(..) => return ControlFlow::BREAK,
11391131
_ => {}
11401132
},
1141-
Event::HardBreak | Event::SoftBreak => {
1142-
if text_length + 1 >= length_limit {
1143-
stopped_early = true;
1144-
break;
1145-
}
1146-
1147-
push(&mut s, &mut text_length, " ");
1148-
}
1133+
Event::HardBreak | Event::SoftBreak => buf.push(" ")?,
11491134
_ => {}
1150-
}
1151-
}
1135+
};
1136+
ControlFlow::CONTINUE
1137+
});
11521138

1153-
(s, stopped_early)
1139+
(buf.finish(), stopped_early)
11541140
}
11551141

11561142
/// Renders a shortened first paragraph of the given Markdown as a subset of Markdown,

src/librustdoc/html/mod.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ crate mod escape;
22
crate mod format;
33
crate mod highlight;
44
crate mod layout;
5+
mod length_limit;
56
// used by the error-index generator, so it needs to be public
67
pub mod markdown;
78
crate mod render;

src/librustdoc/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
#![feature(rustc_private)]
66
#![feature(array_methods)]
77
#![feature(box_patterns)]
8+
#![feature(control_flow_enum)]
89
#![feature(in_band_lifetimes)]
910
#![feature(nll)]
1011
#![feature(test)]

0 commit comments

Comments
 (0)