aprender-common 0.34.0

Shared utilities for the Batuta stack: formatting, system info, display helpers
Documentation
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Display utilities: column alignment, truncation, and builder traits.
//!
//! Provides consistent text formatting for terminal output across the Batuta stack.

use crate::fmt;

// =============================================================================
// ENUMS
// =============================================================================

/// Truncation strategy for text that exceeds column width.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum TruncateStrategy {
    /// Truncate from the end with ellipsis: "very long te…"
    #[default]
    End,
    /// Truncate from the start with ellipsis: "…ong text here"
    Start,
    /// Truncate in the middle: "hel…orld"
    Middle,
    /// Smart path truncation: keeps filename, truncates directories
    Path,
}

/// Column alignment for formatted output.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ColumnAlign {
    /// Left-align text.
    #[default]
    Left,
    /// Right-align text (common for numbers).
    Right,
    /// Center-align text.
    Center,
}

// =============================================================================
// TRUNCATION
// =============================================================================

/// Truncate a string to fit within a maximum width.
///
/// **Guarantee**: Output length will NEVER exceed `max_width` characters.
///
/// # Examples
/// ```
/// use batuta_common::display::{truncate, TruncateStrategy};
/// assert_eq!(truncate("hello world", 8, TruncateStrategy::End), "hello w…");
/// assert_eq!(truncate("hello world", 8, TruncateStrategy::Start), "…o world");
/// assert_eq!(truncate("hello world", 8, TruncateStrategy::Middle), "hel…orld");
/// assert_eq!(truncate("short", 10, TruncateStrategy::End), "short");
/// ```
#[must_use]
pub fn truncate(s: &str, max_width: usize, strategy: TruncateStrategy) -> String {
    if max_width == 0 {
        return String::new();
    }

    let char_count = s.chars().count();

    if char_count <= max_width {
        return s.to_string();
    }

    if max_width == 1 {
        return "\u{2026}".to_string();
    }

    match strategy {
        TruncateStrategy::End => {
            let chars: String = s.chars().take(max_width - 1).collect();
            format!("{chars}\u{2026}")
        }
        TruncateStrategy::Start => {
            let chars: String = s.chars().skip(char_count - max_width + 1).collect();
            format!("\u{2026}{chars}")
        }
        TruncateStrategy::Middle => {
            let left_len = (max_width - 1) / 2;
            let right_len = max_width - 1 - left_len;
            let left: String = s.chars().take(left_len).collect();
            let right: String = s.chars().skip(char_count - right_len).collect();
            format!("{left}\u{2026}{right}")
        }
        TruncateStrategy::Path => truncate_path(s, max_width),
    }
}

/// Smart path truncation that preserves the filename.
///
/// **Guarantee**: Output length will NEVER exceed `max_width` characters.
///
/// # Examples
/// ```
/// use batuta_common::display::truncate_path;
/// assert_eq!(truncate_path("/home/user/documents/file.txt", 20), "/home/user…/file.txt");
/// assert_eq!(truncate_path("/a/b/c.txt", 20), "/a/b/c.txt");
/// ```
#[must_use]
pub fn truncate_path(path: &str, max_width: usize) -> String {
    if max_width == 0 {
        return String::new();
    }

    let char_count = path.chars().count();

    if char_count <= max_width {
        return path.to_string();
    }

    if let Some(last_sep) = path.rfind('/') {
        let filename = &path[last_sep..];
        let filename_len = filename.chars().count();

        if filename_len >= max_width {
            return truncate(path, max_width, TruncateStrategy::End);
        }

        let dir_space = max_width.saturating_sub(filename_len).saturating_sub(1);

        if dir_space == 0 {
            let result = format!("\u{2026}{filename}");
            if result.chars().count() <= max_width {
                return result;
            }
            return truncate(path, max_width, TruncateStrategy::End);
        }

        let dir = &path[..last_sep];
        let dir_chars: Vec<char> = dir.chars().collect();

        if dir_chars.len() <= dir_space {
            return path.to_string();
        }

        let truncated_dir: String = dir_chars.iter().take(dir_space).collect();
        let result = format!("{truncated_dir}\u{2026}{filename}");

        if result.chars().count() <= max_width {
            result
        } else {
            truncate(path, max_width, TruncateStrategy::End)
        }
    } else {
        truncate(path, max_width, TruncateStrategy::End)
    }
}

// =============================================================================
// COLUMN FORMATTING
// =============================================================================

