Skip to content

Commit 1f41a19

Browse files
committed
chore: util methods
1 parent 9fb518f commit 1f41a19

File tree

2 files changed

+40
-1
lines changed

2 files changed

+40
-1
lines changed

Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ name = "init4-bin-base"
44
description = "Internal utilities for binaries produced by the init4 team"
55
keywords = ["init4", "bin", "base"]
66

7-
version = "0.3.0"
7+
version = "0.3.1"
88
edition = "2021"
99
rust-version = "1.81"
1010
authors = ["init4", "James Prestwich"]

src/utils/from_env.rs

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,45 @@ pub trait FromEnvVar: core::fmt::Debug + Sized + 'static {
346346

347347
/// Load the primitive from the environment at the given variable.
348348
fn from_env_var(env_var: &str) -> Result<Self, FromEnvErr<Self::Error>>;
349+
350+
/// Load the primitive from the environment at the given variable. If the
351+
/// variable is unset or empty, return the default value.
352+
///
353+
354+
fn from_env_var_or(env_var: &str, default: Self) -> Result<Self, FromEnvErr<Self::Error>> {
355+
match Self::from_env_var(env_var) {
356+
Ok(v) => Ok(v),
357+
Err(FromEnvErr::Empty(_)) | Err(FromEnvErr::EnvError(_, _)) => Ok(default),
358+
Err(e) => Err(e),
359+
}
360+
}
361+
362+
/// Load the primitive from the environment at the given variable. If the
363+
/// variable is unset or empty, call the provided function to get the
364+
/// default value.
365+
///
366+
/// This function will return an error if the environment variable is set
367+
/// but cannot be parsed.
368+
fn from_env_var_or_else(
369+
env_var: &str,
370+
default: impl FnOnce() -> Self,
371+
) -> Result<Self, FromEnvErr<Self::Error>> {
372+
match Self::from_env_var(env_var) {
373+
Ok(v) => Ok(v),
374+
Err(FromEnvErr::Empty(_)) | Err(FromEnvErr::EnvError(_, _)) => Ok(default()),
375+
Err(e) => Err(e),
376+
}
377+
}
378+
379+
/// Load the primitive from the environment at the given variable. If the
380+
/// variable is unset or empty, return the value generated by
381+
/// [`Default::default`].
382+
fn from_env_var_or_default(env_var: &str) -> Result<Self, FromEnvErr<Self::Error>>
383+
where
384+
Self: Default,
385+
{
386+
Self::from_env_var_or_else(env_var, Self::default)
387+
}
349388
}
350389

351390
impl<T> FromEnvVar for Option<T>

0 commit comments

Comments
 (0)