rformat 0.2.0

Runtime formatting library
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
use crate::error::{FormatError, Result};

/// Represents an argument in a format string, either by position or by name.
#[derive(Debug, PartialEq)]
pub enum Argument<'f> {
    /// Positional argument (e.g., `{0}`)
    Integer(usize),
    /// Named argument (e.g., `{name}`)
    Identifier(&'f str),
}

/// Represents a parsed format specification.
#[derive(Debug, PartialEq)]
pub struct FormatSpec<'f> {
    /// Fill character for padding
    pub fill: char,
    /// Alignment specification
    pub align: Align,
    /// Optional sign specification
    pub sign: Option<Sign>,
    /// Alternate form flag (`#`)
    pub alternate: bool,
    /// Zero-padding flag (`0`)
    pub zero_pad: bool,
    /// Optional width specification
    pub width: Option<Count<'f>>,
    /// Optional precision specification
    pub precision: Option<Precision<'f>>,
    /// Type of formatting to apply
    pub r#type: Type<'f>,
}

/// Alignment options for formatting.
#[derive(Debug, PartialEq)]
pub enum Align {
    /// Left alignment (`<`)
    Left,
    /// Center alignment (`^`)
    Center,
    /// Right alignment (`>`, default)
    Right,
}

/// Sign options for formatting.
#[derive(Debug, PartialEq)]
pub enum Sign {
    /// Always show plus sign (`+`)
    Plus,
    /// Only show minus sign (`-`)
    Minus,
}

/// Precision specification for formatting.
#[derive(Debug, PartialEq)]
pub enum Precision<'f> {
    /// Precision specified as a count (integer or argument)
    Count(Count<'f>),
    /// Precision specified as a star (`*`), meaning next parameter
    Star,
}

/// Type of formatting to apply.
#[derive(Debug, PartialEq)]
pub enum Type<'f> {
    /// Binary formatting (`b`)
    Binary,
    /// Custom formatting (user-defined type)
    Custom(&'f str),
    /// Debug formatting (`?`)
    Debug,
    /// Debug lower hex formatting (`x?`)
    DebugLowerHex,
    /// Debug upper hex formatting (`X?`)
    DebugUpperHex,
    /// Display formatting (default)
    Display,
    /// Lower exponential formatting (`e`)
    LowerExp,
    /// Lower hexadecimal formatting (`x`)
    LowerHex,
    /// Octal formatting (`o`)
    Octal,
    /// Pointer formatting (`p`)
    Pointer,
    /// Upper exponential formatting (`E`)
    UpperExp,
    /// Upper hexadecimal formatting (`X`)
    UpperHex,
}

impl Type<'_> {
    /// Returns a string representation of the format type.
    pub fn to_str(&self) -> &str {
        match self {
            Type::Binary => "binary",
            Type::Custom(name) => name,
            Type::Debug => "debug",
            Type::DebugLowerHex => "debug_lower_hex",
            Type::DebugUpperHex => "debug_upper_hex",
            Type::Display => "display",
            Type::LowerExp => "lower_exp",
            Type::LowerHex => "lower_hex",
            Type::Octal => "octal",
            Type::Pointer => "pointer",
            Type::UpperExp => "upper_exp",
            Type::UpperHex => "upper_hex",
        }
    }
}

/// Count specification for width or precision.
#[derive(Debug, PartialEq)]
pub enum Count<'f> {
    /// Count specified as an argument (positional or named)
    Argument(Argument<'f>),
    /// Count specified as an integer
    Integer(usize),
}

