envigil 0.4.0

Keep vigil over your environment — load, parse, and validate env vars with zero dependencies.
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
882
883
884
885
886
887
//! Ready-made parser functions for common types.
//!
//! Each function has the signature `Fn(&str) -> Result<T, String>`
//! and can be passed directly to [`VarBuilder::new`](crate::VarBuilder::new).
//!
//! # Examples
//!
//! ```
//! use envigil::parse;
//!
//! assert_eq!(parse::secs("30").unwrap(), std::time::Duration::from_secs(30));
//! assert_eq!(parse::flag("yes").unwrap(), true);
//! assert_eq!(parse::list("a, b, c").unwrap(), vec!["a", "b", "c"]);
//! ```

use std::net::SocketAddr;
use std::time::Duration;

/// Parse an integer number of seconds into a [`Duration`].
///
/// # Examples
///
/// ```
/// use envigil::parse;
/// use std::time::Duration;
///
/// assert_eq!(parse::secs("30").unwrap(), Duration::from_secs(30));
/// assert!(parse::secs("abc").is_err());
/// assert!(parse::secs("-1").is_err());
/// ```
///
/// # Errors
///
/// Returns an error if the input string cannot be parsed as a non-negative
/// integer (`u64`).
pub fn secs(raw: &str) -> Result<Duration, String> {
    raw.trim()
        .parse::<u64>()
        .map(Duration::from_secs)
        .map_err(|e| format!("invalid number of seconds: {e}"))
}

/// Parse an integer number of milliseconds into a [`Duration`].
///
/// # Examples
///
/// ```
/// use envigil::parse;
/// use std::time::Duration;
///
/// assert_eq!(parse::millis("500").unwrap(), Duration::from_millis(500));
/// assert!(parse::millis("abc").is_err());
/// ```
///
/// # Errors
///
/// Returns an error if the input string cannot be parsed as a non-negative
/// integer (`u64`).
pub fn millis(raw: &str) -> Result<Duration, String> {
    raw.trim()
        .parse::<u64>()
        .map(Duration::from_millis)
        .map_err(|e| format!("invalid number of milliseconds: {e}"))
}

/// Parse a boolean value from a string.
///
/// Accepted values (case-insensitive):
/// - **true:** `true`, `1`, `yes`, `on`
/// - **false:** `false`, `0`, `no`, `off`
///
/// This is the preferred name for boolean parsing. [`flag`] is retained
/// as a deprecated alias for backward compatibility.
///
/// # Errors
///
/// Returns an error if the input does not match any of the accepted
/// boolean representations.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(parse::bool("true").unwrap(), true);
/// assert_eq!(parse::bool("YES").unwrap(), true);
/// assert_eq!(parse::bool("0").unwrap(), false);
/// assert_eq!(parse::bool("off").unwrap(), false);
/// assert!(parse::bool("maybe").is_err());
/// ```
#[allow(deprecated)]
pub fn bool(raw: &str) -> Result<bool, String> {
    flag(raw)
}

/// Parse a boolean flag.
///
/// **Deprecated:** use [`bool()`] instead. This function is retained for
/// backward compatibility and will be removed in a future major release.
///
/// Accepted values (case-insensitive):
/// - **true:** `true`, `1`, `yes`, `on`
/// - **false:** `false`, `0`, `no`, `off`
///
/// # Errors
///
/// Returns an error if the input does not match any of the accepted
/// boolean representations.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(parse::flag("true").unwrap(), true);
/// assert_eq!(parse::flag("YES").unwrap(), true);
/// assert_eq!(parse::flag("0").unwrap(), false);
/// assert_eq!(parse::flag("off").unwrap(), false);
/// assert!(parse::flag("maybe").is_err());
/// ```
#[deprecated(since = "0.4.0", note = "use `envigil::parse::bool` instead")]
pub fn flag(raw: &str) -> Result<bool, String> {
    match raw.trim().to_ascii_lowercase().as_str() {
        "true" | "1" | "yes" | "on" => Ok(true),
        "false" | "0" | "no" | "off" => Ok(false),
        other => Err(format!(
            "expected true/false, 1/0, yes/no, or on/off; got {other:?}"
        )),
    }
}

