fmt-dur 0.1.3

Strict human-readable Duration parser/formatter: '2d3h4m', '90s', '1.5h'. Enforces unit order, no duplicates, and precise decimal rules.
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
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
//! fmt_dur - strict Duration parsing/formatting.
//!
//! # Grammar (strict by default)
//!
//! ```text
//! Input := Segment { Segment }
//! Segment := Number Unit
//! Number := DIGIT+ [ "." DIGIT{1,9} ]   // decimal allowed at most once, and only in the last Segment
//! Unit   := "d" | "h" | "m" | "s" | "ms" | "us" | "ns"
//! ```
//!
//! ## Rules
//!
//! - Units must appear in strictly descending order: d > h > m > s > ms > us > ns
//! - No duplicate units
//! - No spaces/underscores; lowercase only (enable "loose" feature to allow spaces/underscores and case-insensitive)
//! - At least one segment must be present (e.g., "0s" is valid)
//! - Up to 9 fractional digits (nanosecond precision). Fraction may appear only on the last segment.
//!
//! # Examples
//!
//! Valid duration strings:
//! - `"2d3h4m"`
//! - `"90s"`
//! - `"1.5h"`
//! - `"250ms"`
//! - `"1m30s"`
//! - `"1m30.5s"`
//! - `"750us"`
//! - `"10ns"`
//!
//! # Usage
//!
//! ```rust
//! use std::time::Duration;
//! # use fmt_dur::{parse, parse_with, format, format_with, ParseOptions, FormatOptions};
//!
//! // Parse a duration string
//! let duration = parse("1.5h").unwrap();
//! assert_eq!(duration, Duration::from_secs(5400));
//!
//! // Parse with custom options (saturating on overflow)
//! let duration = parse_with("1.5h", &ParseOptions::strict().saturating()).unwrap();
//!
//! // Format a duration (default: mixed-units; decimals only on the last unit)
//! let formatted = format(duration);
//! assert_eq!(formatted, "1h30m");
//!
//! // Format with custom options (largest unit with decimal)
//! let formatted = format_with(duration, &FormatOptions::largest_unit_decimal());
//! assert_eq!(formatted, "1.5h");
//! ```
//!
//! # Features
//!
//! - **`loose`**: Allows spaces and underscores between segments and case-insensitive units (ordering still enforced).
//! - **`serde`**: Enables `serde::{Serialize, Deserialize}` for [`DurationStr`] using this format.

#![forbid(unsafe_code)]
// #![deny(missing_docs)]
use std::fmt;
use std::time::Duration;

/// Behavior when a parsed value exceeds `Duration`'s maximum.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OverflowBehavior {
    /// Return an error on overflow (default).
    Error,
    /// Saturate to `Duration::MAX` on overflow.
    Saturate,
}

/// Options controlling parsing behavior.
#[derive(Clone, Copy, Debug)]
pub struct ParseOptions {
    overflow: OverflowBehavior,
}

impl ParseOptions {
    /// Strict defaults: overflow errors.
    pub fn strict() -> Self {
        Self {
            overflow: OverflowBehavior::Error,
        }
    }
    /// Change overflow behavior to saturate.
    pub fn saturating(mut self) -> Self {
        self.overflow = OverflowBehavior::Saturate;
        self
    }
}

/// Parse a strict human duration using default options.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use fmt_dur::parse;
///
/// assert_eq!(parse("90s").unwrap(), Duration::from_secs(90));
/// assert_eq!(parse("1.5h").unwrap(), Duration::from_secs(5400));
/// assert_eq!(parse("2d3h4m").unwrap(), Duration::from_secs(2 * 86_400 + 3 * 3600 + 4 * 60));
/// ```
pub fn parse(input: &str) -> Result<Duration, ParseError> {
    parse_with(input, &ParseOptions::strict())
}

/// Parse with explicit options.
///
/// # Examples
///
/// ```
/// use fmt_dur::{parse_with, ParseOptions};
///
/// let result = parse_with("999999999d", &ParseOptions::strict().saturating());
/// assert!(result.is_ok());
/// ```
pub fn parse_with(input: &str, opts: &ParseOptions) -> Result<Duration, ParseError> {
    let s = normalize_input(input)?;
    Parser::new(&s, *opts).parse()
}