/// Parses a format specification string into a `FormatSpec` struct.
///
/// # Arguments
///
/// * `format_spec` - The format specification string (e.g., `"<10.2x"`)
///
/// # Returns
///
/// A `Result` containing the parsed `FormatSpec` or an error if parsing fails.
pub fn parse_format_spec(format_spec: &str) -> Result<FormatSpec> {
    // Format spec found at https://doc.rust-lang.org/std/fmt/#syntax
    // Only difference is that `type` can be extended to custom types by the user,
    // If it's not a built-in type, it will be treated as a custom type, so any string is accepted.

    let mut format_spec_substr = format_spec.trim_end();

    // Parse fill and alignment
    let (fill, align) = match (
        format_spec_substr.chars().next(),
        format_spec_substr.chars().nth(1),
    ) {
        (Some(fill), Some('<')) => (Some(fill), Some(Align::Left)),
        (Some(fill), Some('^')) => (Some(fill), Some(Align::Center)),
        (Some(fill), Some('>')) => (Some(fill), Some(Align::Right)),
        (Some('<'), _) => (None, Some(Align::Left)),
        (Some('^'), _) => (None, Some(Align::Center)),
        (Some('>'), _) => (None, Some(Align::Right)),
        _ => (None, None),
    };

    // Skip fill character
    if fill.is_some() {
        format_spec_substr = &format_spec_substr[fill.unwrap().len_utf8()..];
    }

    // Skip align character
    if align.is_some() {
        format_spec_substr = &format_spec_substr[1..];
    }

    // Parse sign
    let sign = match format_spec_substr.chars().next() {
        Some('+') => Some(Sign::Plus),
        Some('-') => Some(Sign::Minus),
        _ => None,
    };

    // Skip sign character
    if sign.is_some() {
        format_spec_substr = &format_spec_substr[1..];
    }

    // Parse alternate form (#)
    let alternate = matches!(format_spec_substr.chars().next(), Some('#'));

    // Skip alternate form character
    if alternate {
        format_spec_substr = &format_spec_substr[1..];
    }

    // Parse zero padding
    let zero_pad = matches!(format_spec_substr.chars().next(), Some('0'));

    // Skip zero pad character
    if zero_pad {
        format_spec_substr = &format_spec_substr[1..];
    }

    // Parse width

    // Here's the possibilities:
    // [width][.precision]type
    // type can be empty - for display.
    let dot = format_spec_substr.chars().position(|c| c == '.');
    let dollar = format_spec_substr.chars().position(|c| c == '$');
    let non_digit = format_spec_substr.chars().position(|c| !c.is_ascii_digit());

    let width = match (dot, dollar, non_digit) {
        // Have precision
        (Some(dot), _, _) => &format_spec_substr[..dot],
        // No precision, width is an argument
        (None, Some(dollar), _) => &format_spec_substr[..=dollar],
        // No precision, width is an integer - type at the end
        (None, None, Some(non_digit)) => &format_spec_substr[..non_digit],
        // No precision, width is an integer - type is empty
        _ => format_spec_substr,
    };

    format_spec_substr = &format_spec_substr[width.len()..];

    let width = parse_count(width)?;

    // Parse precision

    // Here's the possibilities:
    // [.precision]type
    // type can be empty - for display.
    let precision = if format_spec_substr.starts_with(".") {
        // skip dot
        format_spec_substr = &format_spec_substr[1..];

        if format_spec_substr.starts_with('*') {
            // skip star
            format_spec_substr = &format_spec_substr[1..];

            Some(Precision::Star)
        } else {
            let dollar = format_spec_substr.chars().position(|c| c == '$');
            let non_digit = format_spec_substr.chars().position(|c| !c.is_ascii_digit());

            let precision = match (dollar, non_digit) {
                // Precision is an argument
                (Some(dollar), _) => &format_spec_substr[..=dollar],
                // Precision is an integer - type at the end
                (None, Some(non_digit)) => &format_spec_substr[..non_digit],
                // Precision is an integer - type is empty
                _ => format_spec_substr,
            };

            format_spec_substr = &format_spec_substr[precision.len()..];

            let precision = parse_count(precision)?
                .map(Precision::Count)
                .ok_or_else(|| FormatError::ExpectedPrecision(format_spec_substr.to_string()))?;

            Some(precision)
        }
    } else {
        None
    };

    // Parse type
    let r#type = parse_type(format_spec_substr)?;

    Ok(FormatSpec {
        // Default behavior
        fill: fill.unwrap_or(' '),
        align: align.unwrap_or(Align::Right),
        sign,
        alternate,
        zero_pad,
        width,
        precision,
        r#type,
    })
}

/// Parses a count string into a `Count` enum.
///
/// # Arguments
///
/// * `count` - The count string (e.g., `"10"`, `"width$"`)
///
/// # Returns
///
/// An `Option<Count>` or an error if parsing fails.
fn parse_count(count: &str) -> Result<Option<Count<'_>>> {
    if count.is_empty() {
        return Ok(None);
    }

    // We have 3 options here:
    // 1. an integer - all characters until the precision or type are digits.
    // 2. an integer argument - all characters are digits, until a $ is reached.
    // 3. an identifier argument - regular characters until a $ is reached.

    if !count.ends_with('$') {
        // Option 1
        let parsed = count.parse::<usize>()?;

        Ok(Some(Count::Integer(parsed)))
    } else {
        // Options 2 & 3
        let argument = &count[..count.len() - 1];

        if argument.chars().all(|c| c.is_ascii_digit()) {
            // Option 2
            let parsed = argument.parse::<usize>()?;

            Ok(Some(Count::Argument(Argument::Integer(parsed))))
        } else {
            // Option 3
            Ok(Some(Count::Argument(Argument::Identifier(argument))))
        }
    }
}

