env
A safe drop-in wrapper for std::env::set_var and remove_var on modern Rust.
Repository Health
Technical Analysis
env is a tiny Rust crate that restores a safe interface for setting and removing environment variables. As of Rust PR #124636, std::env::set_var and std::env::remove_var became unsafe because mutating the environment is not sound in a multi-threaded Unix process. This crate wraps those functions with a runtime check so you can call them safely again.
Instead of forcing an unsafe block on every call site, env exposes set_var and remove_var that return Option<()> — performing the mutation and returning Some(()) only when it is provably safe (single-threaded, or on operating systems with a thread-safe environment such as Windows, illumos, and NetBSD), and None otherwise. It re-exports the rest of std::env, so it can be used as a drop-in replacement for the standard module.
What You Get
- Safe
set_varandremove_varfunctions that returnOption<()>instead of requiringunsafe - A runtime thread-safety check that avoids undoing Rust’s soundness guarantees
- A full re-export of
std::env, usable as a drop-in module replacement - A fast-path constant that skips the check on OSes with a thread-safe environment
- A minimal footprint — a single small dependency (
num_threads)
Common Use Cases
- Setting environment variables in application startup code without scattering
unsafeblocks - Migrating code to newer Rust editions where
set_var/remove_varbecame unsafe - Configuring the environment early in tests or single-threaded contexts
- Wrapping environment mutation behind a fallible API that signals when it is unsafe
Under The Hood
Architecture — The entire crate is a single src/lib.rs (~80 lines). It pub use std::env::* to inherit the standard module’s surface, then defines its own set_var/remove_var that shadow the unsafe originals. A const SAFE computed from std::env::consts::OS short-circuits the check on operating systems known to have a thread-safe environment; otherwise it defers to num_threads::is_single_threaded(). The mutation is performed inside an unsafe block that the crate proves sound by the surrounding guard.
Tech Stack — Pure Rust on edition 2024, with exactly one runtime dependency, num_threads, used to detect whether the process is single-threaded.
Code Quality — Small and carefully documented, with #![forbid(clippy::missing_safety_doc)], thorough doc comments including safety and panic sections, and doctests demonstrating usage. There is no separate test suite beyond the doctests, which is reasonable given the size.
API Design — Intentionally mirrors std::env so it reads as a drop-in replacement. The one semantic change — returning Option<()> marked #[must_use] — is well signposted so callers must acknowledge that the mutation may be skipped.