/// Format a Duration using mixed-units style (default).
///
/// Examples: `"2d3h4m5.25s"`, `"250ms"`, `"0s"`.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use fmt_dur::format;
///
/// assert_eq!(format(Duration::from_secs(90)), "1m30s");
/// assert_eq!(format(Duration::from_millis(250)), "250ms");
/// ```
pub fn format(d: Duration) -> String {
    format_with(d, &FormatOptions::mixed())
}

/// Formatting style.
#[derive(Clone, Copy, Debug)]
pub enum FormatStyle {
    /// Mixed units, descending, with decimals only on the last (seconds) component.
    /// Sub-second durations use ms/us/ns.
    Mixed,
    /// Single largest unit with a decimal fraction if needed, e.g., `"1.5h"`, `"90s"`, `"0.123s"`.
    /// This style cannot always be finite-decimal exact (e.g., 30s in hours),
    /// but it still round-trips because the parser accepts up to 9 fractional digits.
    LargestUnitDecimal,
}

/// Options controlling formatting.
#[derive(Clone, Copy, Debug)]
pub struct FormatOptions {
    style: FormatStyle,
    max_frac_digits: u8, // 0..=9
}

impl FormatOptions {
    /// Mixed-units default. Fractions up to 9 digits when needed.
    pub fn mixed() -> Self {
        Self {
            style: FormatStyle::Mixed,
            max_frac_digits: 9,
        }
    }
    /// Largest-unit decimal style.
    pub fn largest_unit_decimal() -> Self {
        Self {
            style: FormatStyle::LargestUnitDecimal,
            max_frac_digits: 9,
        }
    }
    /// Limit fractional digits (0..=9).
    pub fn with_max_frac_digits(mut self, digits: u8) -> Self {
        self.max_frac_digits = digits.min(9);
        self
    }
}

/// Format with options.
///
/// # Examples
///
/// ```
/// use std::time::Duration;
/// use fmt_dur::{format_with, FormatOptions};
///
/// let d = Duration::from_secs(5400);
/// let s = format_with(d, &FormatOptions::largest_unit_decimal());
/// assert_eq!(s, "1.5h");
/// ```
pub fn format_with(d: Duration, opts: &FormatOptions) -> String {
    match opts.style {
        FormatStyle::Mixed => format_mixed(d, opts.max_frac_digits),
        FormatStyle::LargestUnitDecimal => format_largest_unit_decimal(d, opts.max_frac_digits),
    }
}

/// Error returned when parsing fails.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum ParseError {
    /// Empty input string.
    Empty,
    /// Invalid character at byte index.
    InvalidChar(usize),
    /// Invalid or missing number at byte index.
    InvalidNumber(usize),
    /// Invalid unit at byte index.
    InvalidUnit(usize),
    /// Units must be strictly descending (e.g., h cannot follow s).
    OutOfOrderUnit {
        /// The previous unit that appeared earlier.
        prev: Unit,
        /// The next unit that violated ordering.
        next: Unit,
        /// Byte index where the violation occurred.
        index: usize,
    },
    /// Unit appeared more than once.
    DuplicateUnit {
        /// The duplicated unit.
        unit: Unit,
        /// Byte index of the duplicate.
        index: usize,
    },
    /// A decimal number was found before the last segment.
    DecimalNotLast(usize),
    /// Too many fractional digits (> 9).
    TooPreciseFraction {
        /// Number of digits found.
        digits: usize,
        /// Byte index of the fraction.
        index: usize,
    },
    /// Overflow (value exceeds Duration::MAX) and behavior was set to Error.
    Overflow,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        use ParseError::*;
        match self {
            Empty => write!(f, "empty duration"),
            InvalidChar(i) => write!(f, "invalid character at byte index {}", i),
            InvalidNumber(i) => write!(f, "invalid number at byte index {}", i),
            InvalidUnit(i) => write!(f, "invalid or missing unit at byte index {}", i),
            OutOfOrderUnit { prev, next, index } => write!(
                f,
                "out-of-order unit '{}' followed by '{}' at byte index {}",
                prev.as_str(),
                next.as_str(),
                index
            ),
            DuplicateUnit { unit, index } => write!(
                f,
                "duplicate unit '{}' at byte index {}",
                unit.as_str(),
                index
            ),
            DecimalNotLast(i) => write!(f, "decimal segment must be last (index {})", i),
            TooPreciseFraction { digits, index } => write!(
                f,
                "fractional part has {} digits (max 9) at byte index {}",
                digits, index
            ),
            Overflow => write!(f, "duration overflowed maximum representable span"),
        }
    }
}