/// Format text into a fixed-width column with alignment and truncation.
///
/// **Guarantee**: Output length will NEVER exceed `width` characters.
///
/// # Examples
/// ```
/// use batuta_common::display::{format_column, ColumnAlign, TruncateStrategy};
/// assert_eq!(format_column("test", 8, ColumnAlign::Left, TruncateStrategy::End), "test    ");
/// assert_eq!(format_column("test", 8, ColumnAlign::Right, TruncateStrategy::End), "    test");
/// assert_eq!(format_column("test", 8, ColumnAlign::Center, TruncateStrategy::End), "  test  ");
/// ```
#[must_use]
pub fn format_column(
    text: &str,
    width: usize,
    align: ColumnAlign,
    truncate_strategy: TruncateStrategy,
) -> String {
    let char_count = text.chars().count();

    let truncated = if char_count > width {
        truncate(text, width, truncate_strategy)
    } else {
        text.to_string()
    };

    let truncated_len = truncated.chars().count();
    let padding = width.saturating_sub(truncated_len);

    match align {
        ColumnAlign::Left => {
            let mut result = truncated;
            for _ in 0..padding {
                result.push(' ');
            }
            result
        }
        ColumnAlign::Right => {
            let mut result = String::with_capacity(width);
            for _ in 0..padding {
                result.push(' ');
            }
            result.push_str(&truncated);
            result
        }
        ColumnAlign::Center => {
            let left_pad = padding / 2;
            let right_pad = padding - left_pad;
            let mut result = String::with_capacity(width);
            for _ in 0..left_pad {
                result.push(' ');
            }
            result.push_str(&truncated);
            for _ in 0..right_pad {
                result.push(' ');
            }
            result
        }
    }
}

/// Format bytes into a fixed-width column (SI units, right-aligned).
///
/// # Examples
/// ```
/// use batuta_common::display::format_bytes_column;
/// assert_eq!(format_bytes_column(1500, 6), " 1.50K");
/// ```
#[must_use]
pub fn format_bytes_column(bytes: u64, width: usize) -> String {
    let formatted = fmt::format_bytes_si(bytes);
    format_column(&formatted, width, ColumnAlign::Right, TruncateStrategy::End)
}

/// Format a percentage into a fixed-width column (right-aligned).
///
/// # Examples
/// ```
/// use batuta_common::display::format_percent_column;
/// assert_eq!(format_percent_column(45.3, 7), "  45.3%");
/// ```
#[must_use]
pub fn format_percent_column(value: f64, width: usize) -> String {
    let formatted = fmt::format_percent(value);
    format_column(&formatted, width, ColumnAlign::Right, TruncateStrategy::End)
}

/// Format a number into a fixed-width column (right-aligned, with commas).
#[must_use]
pub fn format_number_column(n: u64, width: usize) -> String {
    let formatted = fmt::format_number(n);
    format_column(&formatted, width, ColumnAlign::Right, TruncateStrategy::End)
}

// =============================================================================
// BUILDER TRAIT
// =============================================================================

/// Trait for types that have configurable width/height dimensions.
///
/// Eliminates the 14+ identical `dimensions()` builder methods duplicated across
/// pmat visualization and trueno-viz chart types.
///
/// # Examples
/// ```
/// use batuta_common::display::WithDimensions;
///
/// struct Chart { width: u32, height: u32 }
///
/// impl WithDimensions for Chart {
///     fn set_dimensions(&mut self, width: u32, height: u32) {
///         self.width = width;
///         self.height = height;
///     }
/// }
///
/// let chart = Chart { width: 80, height: 24 }.dimensions(120, 40);
/// assert_eq!(chart.width, 120);
/// assert_eq!(chart.height, 40);
/// ```
pub trait WithDimensions: Sized {
    /// Set the width and height on this type.
    fn set_dimensions(&mut self, width: u32, height: u32);

    /// Builder method: set dimensions and return self.
    #[must_use]
    fn dimensions(mut self, width: u32, height: u32) -> Self {
        self.set_dimensions(width, height);
        self
    }
}

// =============================================================================
// CONVENIENCE: truncate_str (ASCII "..." suffix)
// =============================================================================