/// Parse a comma-separated list, trimming whitespace around items.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(
///     parse::list("a, b, c").unwrap(),
///     vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
/// );
/// assert_eq!(parse::list("").unwrap(), Vec::<String>::new());
/// ```
///
/// # Errors
///
/// This function never returns an error (the `Result` is always `Ok`).
pub fn list(raw: &str) -> Result<Vec<String>, String> {
    list_sep(',')(raw)
}

/// Parse a list separated by an arbitrary character.
///
/// Returns a closure suitable for [`VarBuilder::new`](crate::VarBuilder::new).
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// let parser = parse::list_sep(';');
/// assert_eq!(
///     parser("x; y; z").unwrap(),
///     vec!["x".to_owned(), "y".to_owned(), "z".to_owned()]
/// );
/// ```
///
/// # Errors
///
/// The returned closure never returns an error (the `Result` is always `Ok`).
pub fn list_sep(sep: char) -> impl Fn(&str) -> Result<Vec<String>, String> {
    move |raw| {
        if raw.trim().is_empty() {
            return Ok(Vec::new());
        }
        Ok(raw.split(sep).map(|s| s.trim().to_owned()).collect())
    }
}

/// Parse a duration string with units into a [`Duration`].
///
/// Supported units (case-insensitive): `ms` (milliseconds), `s` (seconds),
/// `m` (minutes), `h` (hours). Multiple components may be combined, with or
/// without spaces between them.
///
/// A bare number without a unit is rejected to avoid ambiguity.
///
/// # Examples
///
/// ```
/// use envigil::parse;
/// use std::time::Duration;
///
/// assert_eq!(parse::duration("30s").unwrap(), Duration::from_secs(30));
/// assert_eq!(parse::duration("5m 30s").unwrap(), Duration::from_secs(330));
/// assert_eq!(parse::duration("1h 2m").unwrap(), Duration::from_secs(3720));
/// assert_eq!(parse::duration("500ms").unwrap(), Duration::from_millis(500));
/// assert!(parse::duration("5").is_err()); // missing unit
/// ```
///
/// # Errors
///
/// Returns an error in the following cases:
/// - The input string is empty.
/// - A numeric value is missing or invalid (not a non-negative integer).
/// - A unit is missing after a number.
/// - An unknown unit is used (allowed: `ms`, `s`, `m`, `h`).
/// - The total duration overflows [`Duration`].
pub fn duration(raw: &str) -> Result<Duration, String> {
    let mut rest = raw.trim();
    if rest.is_empty() {
        return Err("duration must not be empty".to_owned());
    }

    let mut total = Duration::ZERO;

    while !rest.is_empty() {
        rest = rest.trim_start();
        if rest.is_empty() {
            break;
        }

        // Numeric component.
        let num_end = rest
            .find(|c: char| !c.is_ascii_digit())
            .unwrap_or(rest.len());
        if num_end == 0 {
            return Err(format!("expected a number in duration {raw:?}"));
        }
        let (num_str, after_num) = rest.split_at(num_end);
        let value: u64 = num_str
            .parse()
            .map_err(|e| format!("invalid number {num_str:?} in duration: {e}"))?;

        // Unit must follow the number directly.
        let unit_end = after_num
            .find(|c: char| !c.is_ascii_alphabetic())
            .unwrap_or(after_num.len());
        let (unit, tail) = after_num.split_at(unit_end);
        if unit.is_empty() {
            return Err(format!(
                "missing unit after {num_str:?} in duration {raw:?}"
            ));
        }

        let part = duration_component(value, unit)?;
        total = total
            .checked_add(part)
            .ok_or_else(|| format!("duration overflow for {raw:?}"))?;

        rest = tail;
    }

    Ok(total)
}

