termosaic 0.2.2

Semantic, structured output for human, machine-text, and opaque-byte destinations
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
//! Ready-made semantic formatters for common terminal content.

use std::borrow::Cow;
use std::fmt;
use std::num::NonZeroU8;

use crate::{Doc, TextLayout};

/// A quantity of bytes that renders itself at a human-readable scale.
///
/// The value is carried exactly as a byte count; scaling happens only at
/// display time, so no precision is lost by storing a size in this type.
/// Machine-readable output emits the underlying `u64` from
/// [`ByteSize::as_u64`].
///
/// Units advance by 1024, matching `du -h` and `ls -h`, and are labelled `B`,
/// `KB`, `MB`, `GB`, `TB`, `PB`, `EB`. The labels are the customary ones
/// rather than the IEC `KiB`/`MiB` spellings; the scale is binary either way.
///
/// ```
/// use termosaic::formatters::ByteSize;
///
/// assert_eq!(ByteSize::bytes(36_828_222_525).to_string(), "34.30 GB");
/// assert_eq!(ByteSize::bytes(0).to_string(), "0 B");
/// assert_eq!(ByteSize::bytes(1023).to_string(), "1023 B");
/// assert_eq!(ByteSize::bytes(1024).to_string(), "1.00 KB");
/// ```
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub struct ByteSize(u64);

const SCALE: u64 = 1024;
const UNITS: [&str; 7] = ["B", "KB", "MB", "GB", "TB", "PB", "EB"];

impl ByteSize {
    pub const fn bytes(value: u64) -> Self {
        Self(value)
    }

    /// Build from a count of 1024-byte units. `None` on overflow past `u64`.
    pub const fn kilobytes(value: u64) -> Option<Self> {
        Self::scaled(value, 1)
    }

    /// Build from a count of 1024² units. `None` on overflow past `u64`.
    pub const fn megabytes(value: u64) -> Option<Self> {
        Self::scaled(value, 2)
    }

    /// Build from a count of 1024³ units. `None` on overflow past `u64`.
    pub const fn gigabytes(value: u64) -> Option<Self> {
        Self::scaled(value, 3)
    }

    /// Build from a count of 1024⁴ units. `None` on overflow past `u64`.
    pub const fn terabytes(value: u64) -> Option<Self> {
        Self::scaled(value, 4)
    }

    /// Build from a count of 1024⁵ units. `None` on overflow past `u64`.
    pub const fn petabytes(value: u64) -> Option<Self> {
        Self::scaled(value, 5)
    }

    /// The exact byte count. This is the value to serialize.
    pub const fn as_u64(self) -> u64 {
        self.0
    }

    const fn scaled(value: u64, exponent: u32) -> Option<Self> {
        match SCALE.checked_pow(exponent) {
            Some(multiplier) => match value.checked_mul(multiplier) {
                Some(bytes) => Some(Self(bytes)),
                None => None,
            },
            None => None,
        }
    }
}

impl From<u64> for ByteSize {
    fn from(value: u64) -> Self {
        Self(value)
    }
}

impl From<ByteSize> for u64 {
    fn from(value: ByteSize) -> Self {
        value.0
    }
}

impl fmt::Display for ByteSize {
    /// Renders whole bytes below 1 KB and two decimal places above it.
    ///
    /// A fraction of a byte has no meaning, so the smallest unit is printed as
    /// an integer. All arithmetic is integer arithmetic: `u64` byte counts
    /// exceed the exact range of `f64`, so dividing in floating point would
    /// perturb the last digits of large sizes.
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut exponent = 0u32;
        let mut divisor = 1u64;
        while exponent + 1 < UNITS.len() as u32 {
            match divisor.checked_mul(SCALE) {
                Some(next) if self.0 >= next => {
                    divisor = next;
                    exponent += 1;
                }
                _ => break,
            }
        }
        if exponent == 0 {
            return write!(formatter, "{} B", self.0);
        }

