docs

You are reading the docs for v0.1.2. Nabi 0.1.2 is no longer supported. Latest release: v0.1.3 →

#3.5. env:: - environment variables / args / directories

On this page

The std::env module provides a consistent entry point for accessing the process environment. Command-line arguments, environment variables and standard directory paths are gathered in one place, hiding OS differences.

#3.5.1. API

The functions and types the module exposes, at a glance. Path parameters follow the tier-wide argument conventions (Path is P: AsPath).

RawStr is a string holding the bytes exactly as the OS provided them (possibly not UTF-8). JoinPathsError occurs when one of the paths contains the separator (: / ;) or, on Windows, a "; its message names the character.

nabi
struct RawStr { /* OS bytes */ }

impl RawStr {
    fn len(self) -> usize;                       // byte length
    fn is_empty(self) -> bool;
    fn to_str(self) throws (Utf8Error) -> str;   // throws if not UTF-8
    fn to_str_lossy(self) -> str;                // ill-formed parts as U+FFFD
    fn as_bytes(self) -> Slice<u8>;              // a view, no copy
}
// RawStr: + Clone, PartialEq, Eq, Hash, Debug

struct JoinPathsError { .. }                     // private fields (0.5.10)
impl JoinPathsError {
    fn path(self) -> str;                        // the path that cannot be joined
    fn message(self) -> str;
}

On Windows the bytes are the OS's UTF-16 as WTF-8; there:

nabi
impl RawStr {
    fn from_wide(wide: Slice<u16>) -> RawStr;
    fn as_wide(self) -> Slice<u16>;              // a view of a list made for it
}

args, vars and RawStr::to_str_lossy replace each ill-formed part of the bytes with U+FFFD, one per maximal ill-formed subsequence as str::from_utf8_lossy does (2.15.6); on Windows a lone surrogate is one U+FFFD. args_os, vars_os and var_os keep the bytes.

#3.5.2. Examples

How these APIs work together in a real program. The following example shows the typical flow of command-line arguments, environment variables and PATH search in one go.

#3.5.3. set_var and remove_var are unsafe

set_var and remove_var change the environment of the whole process. The children it spawns later inherit it; to set one child's environment, use Command::env / env_remove (3.6), which is safe.

nabi
unsafe { try env::set_var("RUST_LOG", "debug"); }   // first thing in main
let child = try Command::new("tool").env("LEVEL", "2").spawn();   // safe: this child only

Both are unsafe fn. Safety: no other thread may read or write the environment during the call, other than through std::env. Nabi's own var, var_os, vars, vars_os, set_var and remove_var take one internal lock, so Nabi code alone does not race; C code that calls getenv or setenv (in a library reached through FFI, for one) does not take it, and a set_var racing with it is undefined behavior on POSIX platforms. A call is sound in a single-threaded program, and on Windows. The recommended pattern is to call set_var at program start, before spawning threads.

Both throw IoError. InvalidInput: the name is empty or holds = or NUL, or the value holds NUL; this check is the same on every target, Windows included. Any other failure is the OS error. Removing a variable that is not set is not an error. A program that wants a panic instead writes try!.

#3.5.4. impl / target

How each platform implements the same semantics:

Itemlinux/macos/windowswasi
argsargc/argv / GetCommandLinewasi:cli
var / varsgetenv / GetEnvironmentVariablewasi:cli
home_dir$HOME / %USERPROFILE%wasi (no concept)
temp_dir$TMPDIR, else /tmp / the first set of %TMP%, %TEMP%, %USERPROFILE%, %SystemRoot%, else C:\Windows (GetTempPath2W's order, read directly)wasi
config_dirXDG / %APPDATA%(no)
current_dirgetcwd / GetCurrentDirectoryW$PWD if absolute and reachable, else / (WASI has none; nabi run / nabi test pass the host's)
current_exe/proc/self/exe / _NSGetExecutablePath / GetModuleFileNameUnsupported (wasm32)

Standard paths use ~/Library/... on macOS, the XDG Base Directory spec on other Unix systems ($XDG_*_HOME is used only when it is an absolute path; otherwise ~/.config and so on), and environment variables on Windows: %USERPROFILE% for home, %APPDATA% for config and data, %LOCALAPPDATA% for cache. The result is none when the variable it reads ($HOME, or the Windows one) is unset or empty.

Found a mistake? Edit this page on GitHub. Last updated