Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.
Sign upstd::env::vars() panics on any non-utf8 env var, feels like a footgun #70251
Labels
Comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Consider some code that is looking for an env var that it knows should be valid UTF-8. It would be tempted to use
std::env::vars()for this:(It doesn't know the exact name of the env var, hence the need to enumerate every env var and test the key with
cond, rather than just usingstd::env::var().)But this will panic if an unrelated env var that isn't convertible to
Stringhappens to be enumerated first, becauseVarsuses.into_string().unwrap()on bothOsStrings that it gets fromVarsOs. This behavior is documented onstd::env::vars(), so it's by design.So, to be robust against this failure mode, the code has to use
std::env::vars_os()and test forString-iness itself:Env vars are almost always out of the hands of one's code, and can come from any number of sources even the user running the program may not account for. So it seems to me that
std::env::vars()as it's implemented today is a trivial way to crash unnecessarily and should never be used.It would be nice if it skipped non-UTF-8 env vars instead. Or, if it's necessary to preserve compatibility with the current behavior (which it has had since 1.0), there was a new function that did (
std::env::vars_utf8_only()?)