        let mut whole = self.0 / divisor;
        // Round the remainder to hundredths, half away from zero. The
        // remainder can reach 1024⁵, so the ×100 is done in `u128`.
        let remainder = u128::from(self.0 % divisor);
        let divisor_wide = u128::from(divisor);
        let mut hundredths = (remainder * 100 + divisor_wide / 2) / divisor_wide;
        if hundredths == 100 {
            hundredths = 0;
            whole += 1;
        }
        // Rounding can carry the whole part up to a full unit, and `1024.00 GB`
        // must be shown as `1.00 TB`. The carried value is exact, so this
        // promotion never needs to round again.
        if whole == SCALE && (exponent as usize) + 1 < UNITS.len() {
            whole = 1;
            exponent += 1;
        }
        write!(
            formatter,
            "{whole}.{hundredths:02} {}",
            UNITS[exponent as usize]
        )
    }
}

const DEFAULT_TAB_WIDTH: NonZeroU8 = match NonZeroU8::new(4) {
    Some(width) => width,
    None => panic!("default tab width must be nonzero"),
};

/// Build prose whose horizontal whitespace defines line-break opportunities.
///
/// Horizontal whitespace is collapsed. Explicit line boundaries, including
/// blank and trailing lines, remain hard boundaries.
pub fn word_wrapped(content: impl AsRef<str>) -> Doc {
    let normalized = normalize_line_endings(content.as_ref());
    if normalized.is_empty() {
        return Doc::empty();
    }

    let lines = normalized
        .split('\n')
        .map(|line| Doc::fill(words(line)))
        .collect::<Vec<_>>();
    Doc::join(Doc::hard_line(), lines)
}

/// Build fixed-width text using a four-column tab policy.
///
/// Horizontal spacing and explicit lines are preserved; tabs are expanded to
/// the next configured tab stop before layout.
pub fn fixed_width(content: impl AsRef<str>) -> Doc {
    fixed_width_with_tab_width(content, DEFAULT_TAB_WIDTH)
}

/// Build fixed-width text with an explicit tab width.
pub fn fixed_width_with_tab_width(content: impl AsRef<str>, tab_width: NonZeroU8) -> Doc {
    Doc::from_text(content, TextLayout::Preformatted { tab_width })
}

/// Split text into fixed-width line documents without line separators.
///
/// Empty interior and trailing lines are retained. Empty input has no lines.
pub fn lines(content: impl AsRef<str>) -> Vec<Doc> {
    lines_with_tab_width(content, DEFAULT_TAB_WIDTH)
}

/// Split text into fixed-width line documents using an explicit tab width.
pub fn lines_with_tab_width(content: impl AsRef<str>, tab_width: NonZeroU8) -> Vec<Doc> {
    let normalized = normalize_line_endings(content.as_ref());
    if normalized.is_empty() {
        return Vec::new();
    }
    normalized
        .split('\n')
        .map(|line| fixed_width_with_tab_width(line, tab_width))
        .collect()
}

/// Split one text fragment into Unicode-whitespace-delimited word documents.
pub fn words(content: impl AsRef<str>) -> Vec<Doc> {
    content.as_ref().split_whitespace().map(Doc::text).collect()
}

fn normalize_line_endings(value: &str) -> Cow<'_, str> {
    if !value.contains('\r') {
        return Cow::Borrowed(value);
    }
    let mut normalized = String::with_capacity(value.len());
    let mut characters = value.chars().peekable();
    while let Some(character) = characters.next() {
        if character == '\r' {
            if characters.peek() == Some(&'\n') {
                characters.next();
            }
            normalized.push('\n');
        } else {
            normalized.push(character);
        }
    }
    Cow::Owned(normalized)
}

#[cfg(feature = "json")]
pub mod json {
    use serde::Serialize;
    use serde_json::Value;

    use crate::{Doc, MachineText, TextSafetyError, tokens};

    /// Adaptive semantic JSON formatter.
    #[derive(Clone, Copy, Debug, Eq, PartialEq)]
    pub struct Pretty {
        indent: u16,
    }

    impl Default for Pretty {
        fn default() -> Self {
            Self { indent: 2 }
        }
    }