/// Truncate a string to `max_len` with ASCII `"..."` suffix.
///
/// This is a convenience wrapper for CLI output where ASCII ellipsis is
/// preferred over Unicode ellipsis. If the string fits, it is returned as-is.
///
/// # Examples
/// ```
/// use batuta_common::display::truncate_str;
/// assert_eq!(truncate_str("hello world", 8), "hello...");
/// assert_eq!(truncate_str("short", 10), "short");
/// assert_eq!(truncate_str("ab", 3), "ab");
/// assert_eq!(truncate_str("abcdef", 3), "...");
/// ```
#[must_use]
pub fn truncate_str(s: &str, max_len: usize) -> String {
    if s.len() <= max_len {
        return s.to_string();
    }
    if max_len <= 3 {
        return ".".repeat(max_len);
    }
    let end = s
        .char_indices()
        .nth(max_len - 3)
        .map_or(max_len - 3, |(i, _)| i);
    format!("{}...", &s[..end])
}

// =============================================================================
// TESTS
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    // --- Truncation ---

    #[test]
    fn test_truncate_short_string_unchanged() {
        assert_eq!(truncate("hello", 10, TruncateStrategy::End), "hello");
    }

    #[test]
    fn test_truncate_end() {
        assert_eq!(
            truncate("hello world", 8, TruncateStrategy::End),
            "hello w\u{2026}"
        );
    }

    #[test]
    fn test_truncate_start() {
        assert_eq!(
            truncate("hello world", 8, TruncateStrategy::Start),
            "\u{2026}o world"
        );
    }

    #[test]
    fn test_truncate_middle() {
        assert_eq!(
            truncate("hello world", 8, TruncateStrategy::Middle),
            "hel\u{2026}orld"
        );
    }

    #[test]
    fn test_truncate_zero_width() {
        assert_eq!(truncate("anything", 0, TruncateStrategy::End), "");
    }

    #[test]
    fn test_truncate_width_one() {
        assert_eq!(truncate("hello", 1, TruncateStrategy::End), "\u{2026}");
    }

    #[test]
    fn test_truncate_path_preserves_filename() {
        assert_eq!(
            truncate_path("/home/user/documents/file.txt", 20),
            "/home/user\u{2026}/file.txt"
        );
    }

    #[test]
    fn test_truncate_path_short_enough() {
        assert_eq!(truncate_path("/a/b/c.txt", 20), "/a/b/c.txt");
    }

    // --- Column formatting ---

    #[test]
    fn test_format_column_left() {
        assert_eq!(
            format_column("test", 8, ColumnAlign::Left, TruncateStrategy::End),
            "test    "
        );
    }

    #[test]
    fn test_format_column_right() {
        assert_eq!(
            format_column("test", 8, ColumnAlign::Right, TruncateStrategy::End),
            "    test"
        );
    }

    #[test]
    fn test_format_column_center() {
        assert_eq!(
            format_column("test", 8, ColumnAlign::Center, TruncateStrategy::End),
            "  test  "
        );
    }

    #[test]
    fn test_format_column_truncates() {
        assert_eq!(
            format_column(
                "very long text",
                8,
                ColumnAlign::Left,
                TruncateStrategy::End
            ),
            "very lo\u{2026}"
        );
    }

    #[test]
    fn test_format_bytes_column() {
        assert_eq!(format_bytes_column(1500, 6), " 1.50K");
    }

    #[test]
    fn test_format_percent_column() {
        assert_eq!(format_percent_column(45.3, 7), "  45.3%");
    }

    // --- truncate_str ---

    #[test]
    fn test_truncate_str_short_unchanged() {
        assert_eq!(truncate_str("hello", 10), "hello");
    }

    #[test]
    fn test_truncate_str_exact_fit() {
        assert_eq!(truncate_str("hello", 5), "hello");
    }

    #[test]
    fn test_truncate_str_with_ellipsis() {
        assert_eq!(truncate_str("hello world", 8), "hello...");
    }

    #[test]
    fn test_truncate_str_min_len() {
        assert_eq!(truncate_str("abcdef", 3), "...");
    }

    #[test]
    fn test_truncate_str_len_4() {
        assert_eq!(truncate_str("abcdef", 4), "a...");
    }

    #[test]
    fn test_truncate_str_empty() {
        assert_eq!(truncate_str("", 5), "");
    }

    // --- WithDimensions trait ---

    #[test]
    fn test_with_dimensions_trait() {
        struct TestWidget {
            width: u32,
            height: u32,
        }

        impl WithDimensions for TestWidget {
            fn set_dimensions(&mut self, width: u32, height: u32) {
                self.width = width;
                self.height = height;
            }
        }

        let w = TestWidget {
            width: 0,
            height: 0,
        }
        .dimensions(120, 40);
        assert_eq!(w.width, 120);
        assert_eq!(w.height, 40);
    }
}