impl std::error::Error for ParseError {}

/// Time unit for duration parsing and formatting.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Unit {
    /// Days
    D,
    /// Hours
    H,
    /// Minutes
    M,
    /// Seconds
    S,
    /// Milliseconds
    Ms,
    /// Microseconds
    Us,
    /// Nanoseconds
    Ns,
}

impl Unit {
    fn as_str(self) -> &'static str {
        match self {
            Unit::D => "d",
            Unit::H => "h",
            Unit::M => "m",
            Unit::S => "s",
            Unit::Ms => "ms",
            Unit::Us => "us",
            Unit::Ns => "ns",
        }
    }
    fn rank(self) -> u8 {
        match self {
            Unit::D => 6,
            Unit::H => 5,
            Unit::M => 4,
            Unit::S => 3,
            Unit::Ms => 2,
            Unit::Us => 1,
            Unit::Ns => 0,
        }
    }
    fn nanos(self) -> u128 {
        match self {
            Unit::D => 86_400_000_000_000,
            Unit::H => 3_600_000_000_000,
            Unit::M => 60_000_000_000,
            Unit::S => 1_000_000_000,
            Unit::Ms => 1_000_000,
            Unit::Us => 1_000,
            Unit::Ns => 1,
        }
    }
}

struct Parser<'a> {
    s: &'a str,
    opts: ParseOptions,
    i: usize,
    len: usize,
}

impl<'a> Parser<'a> {
    fn new(s: &'a str, opts: ParseOptions) -> Self {
        Self {
            s,
            opts,
            i: 0,
            len: s.len(),
        }
    }

    fn parse(&mut self) -> Result<Duration, ParseError> {
        if self.s.is_empty() {
            return Err(ParseError::Empty);
        }

        let mut total_nanos: u128 = 0;
        let max_nanos: u128 =
            (u128::from(u64::MAX) * 1_000_000_000u128) + (1_000_000_000u128 - 1u128);

        let mut prev_rank: Option<u8> = None;
        let mut seen_mask: u8 = 0;
        let mut decimal_used = false;
        let mut segments = 0usize;

        while self.i < self.len {
            let start_num = self.i;
            // Parse number with optional decimal.
            let (int_part, frac_part) = self.parse_number()?;
            segments += 1;

            // Decimal can only appear on the last segment.
            if frac_part.is_some() && self.i < self.len {
                // There are more characters; must be unit or next segment.
                // Check after unit parse that we're not at end.
                decimal_used = true;
            }

            let unit_start = self.i;
            let unit = self
                .parse_unit()
                .map_err(|_| ParseError::InvalidUnit(unit_start))?;

            // Enforce ordering
            let rank = unit.rank();
            if let Some(prev) = prev_rank {
                if rank >= prev {
                    return Err(ParseError::OutOfOrderUnit {
                        prev: rank_to_unit(prev),
                        next: unit,
                        index: unit_start,
                    });
                }
            }
            prev_rank = Some(rank);

            // Enforce no duplicates
            let bit = 1u8 << rank;
            if (seen_mask & bit) != 0 {
                return Err(ParseError::DuplicateUnit {
                    unit,
                    index: unit_start,
                });
            }
            seen_mask |= bit;

            // Decimal must be on the last segment only.
            if decimal_used && self.i < self.len {
                return Err(ParseError::DecimalNotLast(start_num));
            }

            // Accumulate nanos, with overflow handling
            let unit_nanos = unit.nanos();

            // int_part
            if int_part > 0 {
                let add = (int_part as u128)
                    .checked_mul(unit_nanos)
                    .ok_or(ParseError::Overflow)?;
                total_nanos = match total_nanos.checked_add(add) {
                    Some(v) => v,
                    None => {
                        if self.opts.overflow == OverflowBehavior::Saturate {
                            return Ok(duration_max());
                        } else {
                            return Err(ParseError::Overflow);
                        }
                    }
                };
                if total_nanos > max_nanos {
                    if self.opts.overflow == OverflowBehavior::Saturate {
                        return Ok(duration_max());
                    } else {
                        return Err(ParseError::Overflow);
                    }
                }
            }

            // frac_part
            if let Some(frac) = frac_part {
                let digits = frac.len();
                if digits == 0 {
                    return Err(ParseError::InvalidNumber(start_num));
                }
                if digits > 9 {
                    return Err(ParseError::TooPreciseFraction {
                        digits,
                        index: start_num,
                    });
                }
                let frac_value = frac
                    .bytes()
                    .try_fold(0u128, |acc, b: u8| {
                        if b.is_ascii_digit() {
                            Some(acc * 10 + u128::from(b - b'0'))
                        } else {
                            None
                        }
                    })
                    .ok_or(ParseError::InvalidNumber(start_num))?;

                // Compute fractional nanos: unit_nanos * frac / 10^digits
                let denom = 10u128.pow(digits as u32);
                let add = unit_nanos
                    .checked_mul(frac_value)
                    .ok_or(ParseError::Overflow)?
                    / denom;

                total_nanos = match total_nanos.checked_add(add) {
                    Some(v) => v,
                    None => {
                        if self.opts.overflow == OverflowBehavior::Saturate {
                            return Ok(duration_max());
                        } else {
                            return Err(ParseError::Overflow);
                        }
                    }
                };
                if total_nanos > max_nanos {
                    if self.opts.overflow == OverflowBehavior::Saturate {
                        return Ok(duration_max());
                    } else {
                        return Err(ParseError::Overflow);
                    }
                }
            }
        }

        if segments == 0 {
            return Err(ParseError::Empty);
        }

        Ok(nanos_to_duration(total_nanos))
    }

