1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
|
use std::fmt;
pub struct HelpMessage {
title: &'static str,
segments: Vec<HelpSegment>,
}
impl fmt::Display for HelpMessage {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}", self.title.to_uppercase())?;
for seg in &self.segments {
write!(f, "{seg}")?;
}
Ok(())
}
}
pub struct HelpSegment {
head: &'static str,
body: &'static str,
}
impl fmt::Display for HelpSegment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "{}:", self.head)?;
const INDENT: IndentStr<4> = IndentStr::new();
const LINE_LEN: usize = 80 - INDENT.len();
let mut curr = self.body;
loop {
let line_len = curr.len().min(LINE_LEN);
let line = &curr[..line_len];
curr = &curr[line_len..];
writeln!(f, "{INDENT}{line}")?;
if curr.len() == 0 {
break Ok(());
}
}
}
}
struct IndentStr<const N: usize> {
arr: [u8; N],
}
impl<const N: usize> IndentStr<N> {
pub const fn new() -> Self {
IndentStr {
arr: [' ' as u8; N],
}
}
pub const fn len(&self) -> usize {
N
}
pub const fn as_str(&self) -> &str {
unsafe { std::str::from_utf8_unchecked(&self.arr) }
}
}
impl<const N: usize> Default for IndentStr<N> {
fn default() -> Self {
Self::new()
}
}
impl<const N: usize> fmt::Display for IndentStr<N> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let ident = unsafe { std::str::from_utf8_unchecked(&self.arr) };
write!(f, "{ident}")
}
}
#[cfg(test)]
mod test {
use crate::helpgen::HelpSegment;
#[test]
fn segment() {
let segment = HelpSegment {
head: "head",
body: "body of the help string",
};
let expected = "head:\n body of the help string\n";
assert_eq!(segment.to_string(), expected)
}
#[test]
fn segment_longline() {
let segment = HelpSegment {
head: "head",
body: "01234567890123456789012345678901234567890123456789012345678901234567890123456789",
};
let expected = "head:\n 0123456789012345678901234567890123456789012345678901234567890123456789012345\n 6789\n";
assert_eq!(segment.to_string(), expected)
}
}
|