    impl Pretty {
        pub const fn new() -> Self {
            Self { indent: 2 }
        }

        pub const fn indent(mut self, indent: u16) -> Self {
            self.indent = indent;
            self
        }

        pub const fn configured_indent(self) -> u16 {
            self.indent
        }

        /// Serialize a value into an adaptive, semantically tokenized document.
        pub fn format<T: Serialize + ?Sized>(self, value: &T) -> Result<Doc, JsonFormatError> {
            let value = serde_json::to_value(value).map_err(serialization_error)?;
            Ok(Doc::tokens(
                [tokens::SYNTAX_CODE, tokens::LANGUAGE_JSON],
                value_doc(&value, self.indent),
            ))
        }
    }

    /// Format a serializable value as adaptive semantic JSON.
    pub fn pretty<T: Serialize + ?Sized>(value: &T) -> Result<Doc, JsonFormatError> {
        Pretty::default().format(value)
    }

    /// Serialize one compact newline-delimited JSON record.
    pub fn ndjson<T: Serialize + ?Sized>(value: &T) -> Result<MachineText, JsonFormatError> {
        let mut encoded = serde_json::to_string(value).map_err(serialization_error)?;
        encoded.push('\n');
        machine_text(encoded)
    }

    /// Serialize multiple compact newline-delimited JSON records.
    pub fn ndjson_records<I>(records: I) -> Result<MachineText, JsonFormatError>
    where
        I: IntoIterator,
        I::Item: Serialize,
    {
        let mut encoded = String::new();
        for record in records {
            let record = serde_json::to_string(&record).map_err(serialization_error)?;
            encoded.push_str(&record);
            encoded.push('\n');
        }
        machine_text(encoded)
    }

    #[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
    pub enum JsonFormatError {
        #[error("failed to serialize JSON: {message}")]
        Serialize { message: String },
        #[error("serialized NDJSON is not valid machine text: {0}")]
        UnsafeMachineText(TextSafetyError),
    }

    fn serialization_error(error: serde_json::Error) -> JsonFormatError {
        JsonFormatError::Serialize {
            message: error.to_string(),
        }
    }

    fn machine_text(encoded: String) -> Result<MachineText, JsonFormatError> {
        MachineText::parse(encoded).map_err(JsonFormatError::UnsafeMachineText)
    }

    fn value_doc(value: &Value, indent: u16) -> Doc {
        match value {
            Value::Null => atom(tokens::DATA_NULL, tokens::SYNTAX_CONSTANT, "null"),
            Value::Bool(value) => atom(
                tokens::DATA_BOOLEAN,
                tokens::SYNTAX_BOOLEAN,
                if *value { "true" } else { "false" },
            ),
            Value::Number(value) => atom(
                tokens::DATA_NUMBER,
                tokens::SYNTAX_NUMBER,
                value.to_string(),
            ),
            Value::String(value) => atom(
                tokens::DATA_STRING,
                tokens::SYNTAX_STRING,
                serde_json::to_string(value).expect("JSON strings always serialize"),
            ),
            Value::Array(values) => {
                let values = values.iter().map(|value| value_doc(value, indent));
                delimited("[", "]", values, indent)
            }
            Value::Object(values) => {
                let entries = values.iter().map(|(key, value)| {
                    let key = atom(
                        tokens::DATA_STRING,
                        tokens::SYNTAX_PROPERTY,
                        serde_json::to_string(key).expect("JSON object keys always serialize"),
                    );
                    Doc::concat([
                        key,
                        punctuation(tokens::SYNTAX_PUNCTUATION_DELIMITER, ":"),
                        Doc::nest(indent, Doc::concat([Doc::line(), value_doc(value, indent)])),
                    ])
                });
                delimited("{", "}", entries, indent)
            }
        }
    }

    fn atom(
        data_token: crate::TokenId,
        syntax_token: crate::TokenId,
        text: impl AsRef<str>,
    ) -> Doc {
        Doc::tokens([tokens::DATA, data_token, syntax_token], Doc::text(text))
    }