    fn parse_number(&mut self) -> Result<(u64, Option<&'a str>), ParseError> {
        let start = self.i;
        let bytes = self.s.as_bytes();

        if start >= self.len {
            return Err(ParseError::InvalidNumber(start));
        }

        let mut saw_digit = false;
        let mut int_end = start;
        while int_end < self.len {
            let b = bytes[int_end];
            if b.is_ascii_digit() {
                saw_digit = true;
                int_end += 1;
            } else {
                break;
            }
        }

        if !saw_digit {
            return Err(ParseError::InvalidNumber(start));
        }

        let mut frac: Option<&'a str> = None;
        let mut pos = int_end;
        if pos < self.len && bytes[pos] == b'.' {
            // fractional part
            pos += 1;
            let frac_start = pos;
            let mut frac_end = pos;
            while frac_end < self.len {
                let b = bytes[frac_end];
                if b.is_ascii_digit() {
                    frac_end += 1;
                } else {
                    break;
                }
            }
            if frac_end == frac_start {
                return Err(ParseError::InvalidNumber(start));
            }
            frac = Some(&self.s[frac_start..frac_end]);
            pos = frac_end;
        }

        // Parse int part (fits u64)
        let int_str = &self.s[start..int_end];
        let int_val = int_str
            .bytes()
            .try_fold(0u64, |acc, b| {
                acc.checked_mul(10)?.checked_add(u64::from(b - b'0'))
            })
            .ok_or(ParseError::InvalidNumber(start))?;

        self.i = pos;
        Ok((int_val, frac))
    }

    fn parse_unit(&mut self) -> Result<Unit, ()> {
        // Match longest unit first: "ms", "us", "ns" before single letters.
        let rest = &self.s[self.i..];

        let try_take =
            |s: &str, u: Unit| -> Option<Unit> { if rest.starts_with(s) { Some(u) } else { None } };

        let unit = try_take("ms", Unit::Ms)
            .or_else(|| try_take("us", Unit::Us))
            .or_else(|| try_take("ns", Unit::Ns))
            .or_else(|| try_take("d", Unit::D))
            .or_else(|| try_take("h", Unit::H))
            .or_else(|| try_take("m", Unit::M))
            .or_else(|| try_take("s", Unit::S));

        if let Some(u) = unit {
            self.i += u.as_str().len();
            Ok(u)
        } else {
            Err(())
        }
    }
}

// Helpers

fn nanos_to_duration(nanos: u128) -> Duration {
    let secs = (nanos / 1_000_000_000) as u64;
    let sub = (nanos % 1_000_000_000) as u32;
    Duration::new(secs, sub)
}

fn duration_max() -> Duration {
    // Equivalent to Duration::MAX without relying on that constant.
    nanos_to_duration((u128::from(u64::MAX) * 1_000_000_000u128) + 999_999_999u128)
}