/// Convert a single `value + unit` pair into a [`Duration`].
///
/// # Errors
///
/// Returns an error if the unit is unknown or if the value overflows when
/// multiplied for minutes or hours.
fn duration_component(value: u64, unit: &str) -> Result<Duration, String> {
    match unit.to_ascii_lowercase().as_str() {
        "ms" => Ok(Duration::from_millis(value)),
        "s" => Ok(Duration::from_secs(value)),
        "m" => {
            let secs = value
                .checked_mul(60)
                .ok_or_else(|| format!("duration overflow for {value}{unit}"))?;
            Ok(Duration::from_secs(secs))
        }
        "h" => {
            let secs = value
                .checked_mul(3600)
                .ok_or_else(|| format!("duration overflow for {value}{unit}"))?;
            Ok(Duration::from_secs(secs))
        }
        other => Err(format!(
            "unknown duration unit {other:?}; expected ms, s, m, or h"
        )),
    }
}

/// Parse a byte-size string into a `u64` number of bytes.
///
/// Supported units (case-insensitive): `B`, `KB`, `MB`, `GB` (decimal) and
/// `KiB`, `MiB`, `GiB` (binary). A bare number is treated as bytes.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(parse::bytes("10MB").unwrap(), 10_000_000);
/// assert_eq!(parse::bytes("1GiB").unwrap(), 1_073_741_824);
/// assert_eq!(parse::bytes("512").unwrap(), 512);
/// assert!(parse::bytes("10XB").is_err());
/// ```
///
/// # Errors
///
/// Returns an error in the following cases:
/// - The input string is empty.
/// - A numeric value is missing or invalid (not a non-negative integer).
/// - An unknown byte unit is used (allowed: `B`, `KB`, `MB`, `GB`, `KiB`,
///   `MiB`, `GiB`; case-insensitive).
/// - The value overflows `u64` when multiplied by the unit multiplier.
pub fn bytes(raw: &str) -> Result<u64, String> {
    let raw = raw.trim();
    if raw.is_empty() {
        return Err("byte size must not be empty".to_owned());
    }

    // Split the leading digits from the trailing unit.
    let num_end = raw.find(|c: char| !c.is_ascii_digit()).unwrap_or(raw.len());
    if num_end == 0 {
        return Err(format!("expected a number of bytes, got {raw:?}"));
    }
    let (num_str, unit_raw) = raw.split_at(num_end);
    let value: u64 = num_str
        .parse()
        .map_err(|e| format!("invalid number {num_str:?}: {e}"))?;

    let unit = unit_raw.trim();
    if !unit.chars().all(|c| c.is_ascii_alphabetic()) {
        return Err(format!("invalid byte size {raw:?}"));
    }

    let multiplier: u64 = match unit.to_ascii_lowercase().as_str() {
        "" | "b" => 1,
        "kb" => 1_000,
        "mb" => 1_000_000,
        "gb" => 1_000_000_000,
        "kib" => 1_024,
        "mib" => 1_048_576,
        "gib" => 1_073_741_824,
        other => {
            return Err(format!(
                "unknown byte unit {other:?}; expected B, KB, MB, GB, KiB, MiB, or GiB"
            ));
        }
    };

    value
        .checked_mul(multiplier)
        .ok_or_else(|| format!("byte size overflow for {raw:?}"))
}

/// Parse a socket address into a [`std::net::SocketAddr`].
///
/// Accepts both IPv4 (`0.0.0.0:8080`) and IPv6 (`[::1]:443`) forms.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// let addr = parse::socket_addr("0.0.0.0:8080").unwrap();
/// assert_eq!(addr.to_string(), "0.0.0.0:8080");
///
/// let addr6 = parse::socket_addr("[::1]:443").unwrap();
/// assert_eq!(addr6.to_string(), "[::1]:443");
///
/// assert!(parse::socket_addr("not-an-address").is_err());
/// ```
///
/// # Errors
///
/// Returns an error if the input string cannot be parsed as a valid socket
/// address (IPv4 or IPv6 with a port).
pub fn socket_addr(raw: &str) -> Result<SocketAddr, String> {
    raw.trim()
        .parse::<SocketAddr>()
        .map_err(|e| format!("invalid socket address: {e}"))
}

