]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/src/attr/doc_comment.rs
Rollup merge of #88601 - ibraheemdev:termination-result-infallible, r=yaahc
[rust.git] / src / tools / rustfmt / src / attr / doc_comment.rs
1 use crate::comment::CommentStyle;
2 use std::fmt::{self, Display};
3
4 /// Formats a string as a doc comment using the given [`CommentStyle`].
5 #[derive(new)]
6 pub(super) struct DocCommentFormatter<'a> {
7     literal: &'a str,
8     style: CommentStyle<'a>,
9 }
10
11 impl Display for DocCommentFormatter<'_> {
12     fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
13         let opener = self.style.opener().trim_end();
14         let mut lines = self.literal.lines().peekable();
15
16         // Handle `#[doc = ""]`.
17         if lines.peek().is_none() {
18             return write!(formatter, "{}", opener);
19         }
20
21         while let Some(line) = lines.next() {
22             let is_last_line = lines.peek().is_none();
23             if is_last_line {
24                 write!(formatter, "{}{}", opener, line)?;
25             } else {
26                 writeln!(formatter, "{}{}", opener, line)?;
27             }
28         }
29         Ok(())
30     }
31 }
32
33 #[cfg(test)]
34 mod tests {
35     use super::*;
36
37     #[test]
38     fn literal_controls_leading_spaces() {
39         test_doc_comment_is_formatted_correctly(
40             "    Lorem ipsum",
41             "///    Lorem ipsum",
42             CommentStyle::TripleSlash,
43         );
44     }
45
46     #[test]
47     fn single_line_doc_comment_is_formatted_correctly() {
48         test_doc_comment_is_formatted_correctly(
49             "Lorem ipsum",
50             "///Lorem ipsum",
51             CommentStyle::TripleSlash,
52         );
53     }
54
55     #[test]
56     fn multi_line_doc_comment_is_formatted_correctly() {
57         test_doc_comment_is_formatted_correctly(
58             "Lorem ipsum\nDolor sit amet",
59             "///Lorem ipsum\n///Dolor sit amet",
60             CommentStyle::TripleSlash,
61         );
62     }
63
64     #[test]
65     fn whitespace_within_lines_is_preserved() {
66         test_doc_comment_is_formatted_correctly(
67             " Lorem ipsum \n Dolor sit amet ",
68             "/// Lorem ipsum \n/// Dolor sit amet ",
69             CommentStyle::TripleSlash,
70         );
71     }
72
73     fn test_doc_comment_is_formatted_correctly(
74         literal: &str,
75         expected_comment: &str,
76         style: CommentStyle<'_>,
77     ) {
78         assert_eq!(
79             expected_comment,
80             format!("{}", DocCommentFormatter::new(literal, style))
81         );
82     }
83 }