pub struct EnvField<T, Variant = UseFromStr>(/* private fields */);
Expand description

A field that deserializes either as T or as String with all environment variables expanded via the shellexpand crate.

By default, it requires T to implement the FromStr trait for deserialization from String after environment variables expansion.

You can use the UseDeserialize to bypass the FromStr and deserialize the T directly from the string with all environment variables expanded.

The EnvField serializes transparently as the T type if the T is serializable.

Works nicely with Option, Vec, and #[serde(default)].

Note: if you want to wrap all the fields of a struct or an enum with the EnvField, you might want to use the env_field_wrap attribute.

Examples

Basic
#[derive(Serialize, Deserialize)]
struct Example {
    name: EnvField<String>,
    size: EnvField<usize>,
    num: EnvField<i32>,
}

std::env::set_var("SIZE", "100");

let de: Example = toml::from_str(r#"
    name = "${NAME:-Default Name}"

    size = "$SIZE"

    num = 42
"#).unwrap();

assert_eq!(&de.name, "Default Name");
assert_eq!(de.size, 100);
assert_eq!(de.num, 42);
Optional fields
#[derive(Serialize, Deserialize)]
struct Example {
    required: EnvField<i32>,
    optional: Option<EnvField<i32>>,
}

let de: Example = toml::from_str(r#"
    required = 512
"#).unwrap();

assert_eq!(de.required, 512);
assert!(de.optional.is_none());

std::env::set_var("OPTIONAL", "-1024");
let de: Example = toml::from_str(r#"
    required = 512
    optional = "$OPTIONAL"
"#).unwrap();

assert_eq!(de.required, 512);
assert_eq!(de.optional.unwrap(), -1024);

let de: Example = toml::from_str(r#"
    required = 512
    optional = 42
"#).unwrap();

assert_eq!(de.required, 512);
assert_eq!(de.optional.unwrap(), 42);
Sequences
#[derive(Serialize, Deserialize)]
struct Example {
    seq: Vec<EnvField<i32>>,
}

std::env::set_var("NUM", "1000");
let de: Example = toml::from_str(r#"
    seq = [
        12, "$NUM", 145,
    ]
"#).unwrap();

assert_eq!(de.seq[0], 12);
assert_eq!(de.seq[1], 1000);
assert_eq!(de.seq[2], 145);
Defaults
use derive_more::FromStr;

#[derive(Serialize, Deserialize)]
struct Example {
    #[serde(default)]
    num: EnvField<NumWithDefault>,
}

#[derive(Serialize, Deserialize, FromStr)]
#[serde(transparent)]
struct NumWithDefault(i32);
impl Default for NumWithDefault {
    fn default() -> Self {
        Self(42)
    }
}

let de: Example = toml::from_str("").unwrap();
assert_eq!(de.num.0, 42);

let de: Example = toml::from_str(r#"
    num = 100
"#).unwrap();
assert_eq!(de.num.0, 100);

std::env::set_var("SOME_NUM", "555");
let de: Example = toml::from_str(r#"
    num = "$SOME_NUM"
"#).unwrap();
assert_eq!(de.num.0, 555);
Deserialization without FromStr
use serde_env_field::UseDeserialize;

#[derive(Serialize, Deserialize)]
struct Example {
    variant: EnvField<Variants, UseDeserialize>
}

#[derive(Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
enum Variants {
    AUsefullVariant,
    AnotherCoolVariant,
}

let de: Example = toml::from_str(r#"
    variant = "a-usefull-variant"
"#).unwrap();
assert!(matches!(*de.variant, Variants::AUsefullVariant));

std::env::set_var("SELECTED_VARIANT", "another-cool-variant");
let de: Example = toml::from_str(r#"
    variant = "$SELECTED_VARIANT"
"#).unwrap();
assert!(matches!(*de.variant, Variants::AnotherCoolVariant));
Deserialization with FromStr
#[derive(Serialize, Deserialize)]
struct Example {
    inner: EnvField<Inner>,
}

#[derive(Serialize, Deserialize)]
struct Inner {
    // We can use `EnvField` in inner structs
    num: EnvField<i32>,

    sym: EnvField<String>,
}

impl FromStr for Inner {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        let mut split = s.split(';');

        let num = split
            .next()
            .unwrap()
            .parse()
            .map_err(|err: ParseIntError| err.to_string())?;

        let sym = split
            .next()
            .unwrap()
            .to_string()
            .into();

        Ok(Self {
            num,
            sym
        })
    }
}

std::env::set_var("INNER_NUM", "2048");
std::env::set_var("INNER_SYM", "Hi");
let de: Example = toml::from_str(r#"
    inner = "$INNER_NUM;$INNER_SYM"
"#).unwrap();

assert_eq!(de.inner.num, 2048);
assert_eq!(&de.inner.sym, "Hi");


let de: Example = toml::from_str(r#"
    [inner]
    num = -500
    sym = "Hello"
"#).unwrap();

assert_eq!(de.inner.num, -500);
assert_eq!(&de.inner.sym, "Hello");

Implementations§

source§

impl<T, V> EnvField<T, V>

source

pub fn into_inner(self) -> T

Unwraps the value, consuming the env field.

Trait Implementations§

source§

impl<T: Add, V> Add<T> for EnvField<T, V>

§

type Output = <T as Add>::Output

The resulting type after applying the + operator.
source§

fn add(self, rhs: T) -> Self::Output

Performs the + operation. Read more
source§

impl<T: Add, V> Add for EnvField<T, V>

§

type Output = <T as Add>::Output

The resulting type after applying the + operator.
source§

fn add(self, rhs: Self) -> Self::Output

Performs the + operation. Read more
source§

impl<T: AddAssign, V> AddAssign<T> for EnvField<T, V>

source§

fn add_assign(&mut self, rhs: T)

Performs the += operation. Read more
source§

impl<T: AddAssign, V> AddAssign for EnvField<T, V>

source§

fn add_assign(&mut self, rhs: Self)

Performs the += operation. Read more
source§

impl<T: BitAnd, V> BitAnd<T> for EnvField<T, V>

§

type Output = <T as BitAnd>::Output

The resulting type after applying the & operator.
source§

fn bitand(self, rhs: T) -> Self::Output

Performs the & operation. Read more
source§

impl<T: BitAnd, V> BitAnd for EnvField<T, V>

§

type Output = <T as BitAnd>::Output

The resulting type after applying the & operator.
source§

fn bitand(self, rhs: Self) -> Self::Output

Performs the & operation. Read more
source§

impl<T: BitAndAssign, V> BitAndAssign<T> for EnvField<T, V>

source§

fn bitand_assign(&mut self, rhs: T)

Performs the &= operation. Read more
source§

impl<T: BitAndAssign, V> BitAndAssign for EnvField<T, V>

source§

fn bitand_assign(&mut self, rhs: Self)

Performs the &= operation. Read more
source§

impl<T: BitOr, V> BitOr<T> for EnvField<T, V>

§

type Output = <T as BitOr>::Output

The resulting type after applying the | operator.
source§

fn bitor(self, rhs: T) -> Self::Output

Performs the | operation. Read more
source§

impl<T: BitOr, V> BitOr for EnvField<T, V>

§

type Output = <T as BitOr>::Output

The resulting type after applying the | operator.
source§

fn bitor(self, rhs: Self) -> Self::Output

Performs the | operation. Read more
source§

impl<T: BitOrAssign, V> BitOrAssign<T> for EnvField<T, V>

source§

fn bitor_assign(&mut self, rhs: T)

Performs the |= operation. Read more
source§

impl<T: BitOrAssign, V> BitOrAssign for EnvField<T, V>

source§

fn bitor_assign(&mut self, rhs: Self)

Performs the |= operation. Read more
source§

impl<T: BitXor, V> BitXor<T> for EnvField<T, V>

§

type Output = <T as BitXor>::Output

The resulting type after applying the ^ operator.
source§

fn bitxor(self, rhs: T) -> Self::Output

Performs the ^ operation. Read more
source§

impl<T: BitXor, V> BitXor for EnvField<T, V>

§

type Output = <T as BitXor>::Output

The resulting type after applying the ^ operator.
source§

fn bitxor(self, rhs: Self) -> Self::Output

Performs the ^ operation. Read more
source§

impl<T: BitXorAssign, V> BitXorAssign<T> for EnvField<T, V>

source§

fn bitxor_assign(&mut self, rhs: T)

Performs the ^= operation. Read more
source§

impl<T: BitXorAssign, V> BitXorAssign for EnvField<T, V>

source§

fn bitxor_assign(&mut self, rhs: Self)

Performs the ^= operation. Read more
source§

impl<T: Clone, V> Clone for EnvField<T, V>

source§

fn clone(&self) -> Self

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl<T: Debug, V> Debug for EnvField<T, V>

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl<T: Default, V> Default for EnvField<T, V>

source§

fn default() -> Self

Returns the “default value” for a type. Read more
source§

impl<T, V> Deref for EnvField<T, V>

§

type Target = T

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl<T, V> DerefMut for EnvField<T, V>

source§

fn deref_mut(&mut self) -> &mut Self::Target

Mutably dereferences the value.
source§

impl<'de, T> Deserialize<'de> for EnvField<T, UseFromStr>
where T: Deserialize<'de> + FromStr, <T as FromStr>::Err: Display,

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<'de, T> Deserialize<'de> for EnvField<T, UseDeserialize>
where T: Deserialize<'de>,

source§

fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>,

Deserialize this value from the given Serde deserializer. Read more
source§

impl<T: Div, V> Div<T> for EnvField<T, V>

§

type Output = <T as Div>::Output

The resulting type after applying the / operator.
source§

fn div(self, rhs: T) -> Self::Output

Performs the / operation. Read more
source§

impl<T: Div, V> Div for EnvField<T, V>

§

type Output = <T as Div>::Output

The resulting type after applying the / operator.
source§

fn div(self, rhs: Self) -> Self::Output

Performs the / operation. Read more
source§

impl<T: DivAssign, V> DivAssign<T> for EnvField<T, V>

source§

fn div_assign(&mut self, rhs: T)

Performs the /= operation. Read more
source§

impl<T: DivAssign, V> DivAssign for EnvField<T, V>

source§

fn div_assign(&mut self, rhs: Self)

Performs the /= operation. Read more
source§

impl<T, V> From<T> for EnvField<T, V>

source§

fn from(value: T) -> Self

Converts to this type from the input type.
source§

impl<T: FromStr, V> FromStr for EnvField<T, V>

§

type Err = <T as FromStr>::Err

The associated error which can be returned from parsing.
source§

fn from_str(s: &str) -> Result<Self, Self::Err>

Parses a string s to return a value of this type. Read more
source§

impl<T: Mul, V> Mul<T> for EnvField<T, V>

§

type Output = <T as Mul>::Output

The resulting type after applying the * operator.
source§

fn mul(self, rhs: T) -> Self::Output

Performs the * operation. Read more
source§

impl<T: Mul, V> Mul for EnvField<T, V>

§

type Output = <T as Mul>::Output

The resulting type after applying the * operator.
source§

fn mul(self, rhs: Self) -> Self::Output

Performs the * operation. Read more
source§

impl<T: MulAssign, V> MulAssign<T> for EnvField<T, V>

source§

fn mul_assign(&mut self, rhs: T)

Performs the *= operation. Read more
source§

impl<T: MulAssign, V> MulAssign for EnvField<T, V>

source§

fn mul_assign(&mut self, rhs: Self)

Performs the *= operation. Read more
source§

impl<T: Neg, V> Neg for EnvField<T, V>

§

type Output = <T as Neg>::Output

The resulting type after applying the - operator.
source§

fn neg(self) -> Self::Output

Performs the unary - operation. Read more
source§

impl<T: Not, V> Not for EnvField<T, V>

§

type Output = <T as Not>::Output

The resulting type after applying the ! operator.
source§

fn not(self) -> Self::Output

Performs the unary ! operation. Read more
source§

impl<T: Ord, V> Ord for EnvField<T, V>

source§

fn cmp(&self, other: &Self) -> Ordering

This method returns an Ordering between self and other. Read more
1.21.0 · source§

fn max(self, other: Self) -> Self
where Self: Sized,

Compares and returns the maximum of two values. Read more
1.21.0 · source§

fn min(self, other: Self) -> Self
where Self: Sized,

Compares and returns the minimum of two values. Read more
1.50.0 · source§

fn clamp(self, min: Self, max: Self) -> Self
where Self: Sized + PartialOrd,

Restrict a value to a certain interval. Read more
source§

impl<T: PartialEq, V> PartialEq<T> for EnvField<T, V>

source§

fn eq(&self, other: &T) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialEq<str>, V> PartialEq<str> for EnvField<T, V>

source§

fn eq(&self, other: &str) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialEq, V> PartialEq for EnvField<T, V>

source§

fn eq(&self, other: &Self) -> bool

This method tests for self and other values to be equal, and is used by ==.
1.0.0 · source§

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
source§

impl<T: PartialOrd, V> PartialOrd<T> for EnvField<T, V>

source§

fn partial_cmp(&self, other: &T) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T: PartialOrd, V> PartialOrd for EnvField<T, V>

source§

fn partial_cmp(&self, other: &Self) -> Option<Ordering>

This method returns an ordering between self and other values if one exists. Read more
1.0.0 · source§

fn lt(&self, other: &Rhs) -> bool

This method tests less than (for self and other) and is used by the < operator. Read more
1.0.0 · source§

fn le(&self, other: &Rhs) -> bool

This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
1.0.0 · source§

fn gt(&self, other: &Rhs) -> bool

This method tests greater than (for self and other) and is used by the > operator. Read more
1.0.0 · source§

fn ge(&self, other: &Rhs) -> bool

This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
source§

impl<T: Rem, V> Rem<T> for EnvField<T, V>

§

type Output = <T as Rem>::Output

The resulting type after applying the % operator.
source§

fn rem(self, rhs: T) -> Self::Output

Performs the % operation. Read more
source§

impl<T: Rem, V> Rem for EnvField<T, V>

§

type Output = <T as Rem>::Output

The resulting type after applying the % operator.
source§

fn rem(self, rhs: Self) -> Self::Output

Performs the % operation. Read more
source§

impl<T: RemAssign, V> RemAssign<T> for EnvField<T, V>

source§

fn rem_assign(&mut self, rhs: T)

Performs the %= operation. Read more
source§

impl<T: RemAssign, V> RemAssign for EnvField<T, V>

source§

fn rem_assign(&mut self, rhs: Self)

Performs the %= operation. Read more
source§

impl<T: Serialize, V> Serialize for EnvField<T, V>

source§

fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,

Serialize this value into the given Serde serializer. Read more
source§

impl<T: Shl, V> Shl<T> for EnvField<T, V>

§

type Output = <T as Shl>::Output

The resulting type after applying the << operator.
source§

fn shl(self, rhs: T) -> Self::Output

Performs the << operation. Read more
source§

impl<T: Shl, V> Shl for EnvField<T, V>

§

type Output = <T as Shl>::Output

The resulting type after applying the << operator.
source§

fn shl(self, rhs: Self) -> Self::Output

Performs the << operation. Read more
source§

impl<T: ShlAssign, V> ShlAssign<T> for EnvField<T, V>

source§

fn shl_assign(&mut self, rhs: T)

Performs the <<= operation. Read more
source§

impl<T: ShlAssign, V> ShlAssign for EnvField<T, V>

source§

fn shl_assign(&mut self, rhs: Self)

Performs the <<= operation. Read more
source§

impl<T: Shr, V> Shr<T> for EnvField<T, V>

§

type Output = <T as Shr>::Output

The resulting type after applying the >> operator.
source§

fn shr(self, rhs: T) -> Self::Output

Performs the >> operation. Read more
source§

impl<T: Shr, V> Shr for EnvField<T, V>

§

type Output = <T as Shr>::Output

The resulting type after applying the >> operator.
source§

fn shr(self, rhs: Self) -> Self::Output

Performs the >> operation. Read more
source§

impl<T: ShrAssign, V> ShrAssign<T> for EnvField<T, V>

source§

fn shr_assign(&mut self, rhs: T)

Performs the >>= operation. Read more
source§

impl<T: ShrAssign, V> ShrAssign for EnvField<T, V>

source§

fn shr_assign(&mut self, rhs: Self)

Performs the >>= operation. Read more
source§

impl<T: Sub, V> Sub<T> for EnvField<T, V>

§

type Output = <T as Sub>::Output

The resulting type after applying the - operator.
source§

fn sub(self, rhs: T) -> Self::Output

Performs the - operation. Read more
source§

impl<T: Sub, V> Sub for EnvField<T, V>

§

type Output = <T as Sub>::Output

The resulting type after applying the - operator.
source§

fn sub(self, rhs: Self) -> Self::Output

Performs the - operation. Read more
source§

impl<T: SubAssign, V> SubAssign<T> for EnvField<T, V>

source§

fn sub_assign(&mut self, rhs: T)

Performs the -= operation. Read more
source§

impl<T: SubAssign, V> SubAssign for EnvField<T, V>

source§

fn sub_assign(&mut self, rhs: Self)

Performs the -= operation. Read more
source§

impl<T: Copy, V> Copy for EnvField<T, V>

source§

impl<T: Eq, V> Eq for EnvField<T, V>

Auto Trait Implementations§

§

impl<T, Variant> RefUnwindSafe for EnvField<T, Variant>
where T: RefUnwindSafe, Variant: RefUnwindSafe,

§

impl<T, Variant> Send for EnvField<T, Variant>
where T: Send, Variant: Send,

§

impl<T, Variant> Sync for EnvField<T, Variant>
where T: Sync, Variant: Sync,

§

impl<T, Variant> Unpin for EnvField<T, Variant>
where T: Unpin, Variant: Unpin,

§

impl<T, Variant> UnwindSafe for EnvField<T, Variant>
where T: UnwindSafe, Variant: UnwindSafe,

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<!> for T

source§

fn from(t: !) -> T

Converts to this type from the input type.
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> Serialize for T
where T: Serialize + ?Sized,

source§

fn erased_serialize(&self, serializer: &mut dyn Serializer) -> Result<Ok, Error>

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
source§

impl<T> DeserializeOwned for T
where T: for<'de> Deserialize<'de>,