/// Parses a type string into a `Type` enum.
///
/// # Arguments
///
/// * `ty` - The type string (e.g., `"x"`, `"?"`, `"custom"`)
///
/// # Returns
///
/// A `Type` enum or an error if parsing fails.
fn parse_type(ty: &str) -> Result<Type> {
    Ok(match ty {
        "" => Type::Display,
        "?" => Type::Debug,
        "x?" => Type::DebugLowerHex,
        "X?" => Type::DebugUpperHex,
        "o" => Type::Octal,
        "x" => Type::LowerHex,
        "X" => Type::UpperHex,
        "p" => Type::Pointer,
        "b" => Type::Binary,
        "e" => Type::LowerExp,
        "E" => Type::UpperExp,
        _ => Type::Custom(ty),
    })
}

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

    #[test]
    fn test_empty_format_spec() {
        let spec = parse_format_spec("").unwrap();

        assert_eq!(spec.fill, ' ');
        assert_eq!(spec.align, Align::Right);
        assert_eq!(spec.sign, None);
        assert!(!spec.alternate);
        assert!(!spec.zero_pad);
        assert_eq!(spec.width, None);
        assert_eq!(spec.precision, None);
        assert_eq!(spec.r#type, Type::Display);
    }

    #[test]
    fn test_fill_and_align() {
        // Left align with _ as fill character
        let spec = parse_format_spec("_<").unwrap();
        assert_eq!(spec.fill, '_');
        assert_eq!(spec.align, Align::Left);

        // Center align with space as fill character
        let spec = parse_format_spec(" ^").unwrap();
        assert_eq!(spec.fill, ' ');
        assert_eq!(spec.align, Align::Center);

        // Right align with 0 as fill character
        let spec = parse_format_spec("0>").unwrap();
        assert_eq!(spec.fill, '0');
        assert_eq!(spec.align, Align::Right);

        // Left align without fill character
        let spec = parse_format_spec("<").unwrap();
        assert_eq!(spec.fill, ' ');
        assert_eq!(spec.align, Align::Left);

        // Center align without fill character
        let spec = parse_format_spec("^").unwrap();
        assert_eq!(spec.fill, ' ');
        assert_eq!(spec.align, Align::Center);

        // Right align without fill character
        let spec = parse_format_spec(">").unwrap();
        assert_eq!(spec.fill, ' ');
        assert_eq!(spec.align, Align::Right);
    }

    #[test]
    fn test_sign() {
        // Plus sign
        let spec = parse_format_spec("+").unwrap();
        assert_eq!(spec.sign, Some(Sign::Plus));

        // Minus sign
        let spec = parse_format_spec("-").unwrap();
        assert_eq!(spec.sign, Some(Sign::Minus));
    }

    #[test]
    fn test_alternate_form() {
        // With alternate form
        let spec = parse_format_spec("#").unwrap();
        assert!(spec.alternate);

        // Without alternate form
        let spec = parse_format_spec("").unwrap();
        assert!(!spec.alternate);
    }

    #[test]
    fn test_zero_padding() {
        // With zero padding
        let spec = parse_format_spec("0").unwrap();
        assert!(spec.zero_pad);

        // Without zero padding
        let spec = parse_format_spec("").unwrap();
        assert!(!spec.zero_pad);
    }

    #[test]
    fn test_width() {
        // Integer width
        let spec = parse_format_spec("10").unwrap();
        assert_eq!(spec.width, Some(Count::Integer(10)));

        // Integer argument
        let spec = parse_format_spec("1$").unwrap();
        assert_eq!(spec.width, Some(Count::Argument(Argument::Integer(1))));

        // Identifier argument
        let spec = parse_format_spec("width$").unwrap();
        assert_eq!(
            spec.width,
            Some(Count::Argument(Argument::Identifier("width")))
        );
    }

    #[test]
    fn test_precision() {
        // Integer precision
        let spec = parse_format_spec(".5").unwrap();
        assert_eq!(spec.precision, Some(Precision::Count(Count::Integer(5))));

        // Integer argument precision
        let spec = parse_format_spec(".2$").unwrap();
        assert_eq!(
            spec.precision,
            Some(Precision::Count(Count::Argument(Argument::Integer(2))))
        );

        // Identifier argument precision
        let spec = parse_format_spec(".prec$").unwrap();
        assert_eq!(
            spec.precision,
            Some(Precision::Count(Count::Argument(Argument::Identifier(
                "prec"
            ))))
        );

        // Star precision
        let spec = parse_format_spec(".*").unwrap();
        assert_eq!(spec.precision, Some(Precision::Star));

        // No precision
        let spec = parse_format_spec("").unwrap();
        assert_eq!(spec.precision, None);
    }

    #[test]
    fn test_type() {
        // Default type (Display)
        let spec = parse_format_spec("").unwrap();
        assert_eq!(spec.r#type, Type::Display);

        // Debug type
        let spec = parse_format_spec("?").unwrap();
        assert_eq!(spec.r#type, Type::Debug);

        // Debug lower hex
        let spec = parse_format_spec("x?").unwrap();
        assert_eq!(spec.r#type, Type::DebugLowerHex);

        // Debug upper hex
        let spec = parse_format_spec("X?").unwrap();
        assert_eq!(spec.r#type, Type::DebugUpperHex);

        // Octal
        let spec = parse_format_spec("o").unwrap();
        assert_eq!(spec.r#type, Type::Octal);

        // Lower hex
        let spec = parse_format_spec("x").unwrap();
        assert_eq!(spec.r#type, Type::LowerHex);

        // Upper hex
        let spec = parse_format_spec("X").unwrap();
        assert_eq!(spec.r#type, Type::UpperHex);

        // Pointer
        let spec = parse_format_spec("p").unwrap();
        assert_eq!(spec.r#type, Type::Pointer);

        // Binary
        let spec = parse_format_spec("b").unwrap();
        assert_eq!(spec.r#type, Type::Binary);

        // Lower exp
        let spec = parse_format_spec("e").unwrap();
        assert_eq!(spec.r#type, Type::LowerExp);

        // Upper exp
        let spec = parse_format_spec("E").unwrap();
        assert_eq!(spec.r#type, Type::UpperExp);

        // Unsupported type
        assert_eq!(parse_format_spec("Z").unwrap().r#type, Type::Custom("Z"));
    }

    #[test]
    fn test_combined_format_specs() {
        // Fill, align, sign, alternate, zero pad, width, precision, type, ws at end ignored
        let spec = parse_format_spec("a^10.5x    ").unwrap();

        // fill and align overridden by zero pad
        assert_eq!(spec.fill, 'a');
        assert_eq!(spec.align, Align::Center);
        assert_eq!(spec.sign, None);
        assert!(!spec.alternate);
        assert!(!spec.zero_pad);
        assert_eq!(spec.width, Some(Count::Integer(10)));
        assert_eq!(spec.precision, Some(Precision::Count(Count::Integer(5))));
        assert_eq!(spec.r#type, Type::LowerHex);

        // Fill, align, sign, alternate, zero pad, width, precision, type, ws at end ignored
        let spec = parse_format_spec("_>+#010.5x    ").unwrap();

        // fill and align overridden by zero pad
        assert_eq!(spec.fill, '_');
        assert_eq!(spec.align, Align::Right);
        assert_eq!(spec.sign, Some(Sign::Plus));
        assert!(spec.alternate);
        assert!(spec.zero_pad);
        assert_eq!(spec.width, Some(Count::Integer(10)));
        assert_eq!(spec.precision, Some(Precision::Count(Count::Integer(5))));
        assert_eq!(spec.r#type, Type::LowerHex);

        // Left align with identifier argument width and identifier argument precision
        let spec = parse_format_spec("<width$.prec$?").unwrap();

        assert_eq!(spec.align, Align::Left);
        assert_eq!(
            spec.width,
            Some(Count::Argument(Argument::Identifier("width")))
        );
        assert_eq!(
            spec.precision,
            Some(Precision::Count(Count::Argument(Argument::Identifier(
                "prec"
            ))))
        );
        assert_eq!(spec.r#type, Type::Debug);

        // Center align with integer argument width and star precision
        let spec = parse_format_spec("^1$.*").unwrap();
        assert_eq!(spec.width, Some(Count::Argument(Argument::Integer(1))));
        assert_eq!(spec.precision, Some(Precision::Star));
    }

    #[test]
    fn test_invalid_precision() {
        // This test assumes certain error handling logic
        assert_eq!(
            parse_format_spec("0.invalid_precision"),
            Err(FormatError::ExpectedPrecision(
                "invalid_precision".to_string()
            ))
        );
    }
}