fn rank_to_unit(rank: u8) -> Unit {
    match rank {
        6 => Unit::D,
        5 => Unit::H,
        4 => Unit::M,
        3 => Unit::S,
        2 => Unit::Ms,
        1 => Unit::Us,
        _ => Unit::Ns,
    }
}

fn normalize_input(input: &str) -> Result<String, ParseError> {
    #[cfg(feature = "loose")]
    {
        let mut s = String::with_capacity(input.len());
        for (i, ch) in input.chars().enumerate() {
            if ch == ' ' || ch == '_' {
                continue;
            }
            if ch.is_ascii() {
                s.push(ch.to_ascii_lowercase());
            } else {
                return Err(ParseError::InvalidChar(i));
            }
        }
        if s.is_empty() {
            return Err(ParseError::Empty);
        }
        Ok(s)
    }
    #[cfg(not(feature = "loose"))]
    {
        // Strict: must be ASCII and contain no spaces/underscores, lower-case only.
        if input.is_empty() {
            return Err(ParseError::Empty);
        }
        for (i, b) in input.bytes().enumerate() {
            if !b.is_ascii() {
                return Err(ParseError::InvalidChar(i));
            }
            if b == b' ' || b == b'_' || b.is_ascii_uppercase() {
                return Err(ParseError::InvalidChar(i));
            }
        }
        Ok(input.to_string())
    }
}

// Formatting

fn format_mixed(d: Duration, max_frac_digits: u8) -> String {
    let mut rem_secs = d.as_secs();
    let rem_nanos = d.subsec_nanos();

    let mut out = String::new();

    let days = rem_secs / 86_400;
    if days > 0 {
        out.push_str(&format!("{}d", days));
        rem_secs %= 86_400;
    }
    let hours = rem_secs / 3_600;
    if hours > 0 {
        out.push_str(&format!("{}h", hours));
        rem_secs %= 3_600;
    }
    let mins = rem_secs / 60;
    if mins > 0 {
        out.push_str(&format!("{}m", mins));
        rem_secs %= 60;
    }

    // Always render seconds if we have any seconds or nanos left.
    if rem_secs > 0 || rem_nanos > 0 {
        if rem_nanos > 0 {
            let s = format_fraction(rem_secs, rem_nanos, max_frac_digits);
            out.push_str(&format!("{}s", s));
        } else {
            out.push_str(&format!("{}s", rem_secs));
        }
    }

    // If nothing at all was emitted, render 0s.
    if out.is_empty() {
        out.push_str("0s");
    }
    out
}

fn format_largest_unit_decimal(d: Duration, max_frac_digits: u8) -> String {
    let total_nanos = (d.as_secs() as u128) * 1_000_000_000u128 + (d.subsec_nanos() as u128);

    if total_nanos == 0 {
        return "0s".to_string();
    }

    let candidates = [
        Unit::D,
        Unit::H,
        Unit::M,
        Unit::S,
        Unit::Ms,
        Unit::Us,
        Unit::Ns,
    ];

    for &u in &candidates {
        let u_nanos = u.nanos();
        if total_nanos >= u_nanos {
            // integer part
            let whole = total_nanos / u_nanos;
            let rem = total_nanos % u_nanos;
            if rem == 0 {
                return format!("{}{}", whole, u.as_str());
            } else {
                // fraction up to max_frac_digits
                let frac = rem * 10u128.pow(max_frac_digits as u32) / u_nanos;
                // Trim trailing zeros, but keep at least one digit.
                let mut frac_str = format!("{:0width$}", frac, width = max_frac_digits as usize);
                while frac_str.ends_with('0') && frac_str.len() > 1 {
                    frac_str.pop();
                }
                return format!("{}.{}{}", whole, frac_str, u.as_str());
            }
        }
    }
    // Fallback, should not happen.
    "0s".to_string()
}

fn format_fraction(secs: u64, nanos: u32, max_frac_digits: u8) -> String {
    if nanos == 0 || max_frac_digits == 0 {
        return format!("{}.", secs).trim_end_matches('.').to_string();
    }
    // Scale nanos (0..1_000_000_000) to fractional digits.
    let scale = 10u32.pow(max_frac_digits as u32);
    let frac = (nanos as u128 * scale as u128) / 1_000_000_000u128;
    let mut frac_str = format!("{:0width$}", frac, width = max_frac_digits as usize);
    // Trim trailing zeros.
    while frac_str.ends_with('0') && frac_str.len() > 1 {
        frac_str.pop();
    }
    format!("{}.{}", secs, frac_str)
}

