1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
use nstd_collections::vec::*;
use std::{
    env,
    ffi::{CStr, CString},
    os::raw::{c_char, c_int, c_void},
    ptr,
};
#[allow(non_camel_case_types)]
type byte = u8;

/// Generates `nstd_std_env_path_to_exe` and `nstd_std_env_current_dir` functions.
macro_rules! nstd_path_fns {
    ($fn_name: ident, $env_fn: ident) => {
        #[no_mangle]
        pub unsafe extern "C" fn $fn_name(errc: *mut c_int) -> *mut c_char {
            match env::$env_fn() {
                Ok(path) => {
                    *errc = 0;
                    let mut path = path.to_string_lossy().to_string();
                    path.push('\0');
                    CString::from_vec_unchecked(path.into_bytes()).into_raw()
                }
                _ => {
                    *errc = 1;
                    ptr::null_mut()
                }
            }
        }
    };
}
nstd_path_fns!(nstd_std_env_path_to_exe, current_exe);
nstd_path_fns!(nstd_std_env_current_dir, current_dir);

/// Returns the path of a temporary directory.
/// Use `nstd_std_env_free_path` to free memory allocated by this function.
/// Returns: `char *path` - The path of the temp dir.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_temp_dir() -> *mut c_char {
    match env::temp_dir().into_os_string().into_string() {
        Ok(path) => CString::from_vec_unchecked(path.into_bytes()).into_raw(),
        _ => ptr::null_mut(),
    }
}

/// Frees memory allocated by `nstd_std_env_path_to_exe`,  `nstd_std_env_current_dir` or
/// `nstd_std_env_temp_dir`.
/// Parameters:
///     `char **path` - String from `nstd_std_env_path_to_exe` or `nstd_std_env_current_dir`.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_free_path(path: *mut *mut c_char) {
    static_nstd_free_cstring(path);
}

/// Sets the current working directory.
/// Parameters:
///     `const char *const path` - The new working directory.
/// Returns: `int errc` - Nonzero on error.
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_set_current_dir(path: *const c_char) -> c_int {
    match CStr::from_ptr(path).to_str() {
        Ok(path) => match env::set_current_dir(path) {
            Ok(_) => 0,
            _ => 1,
        },
        _ => 1,
    }
}

/// Returns a vector of strings that contain the cmd args that the program was started with.
/// Returns: `NSTDVec args` - The command line arguments.
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_args() -> NSTDVec {
    const ELEMENT_SIZE: usize = std::mem::size_of::<*mut c_char>();
    let args_iter = env::args().collect::<Vec<String>>();
    let mut args = nstd_std_collections_vec_new_with_capacity(ELEMENT_SIZE, args_iter.len());
    if !args.data.is_null() {
        for arg in args_iter {
            let mut bytes = arg.into_bytes();
            bytes.push(0);
            let cstr = CString::from_vec_unchecked(bytes).into_raw();
            let cstrptr = &cstr as *const *mut c_char as *const c_void;
            nstd_std_collections_vec_push(&mut args, cstrptr);
        }
    }
    args
}

/// Frees memory allocated by `nstd_std_env_args`.
/// Parameters:
///     `NSTDVec *const args` - Returned from `nstd_std_env_args`.
/// Returns: `int errc` - Nonzero on error.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_free_args(args: &mut NSTDVec) -> c_int {
    for i in 0..args.size {
        let cstrptr = nstd_std_collections_vec_get(args, i) as *const *mut c_char;
        if !cstrptr.is_null() {
            CString::from_raw(*cstrptr);
        }
    }
    nstd_std_collections_vec_free(args)
}

/// Sets an environment variable.
/// Parameters:
///     `const char *const k` - The var key.
///     `const char *const v` - The var value.
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_set_var(k: *const c_char, v: *const c_char) {
    if let Ok(k) = CStr::from_ptr(k).to_str() {
        if let Ok(v) = CStr::from_ptr(v).to_str() {
            env::set_var(k, v);
        }
    }
}

/// Gets an environment variable.
/// Parameters:
///     `const char *const k` - The var key.
/// Returns: `char *v` - The value of the variable.
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_get_var(k: *const c_char) -> *mut c_char {
    if let Ok(k) = CStr::from_ptr(k).to_str() {
        if let Ok(v) = env::var(k) {
            return CString::from_vec_unchecked(v.into_bytes()).into_raw();
        }
    }
    ptr::null_mut()
}

/// Removes an environment variable.
/// This will not free memory allocated by `nstd_std_env_get_var`.
/// Parameters:
///     `const char *const k` - The var key.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_remove_var(k: *const c_char) {
    if let Ok(k) = CStr::from_ptr(k).to_str() {
        env::remove_var(k);
    }
}

/// Frees memory allocated by `nstd_std_env_get_var`.
/// Parameters:
///     `char **v` - The value returned from `nstd_std_env_get_var`.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_free_var(k: *mut *mut c_char) {
    static_nstd_free_cstring(k);
}

/// Returns an array of strings that contain the environment variables.
/// Parameters:
///     `NSTDUSize *size` - Number of variables.
/// Returns: `char *vars` - The environment variables keys.
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_vars(size: *mut usize) -> *mut c_char {
    let vars = env::vars().collect::<Vec<(String, String)>>();
    let mut bytes = Vec::<byte>::new();
    *size = vars.len();
    for var in vars {
        bytes.extend(var.0.into_bytes());
        bytes.push(0);
    }
    Box::<[byte]>::into_raw(bytes.into_boxed_slice()) as *mut c_char
}

/// Frees memory allocated by `nstd_std_env_vars`.
/// Parameters:
///     `char **vars` - Returned from `nstd_std_env_vars`.
#[inline]
#[no_mangle]
pub unsafe extern "C" fn nstd_std_env_free_vars(vars: *mut *mut c_char) {
    static_nstd_free_cstring(vars);
}

/// Frees a cstring.
/// Parameters:
///     `cstr: *mut *mut c_char` - The cstring.
#[inline]
unsafe fn static_nstd_free_cstring(cstr: *mut *mut c_char) {
    Box::from_raw(*cstr as *mut byte);
    *cstr = ptr::null_mut();
}