styled_str/types/
lines.rs1use crate::StyledStr;
4
5#[derive(Debug)]
7pub struct Lines<'a> {
8 remainder: StyledStr<'a>,
9}
10
11impl<'a> Lines<'a> {
12 pub(super) fn new(str: StyledStr<'a>) -> Self {
13 Self { remainder: str }
14 }
15}
16
17impl<'a> Iterator for Lines<'a> {
18 type Item = StyledStr<'a>;
19
20 fn next(&mut self) -> Option<Self::Item> {
21 if self.remainder.is_empty() {
22 return None;
23 }
24
25 let text = self.remainder.text();
27 let next_pos = text.find('\n').map_or(text.len(), |pos| pos + 1);
28 let (mut line, remainder) = self.remainder.split_at(next_pos);
29 self.remainder = remainder;
30
31 if line.text.ends_with('\n') {
33 line.pop();
34 }
35 if line.text.ends_with('\r') {
36 line.pop();
37 }
38 Some(line)
39 }
40}
41
42#[cfg(test)]
43mod tests {
44 use alloc::vec::Vec;
45
46 use crate::styled;
47
48 #[test]
49 fn lines_basics() {
50 let str = styled!("[[red on white]]Test");
51 let lines: Vec<_> = str.lines().collect();
52 assert_eq!(lines, [str]);
53
54 let str_with_nl = styled!("[[red on white]]Test\n");
55 let lines: Vec<_> = str_with_nl.lines().collect();
56 assert_eq!(lines, [str]);
57
58 let str_with_nl = styled!("[[red on white]]Test\r\n");
59 let lines: Vec<_> = str_with_nl.lines().collect();
60 assert_eq!(lines, [str]);
61 }
62
63 #[test]
64 fn lines_with_multiline_text() {
65 let str = styled!("[[red on white]]Test\nHello, [[bold green]]world[[* -bold]]!");
66 let expected_lines = [
67 styled!("[[red on white]]Test"),
68 styled!("[[red on white]]Hello, [[bold green]]world[[green]]!"),
69 ];
70
71 let lines: Vec<_> = str.lines().collect();
72 assert_eq!(lines, expected_lines);
73 }
74
75 #[test]
76 fn styles_bordering_on_newlines() {
77 let str = styled!("[[red on white]]Test\n[[/]]Hello,[[bold green]]\nworld[[* -bold]]!\n");
78 let expected_lines = [
79 styled!("[[red on white]]Test"),
80 styled!("Hello,"),
81 styled!("[[bold green]]world[[green]]!"),
82 ];
83
84 let lines: Vec<_> = str.lines().collect();
85 assert_eq!(lines, expected_lines);
86 }
87}