Skip to content

Commit

Permalink
Fewer temporary strings
Browse files Browse the repository at this point in the history
  • Loading branch information
bugadani committed Jan 29, 2021
1 parent e2fa4e0 commit d5cac19
Show file tree
Hide file tree
Showing 6 changed files with 126 additions and 97 deletions.
2 changes: 1 addition & 1 deletion src/librustdoc/formats/item_type.rs
Original file line number Diff line number Diff line change
Expand Up @@ -158,6 +158,6 @@ impl ItemType {

impl fmt::Display for ItemType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.as_str())
f.write_str(self.as_str())
}
}
44 changes: 21 additions & 23 deletions src/librustdoc/html/highlight.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,26 @@

use crate::html::escape::Escape;

use std::fmt::{Display, Write};
use std::fmt::Display;
use std::iter::Peekable;

use rustc_lexer::{LiteralKind, TokenKind};
use rustc_span::edition::Edition;
use rustc_span::symbol::Symbol;
use rustc_span::with_default_session_globals;

use super::format::Buffer;

/// Highlights `src`, returning the HTML output.
crate fn render_with_highlighting(
src: &str,
out: &mut Buffer,
class: Option<&str>,
playground_button: Option<&str>,
tooltip: Option<(Option<Edition>, &str)>,
edition: Edition,
) -> String {
) {
debug!("highlighting: ================\n{}\n==============", src);
let mut out = String::with_capacity(src.len());
if let Some((edition_info, class)) = tooltip {
write!(
out,
Expand All @@ -35,23 +37,19 @@ crate fn render_with_highlighting(
} else {
String::new()
},
)
.unwrap();
);
}

write_header(&mut out, class);
write_code(&mut out, &src, edition);
write_footer(&mut out, playground_button);

out
write_header(out, class);
write_code(out, &src, edition);
write_footer(out, playground_button);
}

fn write_header(out: &mut String, class: Option<&str>) {
write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or_default())
.unwrap()
fn write_header(out: &mut Buffer, class: Option<&str>) {
write!(out, "<div class=\"example-wrap\"><pre class=\"rust {}\">\n", class.unwrap_or_default());
}

fn write_code(out: &mut String, src: &str, edition: Edition) {
fn write_code(out: &mut Buffer, src: &str, edition: Edition) {
// This replace allows to fix how the code source with DOS backline characters is displayed.
let src = src.replace("\r\n", "\n");
Classifier::new(&src, edition).highlight(&mut |highlight| {
Expand All @@ -63,8 +61,8 @@ fn write_code(out: &mut String, src: &str, edition: Edition) {
});
}

fn write_footer(out: &mut String, playground_button: Option<&str>) {
write!(out, "</pre>{}</div>\n", playground_button.unwrap_or_default()).unwrap()
fn write_footer(out: &mut Buffer, playground_button: Option<&str>) {
write!(out, "</pre>{}</div>\n", playground_button.unwrap_or_default());
}

/// How a span of text is classified. Mostly corresponds to token kinds.
Expand Down Expand Up @@ -331,13 +329,13 @@ impl<'a> Classifier<'a> {

/// Called when we start processing a span of text that should be highlighted.
/// The `Class` argument specifies how it should be highlighted.
fn enter_span(out: &mut String, klass: Class) {
write!(out, "<span class=\"{}\">", klass.as_html()).unwrap()
fn enter_span(out: &mut Buffer, klass: Class) {
write!(out, "<span class=\"{}\">", klass.as_html());
}

/// Called at the end of a span of highlighted text.
fn exit_span(out: &mut String) {
write!(out, "</span>").unwrap()
fn exit_span(out: &mut Buffer) {
out.write_str("</span>");
}

/// Called for a span of text. If the text should be highlighted differently
Expand All @@ -351,10 +349,10 @@ fn exit_span(out: &mut String) {
/// ```
/// The latter can be thought of as a shorthand for the former, which is more
/// flexible.
fn string<T: Display>(out: &mut String, text: T, klass: Option<Class>) {
fn string<T: Display>(out: &mut Buffer, text: T, klass: Option<Class>) {
match klass {
None => write!(out, "{}", text).unwrap(),
Some(klass) => write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text).unwrap(),
None => write!(out, "{}", text),
Some(klass) => write!(out, "<span class=\"{}\">{}</span>", klass.as_html(), text),
}
}

Expand Down
9 changes: 5 additions & 4 deletions src/librustdoc/html/highlight/tests.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use super::write_code;
use crate::html::format::Buffer;
use expect_test::expect_file;
use rustc_span::edition::Edition;

Expand All @@ -18,9 +19,9 @@ const STYLE: &str = r#"
fn test_html_highlighting() {
let src = include_str!("fixtures/sample.rs");
let html = {
let mut out = String::new();
let mut out = Buffer::new();
write_code(&mut out, src, Edition::Edition2018);
format!("{}<pre><code>{}</code></pre>\n", STYLE, out)
format!("{}<pre><code>{}</code></pre>\n", STYLE, out.into_inner())
};
expect_file!["fixtures/sample.html"].assert_eq(&html);
}
Expand All @@ -30,7 +31,7 @@ fn test_dos_backline() {
let src = "pub fn foo() {\r\n\
println!(\"foo\");\r\n\
}\r\n";
let mut html = String::new();
let mut html = Buffer::new();
write_code(&mut html, src, Edition::Edition2018);
expect_file!["fixtures/dos_line.html"].assert_eq(&html);
expect_file!["fixtures/dos_line.html"].assert_eq(&html.into_inner());
}
17 changes: 11 additions & 6 deletions src/librustdoc/html/markdown.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,8 @@ use pulldown_cmark::{
html, BrokenLink, CodeBlockKind, CowStr, Event, LinkType, Options, Parser, Tag,
};

use super::format::Buffer;

#[cfg(test)]
mod tests;

Expand Down Expand Up @@ -235,9 +237,7 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
}
let lines = origtext.lines().filter_map(|l| map_line(l).for_html());
let text = lines.collect::<Vec<Cow<'_, str>>>().join("\n");
// insert newline to clearly separate it from the
// previous block so we can shorten the html output
let mut s = String::from("\n");

let playground_button = self.playground.as_ref().and_then(|playground| {
let krate = &playground.crate_name;
let url = &playground.url;
Expand Down Expand Up @@ -298,17 +298,22 @@ impl<'a, I: Iterator<Item = Event<'a>>> Iterator for CodeBlocks<'_, 'a, I> {
None
};

s.push_str(&highlight::render_with_highlighting(
// insert newline to clearly separate it from the
// previous block so we can shorten the html output
let mut s = Buffer::new();
s.push_str("\n");
highlight::render_with_highlighting(
&text,
&mut s,
Some(&format!(
"rust-example-rendered{}",
if let Some((_, class)) = tooltip { format!(" {}", class) } else { String::new() }
)),
playground_button.as_deref(),
tooltip,
edition,
));
Some(Event::Html(s.into()))
);
Some(Event::Html(s.into_inner().into()))
}
}

Expand Down
Loading

0 comments on commit d5cac19

Please sign in to comment.