markdown_builder/types/
paragraph.rs

1use std::fmt;
2
3/// A markdown paragraph.
4///
5/// A paragraph is a continuous text that is visually separated from its
6/// surrounding markdown elements. Word wrapped at 80 characters.
7
8#[derive(Clone, Debug)]
9pub struct Paragraph {
10    /// The text inside the paragraph.
11    pub text: String,
12}
13
14impl Paragraph {
15    /// Creates a new paragraph with the given text.
16    pub fn from(text: impl Into<String>) -> Self {
17        Self { text: text.into() }
18    }
19}
20
21impl fmt::Display for Paragraph {
22    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
23        let mut current_size = 0;
24
25        for (index, word) in self.text.split(" ").enumerate() {
26            if current_size + word.len() > 80 {
27                current_size = 0;
28                write!(f, "\n{}", word)?;
29            } else {
30                current_size += word.len();
31                if index == 0 {
32                    write!(f, "{}", word,)?;
33                } else {
34                    write!(f, " {}", word,)?;
35                };
36            }
37        }
38
39        write!(f, "\n")?;
40
41        Ok(())
42    }
43}
44
45#[cfg(test)]
46mod tests {
47    use super::*;
48
49    #[test]
50    fn test_display() {
51        assert_eq!(Paragraph::from("Hello world").to_string(), "Hello world\n");
52    }
53
54    #[test]
55    fn test_word_wrapping() {
56        assert_eq!(
57			Paragraph::from(
58				"Markdown Builder is a Rustlang crate by Erb3, which lets you create markdown documents. It now supports word wrapping!"
59			).to_string(),
60			"Markdown Builder is a Rustlang crate by Erb3, which lets you create markdown documents. It now\nsupports word wrapping!\n"
61		);
62    }
63}