From f2c0f29248fa6f6d2c8d71fdfa2dfb86088dc4c7 Mon Sep 17 00:00:00 2001 From: Aris Merchant <22333129+inquisitivecrystal@users.noreply.github.com> Date: Wed, 9 Jun 2021 00:40:31 -0700 Subject: [PATCH] Change env var getters to error recoverably Before this, `std`'s env var getter functions would panic on receiving certain invalid inputs. This commit makes them return a `None` or `Err` instead. --- library/std/src/env.rs | 25 ++++++++++--------------- 1 file changed, 10 insertions(+), 15 deletions(-) diff --git a/library/std/src/env.rs b/library/std/src/env.rs index 64f88c1aba68e..c0f9cc1f64e9f 100644 --- a/library/std/src/env.rs +++ b/library/std/src/env.rs @@ -188,12 +188,8 @@ impl fmt::Debug for VarsOs { /// Errors if the environment variable is not present. /// Errors if the environment variable is not valid Unicode. If this is not desired, consider using /// [`var_os`]. -/// -/// # Panics -/// -/// This function may panic if `key` is empty, contains an ASCII equals sign -/// `'='` or the NUL character `'\0'`, or when the value contains the NUL -/// character. +/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. +/// May error when the value contains the NUL character. /// /// # Examples /// @@ -219,18 +215,18 @@ fn _var(key: &OsStr) -> Result { } /// Fetches the environment variable `key` from the current process, returning -/// [`None`] if the variable isn't set. -/// -/// # Panics -/// -/// This function may panic if `key` is empty, contains an ASCII equals sign -/// `'='` or the NUL character `'\0'`, or when the value contains the NUL -/// character. +/// [`None`] if the variable isn't set or there's another error. /// /// Note that the method will not check if the environment variable /// is valid Unicode. If you want to have an error on invalid UTF-8, /// use the [`var`] function instead. /// +/// # Errors +/// +/// Errors if the variable isn't set. +/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`. +/// May error when the value contains the NUL character. +/// /// # Examples /// /// ``` @@ -248,8 +244,7 @@ pub fn var_os>(key: K) -> Option { } fn _var_os(key: &OsStr) -> Option { - os_imp::getenv(key) - .unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e)) + os_imp::getenv(key).ok()? } /// The error type for operations interacting with environment variables.