← std

std/env.kur

//! The environment the process was started with. The library never changes
//! it, so the value `getenv` finds stays put while it is copied; foreign
//! code that calls `setenv` or `putenv` while another thread reads here
//! breaks that.
use package as std;

use alloc::buffer::Buffer!;
use core::fmt::Writer;
use core::cstr::cstr_len;
use core::option::Option;
use core::slice::ReadBytes;
use libc::env::kur_libc_env_get;
use libc::fs::kur_libc_fs_release;
use std::io::c_string;

/// The value of the environment variable `name`, any byte view, copied into
/// a buffer of its own; `None` when it is unset, or when `name` holds a NUL
/// or an `=`, which no variable's name does.
forall C, S where ReadBytes[C, S], Copy[S].
fn variable(&cx: C, name: S) -> Option[Buffer!] {
    var text = c_string(&cx, name);
    let p = unsafe &text.as_ptr();
    // `p` holds the name and a NUL; the result is a copy `strdup` made.
    let value = unsafe kur_libc_env_get(p, &text.len() - 1usize);
    text.destroy();
    if unsafe (value as usize) == 0usize {
        Option::None
    } else {
        let len = unsafe cstr_len(value);
        let output = unsafe Buffer!::new().write_raw(value, len);
        let unit = unsafe kur_libc_fs_release(value);
        Option::Some.(output)
    }
}