envigil 0.3.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
//! 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());
/// ```
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());
/// ```
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 flag.
///
/// Accepted values (case-insensitive):
/// - **true:** `true`, `1`, `yes`, `on`
/// - **false:** `false`, `0`, `no`, `off`
///
/// # 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());
/// ```
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());
/// ```
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()]
/// );
/// ```
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
/// ```
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`].
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());
/// ```
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());
/// ```
pub fn socket_addr(raw: &str) -> Result<SocketAddr, String> {
    raw.trim()
        .parse::<SocketAddr>()
        .map_err(|e| format!("invalid socket address: {e}"))
}

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

    // -- secs --

    #[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());
    }

    // -- millis --

    #[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());
    }

    // -- flag --

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

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

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

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

    // -- list --

    #[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()]);
    }

    // -- list_sep --

    #[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());
    }

    // -- duration --

    #[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());
    }

    // -- bytes --

    #[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());
    }

    // -- socket_addr --

    #[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());
    }
}