BlueGit

timfa posprint

Files

posprint / src / align_row.rs

align_row.rs

align_row.rs 5.5 KiB Download Raw
1//! Space-pad multi-align text onto one Font A column row.
2//!
3//! ESC/POS `ESC a` justifies whole lines only; same-line `:left:` + `:right:`
4//! (and optional `:center:`) must be simulated with spaces to `chars_per_line`.
5
6use crate::dsl::Align;
7
8#[derive(Debug, Clone, Default, PartialEq, Eq)]
9pub struct AlignedColumns {
10 pub left: Option<String>,
11 pub center: Option<String>,
12 pub right: Option<String>,
13}
14
15/// Map ordered `(Align, text)` parts into Left / Center / Right columns.
16/// Later segments for the same align win (silent replace).
17pub fn columns_from_parts(parts: &[(Align, String)]) -> AlignedColumns {
18 let mut cols = AlignedColumns::default();
19 for (align, text) in parts {
20 let text = text.clone();
21 match align {
22 Align::Left => cols.left = Some(text),
23 Align::Center => cols.center = Some(text),
24 Align::Right => cols.right = Some(text),
25 }
26 }
27 cols
28}
29
30/// Build one fixed-width line, or `None` when content cannot fit without overlap.
31pub fn layout_aligned_row(
32 left: Option<&str>,
33 center: Option<&str>,
34 right: Option<&str>,
35 cols: usize,
36) -> Option<String> {
37 if cols == 0 {
38 return None;
39 }
40 let left = left.unwrap_or("");
41 let center = center.unwrap_or("");
42 let right = right.unwrap_or("");
43 let left_len = left.chars().count();
44 let center_len = center.chars().count();
45 let right_len = right.chars().count();
46
47 if left_len + center_len + right_len > cols {
48 return None;
49 }
50
51 // Fast path: classic label … amount (no center).
52 if center_len == 0 {
53 let gap = cols - left_len - right_len;
54 return Some(format!("{left}{}{right}", " ".repeat(gap)));
55 }
56
57 let mut buf = vec![' '; cols];
58 for (i, ch) in left.chars().enumerate() {
59 buf[i] = ch;
60 }
61 if right_len > 0 {
62 let start = cols - right_len;
63 for (i, ch) in right.chars().enumerate() {
64 buf[start + i] = ch;
65 }
66 }
67
68 let center_start = (cols - center_len) / 2;
69 for (i, ch) in center.chars().enumerate() {
70 let idx = center_start + i;
71 // Overlaps left or right region → cannot pad safely.
72 if idx < left_len || (right_len > 0 && idx >= cols - right_len) {
73 return None;
74 }
75 if buf[idx] != ' ' {
76 return None;
77 }
78 buf[idx] = ch;
79 }
80
81 Some(buf.into_iter().collect())
82}
83
84/// Prefer a single padded line; on overflow return Left → Center → Right lines.
85pub fn layout_aligned_row_or_lines(columns: &AlignedColumns, cols: usize) -> Vec<(Align, String)> {
86 let left = columns.left.as_deref();
87 let center = columns.center.as_deref();
88 let right = columns.right.as_deref();
89
90 if let Some(line) = layout_aligned_row(left, center, right, cols) {
91 return vec![(Align::Left, line)];
92 }
93
94 let mut lines = Vec::new();
95 if let Some(t) = columns.left.as_ref().filter(|s| !s.is_empty()) {
96 lines.push((Align::Left, t.clone()));
97 }
98 if let Some(t) = columns.center.as_ref().filter(|s| !s.is_empty()) {
99 lines.push((Align::Center, t.clone()));
100 }
101 if let Some(t) = columns.right.as_ref().filter(|s| !s.is_empty()) {
102 lines.push((Align::Right, t.clone()));
103 }
104 lines
105}
106
107#[cfg(test)]
108mod tests {
109 use super::*;
110
111 #[test]
112 fn left_right_gap_matches_cols() {
113 let line = layout_aligned_row(Some("appel"), None, Some("10"), 32).unwrap();
114 assert_eq!(line.chars().count(), 32);
115 assert!(line.starts_with("appel"));
116 assert!(line.ends_with("10"));
117 assert_eq!(&line[5..30], &" ".repeat(25));
118 }
119
120 #[test]
121 fn right_then_left_parts_normalize_order() {
122 let cols = columns_from_parts(&[
123 (Align::Right, "10".into()),
124 (Align::Left, "appel".into()),
125 ]);
126 assert_eq!(cols.left.as_deref(), Some("appel"));
127 assert_eq!(cols.right.as_deref(), Some("10"));
128 let line = layout_aligned_row_or_lines(&cols, 32);
129 assert_eq!(line.len(), 1);
130 assert_eq!(line[0].0, Align::Left);
131 assert!(line[0].1.starts_with("appel"));
132 assert!(line[0].1.ends_with("10"));
133 }
134
135 #[test]
136 fn longer_right_shortens_gap() {
137 let short = layout_aligned_row(Some("A"), None, Some("1"), 10).unwrap();
138 let long = layout_aligned_row(Some("A"), None, Some("12345"), 10).unwrap();
139 assert_eq!(short.chars().count(), 10);
140 assert_eq!(long.chars().count(), 10);
141 assert!(short.contains(" ")); // 8 spaces
142 assert_eq!(&long[1..5], " "); // 4 spaces
143 }
144
145 #[test]
146 fn overflow_falls_back_to_separate_lines() {
147 let cols = AlignedColumns {
148 left: Some("AAAAAAAAAA".into()),
149 center: None,
150 right: Some("BBBBBBBBBBBB".into()),
151 };
152 let lines = layout_aligned_row_or_lines(&cols, 10);
153 assert_eq!(lines.len(), 2);
154 assert_eq!(lines[0], (Align::Left, "AAAAAAAAAA".into()));
155 assert_eq!(lines[1], (Align::Right, "BBBBBBBBBBBB".into()));
156 }
157
158 #[test]
159 fn center_between_left_and_right() {
160 let line = layout_aligned_row(Some("L"), Some("MID"), Some("R"), 11).unwrap();
161 assert_eq!(line, "L MID R");
162 }
163
164 #[test]
165 fn center_overlap_with_left_returns_none() {
166 assert!(layout_aligned_row(Some("LEFTSIDE"), Some("CENTER"), None, 12).is_none());
167 }
168}