/// Parse a URL string with basic validation and normalization.
///
/// This is a lightweight, zero-dependency parser suitable for environment
/// variables like `DATABASE_URL` or `WEBHOOK_URL`. It checks for:
/// - A valid scheme (ASCII letters, digits, `+`, `-`, `.`, followed by `://`)
/// - No whitespace or control characters
/// - Non-empty authority after `://`
///
/// The returned string is normalized: scheme is lowercased and surrounding
/// whitespace is trimmed. Trailing slashes are preserved as-is because
/// `/api/` and `/api` may be semantically different routes.
///
/// For strict RFC 3986 parsing, enable the `url` feature and use
/// [`strict_url`] instead.
///
/// # Errors
///
/// Returns an error if:
/// - The input is empty or contains only whitespace.
/// - The input contains internal whitespace or ASCII control characters.
/// - No `://` scheme separator is found.
/// - The scheme is empty, does not start with a letter, or contains
///   invalid characters.
/// - The authority portion after `://` is empty.
///
/// # Examples
///
/// ```
/// use envigil::parse;
///
/// assert_eq!(parse::url("HTTPS://Example.COM/path").unwrap(), "https://Example.COM/path");
/// assert_eq!(parse::url("postgres://localhost/db").unwrap(), "postgres://localhost/db");
/// assert!(parse::url("not-a-url").is_err());
/// assert!(parse::url("://missing-scheme").is_err());
/// ```
pub fn url(raw: &str) -> Result<String, String> {
    let trimmed = raw.trim();
    if trimmed.is_empty() {
        return Err("URL must not be empty".to_owned());
    }

    // Reject control characters and internal whitespace.
    if trimmed
        .chars()
        .any(|c| c.is_ascii_control() || c == ' ' || c == '\t')
    {
        return Err(format!(
            "URL contains invalid whitespace or control characters: {trimmed:?}"
        ));
    }

    // Extract scheme: must be [a-zA-Z][a-zA-Z0-9+.-]* followed by ://
    let scheme_end = trimmed
        .find("://")
        .ok_or_else(|| format!("URL must contain '://' scheme separator: {trimmed:?}"))?;

    if scheme_end == 0 {
        return Err(format!("URL scheme must not be empty: {trimmed:?}"));
    }

    let scheme = &trimmed[..scheme_end];
    if !scheme.starts_with(|c: char| c.is_ascii_alphabetic()) {
        return Err(format!("URL scheme must start with a letter: {trimmed:?}"));
    }
    if !scheme
        .chars()
        .all(|c| c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.')
    {
        return Err(format!(
            "URL scheme contains invalid characters: {trimmed:?}"
        ));
    }

    // Authority must not be empty after ://
    let after_scheme = &trimmed[scheme_end + 3..];
    if after_scheme.is_empty() {
        return Err(format!(
            "URL must have an authority after '://': {trimmed:?}"
        ));
    }

    // Normalize: lowercase scheme only. Trailing slash is preserved as-is
    // because `/api/` and `/api` may be semantically different routes.
    let normalized_scheme = scheme.to_ascii_lowercase();

    Ok(format!("{normalized_scheme}://{after_scheme}"))
}

/// Parse a URL using the `url` crate for strict RFC 3986 compliance.
///
/// Only available with the `url` feature enabled.
///
/// # Errors
///
/// Returns an error if the input is not a valid RFC 3986 URL as determined
/// by [`url::Url::parse`]. Common causes include missing scheme, invalid
/// host, or malformed percent-encoding.
///
/// # Examples
///
/// ```ignore
/// use envigil::parse;
///
/// let parsed = parse::strict_url("https://example.com/path?q=1").unwrap();
/// assert_eq!(parsed.host_str(), Some("example.com"));
/// ```
#[cfg(feature = "url")]
pub fn strict_url(raw: &str) -> Result<::url::Url, String> {
    ::url::Url::parse(raw.trim()).map_err(|e| format!("invalid URL: {e}"))
}

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

    #[test]
    fn secs_valid() {
        assert_eq!(secs("30").unwrap(), Duration::from_secs(30));
        assert_eq!(secs(" 10 ").unwrap(), Duration::from_secs(10));
        assert_eq!(secs("0").unwrap(), Duration::from_secs(0));
    }

    #[test]
    fn secs_invalid() {
        assert!(secs("abc").is_err());
        assert!(secs("-1").is_err());
        assert!(secs("1.5").is_err());
    }

    #[test]
    fn millis_valid() {
        assert_eq!(millis("500").unwrap(), Duration::from_millis(500));
        assert_eq!(millis("0").unwrap(), Duration::from_millis(0));
    }

    #[test]
    fn millis_invalid() {
        assert!(millis("abc").is_err());
        assert!(millis("-1").is_err());
    }

    #[test]
    #[allow(deprecated)]
    fn flag_true_variants() {
        for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
            assert!(flag(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    #[allow(deprecated)]
    fn flag_false_variants() {
        for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
            assert!(!flag(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    #[allow(deprecated)]
    fn flag_invalid() {
        assert!(flag("maybe").is_err());
        assert!(flag("2").is_err());
        assert!(flag("").is_err());
    }

    #[test]
    #[allow(deprecated)]
    fn flag_trims_whitespace() {
        assert!(flag(" true ").unwrap());
    }

    #[test]
    fn list_basic() {
        assert_eq!(
            list("a,b,c").unwrap(),
            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
        );
    }

    #[test]
    fn list_trims_whitespace() {
        assert_eq!(
            list(" a , b , c ").unwrap(),
            vec!["a".to_owned(), "b".to_owned(), "c".to_owned()]
        );
    }

    #[test]
    fn list_empty_string() {
        assert_eq!(list("").unwrap(), Vec::<String>::new());
        assert_eq!(list("   ").unwrap(), Vec::<String>::new());
    }

    #[test]
    fn list_single_item() {
        assert_eq!(list("solo").unwrap(), vec!["solo".to_owned()]);
    }

    #[test]
    fn list_sep_semicolon() {
        let parser = list_sep(';');
        assert_eq!(
            parser("x; y; z").unwrap(),
            vec!["x".to_owned(), "y".to_owned(), "z".to_owned()]
        );
    }

    #[test]
    fn list_sep_pipe() {
        let parser = list_sep('|');
        assert_eq!(parser("a|b").unwrap(), vec!["a".to_owned(), "b".to_owned()]);
    }

    #[test]
    fn list_sep_empty() {
        let parser = list_sep(';');
        assert_eq!(parser("").unwrap(), Vec::<String>::new());
    }

    #[test]
    fn duration_single_unit() {
        assert_eq!(duration("30s").unwrap(), Duration::from_secs(30));
        assert_eq!(duration("5m").unwrap(), Duration::from_secs(300));
        assert_eq!(duration("2h").unwrap(), Duration::from_secs(7200));
        assert_eq!(duration("500ms").unwrap(), Duration::from_millis(500));
    }

    #[test]
    fn duration_multiple_units() {
        assert_eq!(duration("5m 30s").unwrap(), Duration::from_secs(330));
        assert_eq!(duration("1h 2m 3s").unwrap(), Duration::from_secs(3723));
        assert_eq!(duration("1s 500ms").unwrap(), Duration::from_millis(1500));
    }

    #[test]
    fn duration_no_spaces_between_components() {
        assert_eq!(duration("5m30s").unwrap(), Duration::from_secs(330));
    }

    #[test]
    fn duration_surrounding_whitespace() {
        assert_eq!(duration(" 5m  30s ").unwrap(), Duration::from_secs(330));
    }

    #[test]
    fn duration_case_insensitive_units() {
        assert_eq!(duration("5M").unwrap(), Duration::from_secs(300));
        assert_eq!(duration("1H").unwrap(), Duration::from_secs(3600));
        assert_eq!(duration("250MS").unwrap(), Duration::from_millis(250));
    }

    #[test]
    fn duration_errors() {
        assert!(duration("").is_err());
        assert!(duration("   ").is_err());
        assert!(duration("5").is_err()); // missing unit
        assert!(duration("abc").is_err());
        assert!(duration("5x").is_err()); // unknown unit
        assert!(duration("m").is_err()); // missing number
        assert!(duration("5m abc").is_err()); // trailing garbage
    }

    #[test]
    fn duration_mul_overflow_is_error() {
        // Fits in u64, but *3600 overflows.
        assert!(duration("9999999999999999999h").is_err());
    }

    #[test]
    fn duration_add_overflow_is_error() {
        // u64::MAX seconds + 1 second overflows Duration.
        assert!(duration("18446744073709551615s 1s").is_err());
    }

    #[test]
    fn bytes_plain_number() {
        assert_eq!(bytes("1024").unwrap(), 1024);
        assert_eq!(bytes("0").unwrap(), 0);
    }

    #[test]
    fn bytes_decimal_units() {
        assert_eq!(bytes("1KB").unwrap(), 1_000);
        assert_eq!(bytes("10MB").unwrap(), 10_000_000);
        assert_eq!(bytes("2GB").unwrap(), 2_000_000_000);
    }

    #[test]
    fn bytes_binary_units() {
        assert_eq!(bytes("1KiB").unwrap(), 1_024);
        assert_eq!(bytes("1MiB").unwrap(), 1_048_576);
        assert_eq!(bytes("1GiB").unwrap(), 1_073_741_824);
    }

    #[test]
    fn bytes_b_suffix() {
        assert_eq!(bytes("5B").unwrap(), 5);
    }

    #[test]
    fn bytes_case_insensitive() {
        assert_eq!(bytes("10mb").unwrap(), 10_000_000);
        assert_eq!(bytes("1kib").unwrap(), 1_024);
        assert_eq!(bytes("2gb").unwrap(), 2_000_000_000);
    }

    #[test]
    fn bytes_whitespace_between_number_and_unit() {
        assert_eq!(bytes(" 10 MB ").unwrap(), 10_000_000);
    }

    #[test]
    fn bytes_errors() {
        assert!(bytes("").is_err());
        assert!(bytes("abc").is_err());
        assert!(bytes("MB").is_err()); // missing number
        assert!(bytes("10XB").is_err()); // unknown unit
        assert!(bytes("1.5KB").is_err()); // fractions not supported
        assert!(bytes("-5KB").is_err()); // negative not supported
    }

    #[test]
    fn bytes_overflow_is_error() {
        // Parses fine, but value * multiplier overflows u64.
        assert!(bytes("18446744073709551615GB").is_err());
    }

    #[test]
    fn socket_addr_ipv4() {
        let addr = socket_addr("0.0.0.0:8080").unwrap();
        assert_eq!(addr.to_string(), "0.0.0.0:8080");
    }

    #[test]
    fn socket_addr_ipv6() {
        let addr = socket_addr("[::1]:443").unwrap();
        assert_eq!(addr.to_string(), "[::1]:443");
    }

    #[test]
    fn socket_addr_trims_whitespace() {
        let addr = socket_addr("  127.0.0.1:80  ").unwrap();
        assert_eq!(addr.to_string(), "127.0.0.1:80");
    }

    #[test]
    fn socket_addr_errors() {
        assert!(socket_addr("").is_err());
        assert!(socket_addr("not-an-address").is_err());
        assert!(socket_addr("1.2.3.4").is_err()); // missing port
        assert!(socket_addr("999.999.999.999:80").is_err());
    }

    #[test]
    fn url_basic_http() {
        assert_eq!(url("http://example.com").unwrap(), "http://example.com");
    }

    #[test]
    fn url_normalizes_scheme_to_lowercase() {
        assert_eq!(
            url("HTTPS://Example.COM/path").unwrap(),
            "https://Example.COM/path"
        );
    }

    #[test]
    fn url_preserves_trailing_slash() {
        assert_eq!(url("https://example.com/").unwrap(), "https://example.com/");
        assert_eq!(
            url("https://example.com/path/").unwrap(),
            "https://example.com/path/"
        );
    }

    #[test]
    fn url_preserves_root_slash() {
        assert_eq!(url("https://example.com/").unwrap(), "https://example.com/");
    }

    #[test]
    fn url_trims_whitespace() {
        assert_eq!(
            url("  https://example.com  ").unwrap(),
            "https://example.com"
        );
    }

    #[test]
    fn url_custom_schemes() {
        assert_eq!(
            url("postgres://localhost/db").unwrap(),
            "postgres://localhost/db"
        );
        assert_eq!(
            url("redis+tls://cache:6379").unwrap(),
            "redis+tls://cache:6379"
        );
        assert_eq!(url("my-app.v2://host").unwrap(), "my-app.v2://host");
    }

    #[test]
    fn url_with_port_and_path() {
        assert_eq!(
            url("http://localhost:8080/api/v1").unwrap(),
            "http://localhost:8080/api/v1"
        );
    }

    #[test]
    fn url_with_query_and_fragment() {
        assert_eq!(
            url("https://example.com/path?key=val#frag").unwrap(),
            "https://example.com/path?key=val#frag"
        );
    }

    #[test]
    fn url_rejects_empty() {
        assert!(url("").is_err());
        assert!(url("   ").is_err());
    }

    #[test]
    fn url_rejects_no_scheme() {
        assert!(url("example.com").is_err());
        assert!(url("/just/a/path").is_err());
    }

    #[test]
    fn url_rejects_empty_scheme() {
        assert!(url("://no-scheme").is_err());
    }

    #[test]
    fn url_rejects_invalid_scheme_start() {
        assert!(url("1bad://host").is_err());
        assert!(url("-bad://host").is_err());
    }

    #[test]
    fn url_rejects_invalid_scheme_chars() {
        assert!(url("bad scheme://host").is_err());
        assert!(url("bad!scheme://host").is_err());
    }

    #[test]
    fn url_rejects_empty_authority() {
        assert!(url("http://").is_err());
    }

    #[test]
    fn url_rejects_whitespace_inside() {
        assert!(url("http://exam ple.com").is_err());
        assert!(url("http://example.com/pa th").is_err());
    }

    #[test]
    fn url_rejects_control_characters() {
        assert!(url("http://example.com\x00").is_err());
        assert!(url("http://example.\x01com").is_err());
    }

    #[test]
    fn url_error_messages_are_descriptive() {
        let msg = url("no-scheme").unwrap_err();
        assert!(msg.contains("://"), "message: {msg}");

        let msg = url("://empty").unwrap_err();
        assert!(msg.contains("scheme"), "message: {msg}");

        let msg = url("http://").unwrap_err();
        assert!(msg.contains("authority"), "message: {msg}");
    }

    #[test]
    fn bool_true_variants() {
        for v in ["true", "1", "yes", "on", "TRUE", "Yes", "ON"] {
            assert!(bool(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    fn bool_false_variants() {
        for v in ["false", "0", "no", "off", "FALSE", "No", "OFF"] {
            assert!(!bool(v).unwrap(), "input: {v}");
        }
    }

    #[test]
    fn bool_invalid() {
        assert!(bool("maybe").is_err());
        assert!(bool("2").is_err());
        assert!(bool("").is_err());
    }

    #[test]
    fn bool_trims_whitespace() {
        assert!(bool(" true ").unwrap());
    }

    #[test]
    #[allow(deprecated)]
    fn flag_still_works() {
        // Ensure deprecated alias continues to function.
        assert!(flag("true").unwrap());
        assert!(!flag("0").unwrap());
    }
}