    fn delimited(
        open: &'static str,
        close: &'static str,
        values: impl IntoIterator<Item = Doc>,
        indent: u16,
    ) -> Doc {
        let values = values.into_iter().collect::<Vec<_>>();
        let open = punctuation(tokens::SYNTAX_PUNCTUATION_BRACKET, open);
        let close = punctuation(tokens::SYNTAX_PUNCTUATION_BRACKET, close);
        if values.is_empty() {
            return Doc::concat([open, close]);
        }
        let separator = Doc::concat([
            punctuation(tokens::SYNTAX_PUNCTUATION_DELIMITER, ","),
            Doc::line(),
        ]);
        let body = Doc::join(separator, values);
        Doc::group(Doc::concat([
            open,
            Doc::nest(indent, Doc::concat([Doc::soft_line(), body])),
            Doc::soft_line(),
            close,
        ]))
    }

    fn punctuation(token: crate::TokenId, text: &'static str) -> Doc {
        Doc::token_text(token, text)
    }
}

#[cfg(test)]
mod byte_size_tests {
    use super::ByteSize;

    #[test]
    fn bytes_below_one_kilobyte_are_whole() {
        assert_eq!(ByteSize::bytes(0).to_string(), "0 B");
        assert_eq!(ByteSize::bytes(1).to_string(), "1 B");
        assert_eq!(ByteSize::bytes(1023).to_string(), "1023 B");
    }

    #[test]
    fn unit_boundaries_are_exact() {
        assert_eq!(ByteSize::bytes(1024).to_string(), "1.00 KB");
        assert_eq!(ByteSize::bytes(1024 * 1024).to_string(), "1.00 MB");
        assert_eq!(ByteSize::bytes(1024 * 1024 * 1024).to_string(), "1.00 GB");
    }

    #[test]
    fn rounding_carries_into_the_next_unit() {
        // 1023.9999 KB must not render as `1024.00 KB`.
        let just_under = 1024 * 1024 - 1;
        assert_eq!(ByteSize::bytes(just_under).to_string(), "1.00 MB");
        // The same carry one unit up.
        assert_eq!(
            ByteSize::bytes(1024 * 1024 * 1024 - 1).to_string(),
            "1.00 GB"
        );
    }

    #[test]
    fn rounding_is_half_away_from_zero() {
        // 1.005 KB in hundredths of a kilobyte: 1029.12 bytes rounds to 1.00,
        // 1034 bytes to 1.01.
        assert_eq!(ByteSize::bytes(1029).to_string(), "1.00 KB");
        assert_eq!(ByteSize::bytes(1034).to_string(), "1.01 KB");
    }

    #[test]
    fn large_sizes_keep_full_integer_precision() {
        // Beyond 2^53 an f64 divide would perturb the result; these two
        // adjacent counts must not collapse onto the same rendering path.
        let base = 9_007_199_254_740_993u64;
        assert_eq!(ByteSize::bytes(base).as_u64(), base);
        assert_eq!(ByteSize::bytes(u64::MAX).to_string(), "16.00 EB");
    }

    #[test]
    fn the_reported_scan_size_renders_at_gigabyte_scale() {
        assert_eq!(ByteSize::bytes(36_828_222_525).to_string(), "34.30 GB");
        assert_eq!(ByteSize::bytes(81_618_377_035).to_string(), "76.01 GB");
        assert_eq!(ByteSize::bytes(146_146_432).to_string(), "139.38 MB");
    }

    #[test]
    fn unit_constructors_agree_with_byte_counts() {
        assert_eq!(ByteSize::kilobytes(1), Some(ByteSize::bytes(1024)));
        assert_eq!(
            ByteSize::megabytes(2),
            Some(ByteSize::bytes(2 * 1024 * 1024))
        );
        assert_eq!(
            ByteSize::gigabytes(1)
                .map(|size| size.to_string())
                .as_deref(),
            Some("1.00 GB")
        );
        assert_eq!(
            ByteSize::petabytes(u64::MAX),
            None,
            "overflow is reported, not wrapped"
        );
    }
}