Debian Codegraph @

src/format.rs

raw symbols SCIP
1 use std::convert::{TryFrom, TryInto};
2
3 use regex::Regex;
4 use smol_str::SmolStr;
5 use unicode_segmentation::UnicodeSegmentation;
6
7 use crate::features::side_by_side::ansifill::ODD_PAD_CHAR;
8
9 #[derive(Debug, PartialEq, Eq)]
10 pub enum Placeholder<'a> {
11 NumberMinus,
12 NumberPlus,
13 Str(&'a str),
14 }
15
16 impl<'a> TryFrom<Option<&'a str>> for Placeholder<'a> {
17 type Error = ();
18 fn try_from(from: Option<&'a str>) -> Result<Self, Self::Error> {
19 match from {
20 Some("nm") => Ok(Placeholder::NumberMinus),
21 Some("np") => Ok(Placeholder::NumberPlus),
22 Some(placeholder) => Ok(Placeholder::Str(placeholder)),
23 _ => Err(()),
24 }
25 }
26 }
27
28 #[derive(Debug, Copy, Clone, PartialEq, Eq)]
29 pub enum Align {
30 Left,
31 Center,
32 Right,
33 }
34
35 impl TryFrom<Option<&str>> for Align {
36 type Error = ();
37 fn try_from(from: Option<&str>) -> Result<Self, Self::Error> {
38 // inlined format args are not supported for `debug_assert` with edition 2018.
39 #[allow(clippy::uninlined_format_args)]
40 match from {
41 Some("<") => Ok(Align::Left),
42 Some(">") => Ok(Align::Right),
43 Some("^") => Ok(Align::Center),
44 Some(alignment) => {
45 debug_assert!(false, "Unknown Alignment: {}", alignment);
46 Err(())
47 }
48 None => Err(()),
49 }
50 }
51 }
52
53 #[derive(Debug, PartialEq, Eq, Clone)]
54 pub struct FormatStringPlaceholderDataAnyPlaceholder<T> {
55 pub prefix: SmolStr,
56 pub prefix_len: usize,
57 pub placeholder: Option<T>,
58 pub alignment_spec: Option<Align>,
59 pub width: Option<usize>,
60 pub precision: Option<usize>,
61 pub fmt_type: SmolStr,
62 pub suffix: SmolStr,
63 pub suffix_len: usize,
64 }
65
66 impl<T> Default for FormatStringPlaceholderDataAnyPlaceholder<T> {
67 fn default() -> Self {
68 Self {
69 prefix: SmolStr::default(),
70 prefix_len: 0,
71 placeholder: None,
72 alignment_spec: None,
73 width: None,
74 precision: None,
75 fmt_type: SmolStr::default(),
76 suffix: SmolStr::default(),
77 suffix_len: 0,
78 }
79 }
80 }
81
82 impl<T> FormatStringPlaceholderDataAnyPlaceholder<T> {
83 pub fn only_string(s: &str) -> Self {
84 Self {
85 suffix: s.into(),
86 suffix_len: s.graphemes(true).count(),
87 ..Self::default()
88 }
89 }
90 }
91
92 pub type FormatStringPlaceholderData<'a> =
93 FormatStringPlaceholderDataAnyPlaceholder<Placeholder<'a>>;
94
95 pub type FormatStringSimple = FormatStringPlaceholderDataAnyPlaceholder<()>;
96
97 impl FormatStringPlaceholderData<'_> {
98 pub fn width(&self, hunk_max_line_number_width: usize) -> (usize, usize) {
99 // Only if Some(placeholder) is present will there be a number formatted
100 // by this placeholder, if not width is also None.
101 (
102 self.prefix_len
103 + std::cmp::max(
104 self.placeholder
105 .as_ref()
106 .map_or(0, |_| hunk_max_line_number_width),
107 self.width.unwrap_or(0),
108 ),
109 self.suffix_len,
110 )
111 }
112 pub fn into_simple(self) -> FormatStringSimple {
113 FormatStringSimple {
114 prefix: self.prefix,
115 prefix_len: self.prefix_len,
116 placeholder: None,
117 alignment_spec: self.alignment_spec,
118 width: self.width,
119 precision: self.precision,
120 fmt_type: self.fmt_type,
121 suffix: self.suffix,
122 suffix_len: self.suffix_len,
123 }
124 }
125 }
126
127 pub type FormatStringData<'a> = Vec<FormatStringPlaceholderData<'a>>;
128
129 pub fn make_placeholder_regex(labels: &[&str]) -> Regex {
130 Regex::new(&format!(
131 r"(?x)
132 \{{
133 ({}) # 1: Placeholder labels
134 (?: # Start optional format spec (non-capturing)
135 : # Literal colon
136 (?: # Start optional fill/alignment spec (non-capturing)
137 ([^<^>])? # 2: Optional fill character (ignored)
138 ([<^>]) # 3: Alignment spec
139 )? #
140 (\d+)? # 4: Width (optional)
141 (?: # Start optional precision (non-capturing)
142 \.(\d+) # 5: Precision
143 )? #
144 (?: # Start optional format type (non-capturing)
145 _?([A-Za-z][0-9A-Za-z_-]*) # 6: Format type, optional leading _
146 )? #
147 )? #
148 \}}
149 ",
150 labels.join("|")
151 ))
152 .unwrap()
153 }
154
155 // The resulting vector is never empty
156 pub fn parse_line_number_format<'a>(
157 format_string: &'a str,
158 placeholder_regex: &Regex,
159 mut prefix_with_space: bool,
160 ) -> FormatStringData<'a> {
161 let mut format_data = Vec::new();
162 let mut offset = 0;
163
164 let mut expand_first_prefix = |prefix: SmolStr| {
165 // Only prefix the first placeholder with a space, also see `UseFullPanelWidth`
166 if prefix_with_space {
167 let prefix = SmolStr::new(format!("{ODD_PAD_CHAR}{prefix}"));
168 prefix_with_space = false;
169 prefix
170 } else {
171 prefix
172 }
173 };
174
175 for captures in placeholder_regex.captures_iter(format_string) {
176 let match_ = captures.get(0).unwrap();
177 let prefix = SmolStr::new(&format_string[offset..match_.start()]);
178 let prefix = expand_first_prefix(prefix);
179 let prefix_len = prefix.graphemes(true).count();
180 let suffix = SmolStr::new(&format_string[match_.end()..]);
181 let suffix_len = suffix.graphemes(true).count();
182 format_data.push(FormatStringPlaceholderData {
183 prefix,
184 prefix_len,
185 placeholder: captures.get(1).map(|m| m.as_str()).try_into().ok(),
186 alignment_spec: captures.get(3).map(|m| m.as_str()).try_into().ok(),
187 width: captures.get(4).map(|m| {
188 m.as_str()
189 .parse()
190 .unwrap_or_else(|_| panic!("Invalid width in format string: {}", format_string))
191 }),
192 precision: captures.get(5).map(|m| {
193 m.as_str().parse().unwrap_or_else(|_| {
194 panic!("Invalid precision in format string: {}", format_string)
195 })
196 }),
197 fmt_type: captures
198 .get(6)
199 .map(|m| SmolStr::from(m.as_str()))
200 .unwrap_or_default(),
201 suffix,
202 suffix_len,
203 });
204 offset = match_.end();
205 }
206 if offset == 0 {
207 let prefix = SmolStr::new("");
208 let prefix = expand_first_prefix(prefix);
209 let prefix_len = prefix.graphemes(true).count();
210 // No placeholders
211 format_data.push(FormatStringPlaceholderData {
212 prefix,
213 prefix_len,
214 suffix: SmolStr::new(format_string),
215 suffix_len: format_string.graphemes(true).count(),
216 ..Default::default()
217 })
218 }
219
220 format_data
221 }
222
223 pub trait CenterRightNumbers {
224 // There is no such thing as "Center Align" with discrete terminal cells. In
225 // some cases a decision has to be made whether to use the left or the right
226 // cell, e.g. when centering one char in 4 cells: "_X__" or "__X_".
227 //
228 // The format!() center/^ default is center left, but when padding numbers
229 // these are now aligned to the center right by having this trait return " "
230 // instead of "". This is prepended to the format string. In the case of " "
231 // the trailing " " must then be removed so everything is shifted to the right.
232 // This assumes no special padding characters, i.e. the default of space.
233 fn center_right_space(&self, alignment: Align, width: usize) -> &'static str;
234 }
235
236 impl CenterRightNumbers for &str {
237 fn center_right_space(&self, _alignment: Align, _width: usize) -> &'static str {
238 // Disables center-right formatting and aligns strings center-left
239 ""
240 }
241 }
242
243 impl CenterRightNumbers for String {
244 fn center_right_space(&self, alignment: Align, width: usize) -> &'static str {
245 self.as_str().center_right_space(alignment, width)
246 }
247 }
248
249 impl CenterRightNumbers for &std::borrow::Cow<'_, str> {
250 fn center_right_space(&self, alignment: Align, width: usize) -> &'static str {
251 self.as_ref().center_right_space(alignment, width)
252 }
253 }
254
255 // Returns the base-10 width of `n`, i.e. `floor(log10(n)) + 1` and 0 is treated as 1.
256 pub fn log10_plus_1(mut n: usize) -> usize {
257 let mut len = 0;
258 // log10 for integers is only in nightly and this is faster than
259 // casting to f64 and back.
260 loop {
261 if n <= 9 {
262 break len + 1;
263 }
264 if n <= 99 {
265 break len + 2;
266 }
267 if n <= 999 {
268 break len + 3;
269 }
270 if n <= 9999 {
271 break len + 4;
272 }
273
274 len += 4;
275 n /= 10000;
276 }
277 }
278
279 impl CenterRightNumbers for usize {
280 fn center_right_space(&self, alignment: Align, width: usize) -> &'static str {
281 if alignment != Align::Center {
282 return "";
283 }
284
285 let width_of_number = log10_plus_1(*self);
286 if width > width_of_number && (width % 2 != width_of_number % 2) {
287 " "
288 } else {
289 ""
290 }
291 }
292 }
293
294 // Note that in this case of a string `s`, `precision` means "max width".
295 // See https://doc.rust-lang.org/std/fmt/index.html
296 pub fn pad<T: std::fmt::Display + CenterRightNumbers>(
297 s: T,
298 width: usize,
299 alignment: Align,
300 precision: Option<usize>,
301 ) -> String {
302 let space = s.center_right_space(alignment, width);
303 let mut result = match precision {
304 None => match alignment {
305 Align::Left => format!("{space}{s:<width$}"),
306 Align::Center => format!("{space}{s:^width$}"),
307 Align::Right => format!("{space}{s:>width$}"),
308 },
309 Some(precision) => match alignment {
310 Align::Left => format!("{space}{s:<width$.precision$}"),
311 Align::Center => format!("{space}{s:^width$.precision$}"),
312 Align::Right => format!("{space}{s:>width$.precision$}"),
313 },
314 };
315 if space == " " {
316 result.pop();
317 }
318 result
319 }
320
321 #[cfg(test)]
322 mod tests {
323 use super::*;
324
325 #[test]
326 fn test_log10_plus_1() {
327 let nrs = [
328 1, 9, 10, 11, 99, 100, 101, 999, 1_000, 1_001, 9_999, 10_000, 10_001, 99_999, 100_000,
329 100_001, 0,
330 ];
331 let widths = [1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 1];
332 for (n, w) in nrs.iter().zip(widths.iter()) {
333 assert_eq!(log10_plus_1(*n), *w);
334 }
335
336 #[cfg(target_pointer_width = "64")]
337 {
338 assert_eq!(log10_plus_1(744_073_709_551_615), 5 * 3);
339 assert_eq!(log10_plus_1(18_446_744_073_709_551_615), 2 + 6 * 3);
340 }
341 }
342
343 #[test]
344 fn test_center_right_space_trait() {
345 assert_eq!("abc".center_right_space(Align::Center, 6), "");
346 assert_eq!("abc".center_right_space(Align::Center, 7), "");
347 assert_eq!(123.center_right_space(Align::Center, 6), " ");
348 assert_eq!(123.center_right_space(Align::Center, 7), "");
349 }
350
351 #[test]
352 fn test_pad_center_align() {
353 assert_eq!(pad("abc", 6, Align::Center, None), " abc ");
354 assert_eq!(pad(1, 1, Align::Center, None), "1");
355 assert_eq!(pad(1, 2, Align::Center, None), " 1");
356 assert_eq!(pad(1, 3, Align::Center, None), " 1 ");
357 assert_eq!(pad(1, 4, Align::Center, None), " 1 ");
358
359 assert_eq!(pad(1001, 3, Align::Center, None), "1001");
360 assert_eq!(pad(1001, 4, Align::Center, None), "1001");
361 assert_eq!(pad(1001, 5, Align::Center, None), " 1001");
362
363 assert_eq!(pad(1, 4, Align::Left, None), "1 ");
364 assert_eq!(pad(1, 4, Align::Right, None), " 1");
365 assert_eq!(pad("abc", 5, Align::Left, None), "abc ");
366 assert_eq!(pad("abc", 5, Align::Right, None), " abc");
367 }
368
369 #[test]
370 fn test_placeholder_with_notype() {
371 let regex = make_placeholder_regex(&["placeholder"]);
372 assert_eq!(
373 parse_line_number_format("{placeholder:^4}", &regex, false),
374 vec![FormatStringPlaceholderData {
375 placeholder: Some(Placeholder::Str("placeholder")),
376 alignment_spec: Some(Align::Center),
377 width: Some(4),
378 ..Default::default()
379 }]
380 );
381 }
382
383 #[test]
384 fn test_placeholder_with_only_type_dash_number() {
385 let regex = make_placeholder_regex(&["placeholder"]);
386 assert_eq!(
387 parse_line_number_format("{placeholder:a_type-b-12}", &regex, false),
388 vec![FormatStringPlaceholderData {
389 placeholder: Some(Placeholder::Str("placeholder")),
390 fmt_type: "a_type-b-12".into(),
391 ..Default::default()
392 }]
393 );
394 }
395
396 #[test]
397 fn test_placeholder_with_empty_formatting() {
398 let regex = make_placeholder_regex(&["placeholder"]);
399 assert_eq!(
400 parse_line_number_format("{placeholder:}", &regex, false),
401 vec![FormatStringPlaceholderData {
402 placeholder: Some(Placeholder::Str("placeholder")),
403 ..Default::default()
404 }]
405 );
406 }
407
408 #[test]
409 fn test_placeholder_with_type_and_more() {
410 let regex = make_placeholder_regex(&["placeholder"]);
411 assert_eq!(
412 parse_line_number_format("prefix {placeholder:<15.14type} suffix", &regex, false),
413 vec![FormatStringPlaceholderData {
414 prefix: "prefix ".into(),
415 placeholder: Some(Placeholder::Str("placeholder")),
416 alignment_spec: Some(Align::Left),
417 width: Some(15),
418 precision: Some(14),
419 fmt_type: "type".into(),
420 suffix: " suffix".into(),
421 prefix_len: 7,
422 suffix_len: 7,
423 }]
424 );
425
426 assert_eq!(
427 parse_line_number_format("prefix {placeholder:<15.14_type} suffix", &regex, false),
428 vec![FormatStringPlaceholderData {
429 prefix: "prefix ".into(),
430 placeholder: Some(Placeholder::Str("placeholder")),
431 alignment_spec: Some(Align::Left),
432 width: Some(15),
433 precision: Some(14),
434 fmt_type: "type".into(),
435 suffix: " suffix".into(),
436 prefix_len: 7,
437 suffix_len: 7,
438 }]
439 );
440 }
441
442 #[test]
443 fn test_placeholder_regex() {
444 let regex = make_placeholder_regex(&["placeholder"]);
445 assert_eq!(
446 parse_line_number_format("prefix {placeholder:<15.14} suffix", &regex, false),
447 vec![FormatStringPlaceholderData {
448 prefix: "prefix ".into(),
449 placeholder: Some(Placeholder::Str("placeholder")),
450 alignment_spec: Some(Align::Left),
451 width: Some(15),
452 precision: Some(14),
453 fmt_type: SmolStr::default(),
454 suffix: " suffix".into(),
455 prefix_len: 7,
456 suffix_len: 7,
457 }]
458 );
459 }
460
461 #[test]
462 fn test_placeholder_regex_empty_placeholder() {
463 let regex = make_placeholder_regex(&[""]);
464 assert_eq!(
465 parse_line_number_format("prefix {:<15.14} suffix", &regex, false),
466 vec![FormatStringPlaceholderData {
467 prefix: "prefix ".into(),
468 placeholder: Some(Placeholder::Str("")),
469 alignment_spec: Some(Align::Left),
470 width: Some(15),
471 precision: Some(14),
472 fmt_type: SmolStr::default(),
473 suffix: " suffix".into(),
474 prefix_len: 7,
475 suffix_len: 7,
476 }]
477 );
478 }
479 #[test]
480 fn test_format_string_simple() {
481 let regex = make_placeholder_regex(&["foo"]);
482 let f = parse_line_number_format("prefix {foo:<15.14} suffix", &regex, false);
483
484 assert_eq!(
485 f,
486 vec![FormatStringPlaceholderData {
487 prefix: "prefix ".into(),
488 placeholder: Some(Placeholder::Str("foo")),
489 alignment_spec: Some(Align::Left),
490 width: Some(15),
491 precision: Some(14),
492 fmt_type: SmolStr::default(),
493 suffix: " suffix".into(),
494 prefix_len: 7,
495 suffix_len: 7,
496 }]
497 );
498 let simple: Vec<_> = f
499 .into_iter()
500 .map(FormatStringPlaceholderData::into_simple)
501 .collect();
502 assert_eq!(
503 simple,
504 vec![FormatStringSimple {
505 prefix: "prefix ".into(),
506 placeholder: None,
507 alignment_spec: Some(Align::Left),
508 width: Some(15),
509 precision: Some(14),
510 fmt_type: SmolStr::default(),
511 suffix: " suffix".into(),
512 prefix_len: 7,
513 suffix_len: 7,
514 }]
515 );
516 }
517
518 #[test]
519 fn test_line_number_format_only_string() {
520 let f = FormatStringSimple::only_string("abc");
521 assert_eq!(f.suffix_len, 3);
522 }
523
524 #[test]
525 fn test_parse_line_number_format_not_empty() {
526 let regex = make_placeholder_regex(&["abc"]);
527 assert!(!parse_line_number_format(" abc ", &regex, false).is_empty());
528 assert!(!parse_line_number_format("", &regex, false).is_empty());
529 let regex = make_placeholder_regex(&[""]);
530 assert!(!parse_line_number_format(" abc ", &regex, false).is_empty());
531 assert!(!parse_line_number_format("", &regex, false).is_empty());
532 }
533 }