Skip to content

Commit f2c0f29

Browse files
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.
1 parent d5a406b commit f2c0f29

File tree

1 file changed

+10
-15
lines changed

1 file changed

+10
-15
lines changed

library/std/src/env.rs

+10-15
Original file line numberDiff line numberDiff line change
@@ -188,12 +188,8 @@ impl fmt::Debug for VarsOs {
188188
/// Errors if the environment variable is not present.
189189
/// Errors if the environment variable is not valid Unicode. If this is not desired, consider using
190190
/// [`var_os`].
191-
///
192-
/// # Panics
193-
///
194-
/// This function may panic if `key` is empty, contains an ASCII equals sign
195-
/// `'='` or the NUL character `'\0'`, or when the value contains the NUL
196-
/// character.
191+
/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`.
192+
/// May error when the value contains the NUL character.
197193
///
198194
/// # Examples
199195
///
@@ -219,18 +215,18 @@ fn _var(key: &OsStr) -> Result<String, VarError> {
219215
}
220216

221217
/// Fetches the environment variable `key` from the current process, returning
222-
/// [`None`] if the variable isn't set.
223-
///
224-
/// # Panics
225-
///
226-
/// This function may panic if `key` is empty, contains an ASCII equals sign
227-
/// `'='` or the NUL character `'\0'`, or when the value contains the NUL
228-
/// character.
218+
/// [`None`] if the variable isn't set or there's another error.
229219
///
230220
/// Note that the method will not check if the environment variable
231221
/// is valid Unicode. If you want to have an error on invalid UTF-8,
232222
/// use the [`var`] function instead.
233223
///
224+
/// # Errors
225+
///
226+
/// Errors if the variable isn't set.
227+
/// May error if the `key` is empty, contains an ASCII equals sign `'='`, or contains the NUL character `'\0'`.
228+
/// May error when the value contains the NUL character.
229+
///
234230
/// # Examples
235231
///
236232
/// ```
@@ -248,8 +244,7 @@ pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
248244
}
249245

250246
fn _var_os(key: &OsStr) -> Option<OsString> {
251-
os_imp::getenv(key)
252-
.unwrap_or_else(|e| panic!("failed to get environment variable `{:?}`: {}", key, e))
247+
os_imp::getenv(key).ok()?
253248
}
254249

255250
/// The error type for operations interacting with environment variables.

0 commit comments

Comments
 (0)