/// A serde wrapper that (de)serializes as a strict human duration string.
///
/// Enable the "serde" feature to use this type.
#[cfg(feature = "serde")]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct DurationStr(pub Duration);

#[cfg(feature = "serde")]
impl serde::Serialize for DurationStr {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        let s = format(self.0);
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for DurationStr {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct V;
        impl<'de> serde::de::Visitor<'de> for V {
            type Value = DurationStr;
            fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
                f.write_str("a strict human duration string (e.g., \"2d3h4m\", \"90s\", \"1.5h\")")
            }
            fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                parse(v)
                    .map(DurationStr)
                    .map_err(|e| E::custom(format!("invalid duration: {}", e)))
            }
        }
        deserializer.deserialize_str(V)
    }
}

// Tests

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

    #[test]
    fn basic_parse() {
        assert_eq!(parse("90s").unwrap(), Duration::from_secs(90));
        assert_eq!(parse("1.5h").unwrap(), Duration::from_secs(5400));
        assert_eq!(
            parse("2d3h4m").unwrap(),
            Duration::from_secs(2 * 86_400 + 3 * 3600 + 4 * 60)
        );
        assert_eq!(parse("250ms").unwrap(), Duration::from_millis(250));
        assert_eq!(parse("750us").unwrap(), Duration::from_micros(750));
        assert_eq!(parse("10ns").unwrap(), Duration::new(0, 10));
        assert_eq!(parse("1m30s").unwrap(), Duration::from_secs(90));
        assert_eq!(
            parse("1m30.5s").unwrap(),
            Duration::from_secs(90) + Duration::from_millis(500)
        );
    }

    #[test]
    fn ordering_and_duplicates() {
        assert!(parse("h1m").is_err());
        assert!(parse("1m1m").is_err());
        assert!(parse("1s2m").is_err());
        assert!(parse("1ms2s").is_err());
    }

    #[test]
    fn decimal_rules() {
        assert!(parse("1.5h10m").is_err()); // decimal not last
        assert!(parse("1.1234567890s").is_err()); // too precise (>9)
        assert!(parse("1.s").is_err());
        assert!(parse(".5h").is_err());
    }

    #[test]
    fn zero_and_format() {
        assert_eq!(parse("0s").unwrap(), Duration::from_secs(0));
        assert_eq!(format(Duration::from_secs(0)), "0s");

        let d = Duration::from_secs(2 * 86_400 + 3 * 3600 + 4 * 60) + Duration::from_millis(250);
        let s = format(d);
        assert_eq!(s, "2d3h4m0.25s");
    }

    #[test]
    fn roundtrip_mixed() {
        let cases = [
            "2d3h4m",
            "90s",
            "1.5h",
            "250ms",
            "1m30s",
            "1m30.5s",
            "999ms",
            "1001ms",
            "3h15m45.123456789s",
        ];
        for &c in &cases {
            let d = parse(c).unwrap();
            let s = format(d);
            let d2 = parse(&s).unwrap();
            assert_eq!(d, d2, "roundtrip failed for {}", c);
        }
    }

    #[test]
    fn largest_unit_decimal_format() {
        let d = Duration::from_secs(5400);
        let s = format_with(
            d,
            &FormatOptions::largest_unit_decimal().with_max_frac_digits(3),
        );
        // 5400 seconds = 1.5h exactly
        assert_eq!(s, "1.5h");
    }

    #[test]
    fn overflow_behavior() {
        // Construct a huge input to overflow
        let huge = format!("{}d", u64::MAX);
        let err = parse_with(&huge, &ParseOptions::strict()).unwrap_err();
        assert!(matches!(err, ParseError::Overflow));

        let saturated = parse_with(&huge, &ParseOptions::strict().saturating()).unwrap();
        assert_eq!(saturated, super::duration_max());
    }

    #[cfg(feature = "loose")]
    #[test]
    fn loose_mode() {
        assert_eq!(
            super::parse("1H 30M").unwrap(),
            std::time::Duration::from_secs(5400)
        );
        assert_eq!(
            super::parse("1h_250ms").unwrap(),
            std::time::Duration::from_millis(3_600_250)
        );
    }
}