@@ -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
351390impl < T > FromEnvVar for Option < T >
0 commit comments