rust/src/libstd/os.rs

1811 lines
57 KiB
Rust
Raw Normal View History

// Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
//! Higher-level interfaces to libc::* functions and operating system services.
//!
2015-01-22 18:31:00 -06:00
//! In general these take and return rust types, use rust idioms (enums,
//! closures, vectors) rather than C idioms, and do more extensive safety
//! checks.
//!
2015-01-22 18:31:00 -06:00
//! This module is not meant to only contain 1:1 mappings to libc entries; any
//! os-interface code that is reasonably useful and broadly applicable can go
//! here. Including utility routines that merely build on other os code.
//!
2015-01-22 18:31:00 -06:00
//! We assume the general case is that users do not care, and do not want to be
//! made to care, which operating system they are on. While they may want to
//! special case various special cases -- and so we will not _hide_ the facts of
//! which OS the user is on -- they should be given the opportunity to write
//! OS-ignorant code by default.
#![unstable(feature = "os")]
2015-03-11 17:24:14 -05:00
#![deprecated(since = "1.0.0", reason = "replaced with std::env APIs")]
2014-10-27 17:37:07 -05:00
#![allow(missing_docs)]
#![allow(non_snake_case)]
#![allow(unused_imports)]
#![allow(deprecated)]
use self::MemoryMapKind::*;
use self::MapOption::*;
use self::MapError::*;
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use boxed::Box;
use clone::Clone;
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use env;
use error::{FromError, Error};
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use ffi::{OsString, OsStr};
use fmt;
2014-11-06 11:32:37 -06:00
use iter::{Iterator, IteratorExt};
use libc::{c_void, c_int, c_char};
use libc;
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use marker::{Copy, Send};
use old_io::{IoResult, IoError};
2014-12-07 13:15:25 -06:00
use ops::{Drop, FnOnce};
use option::Option::{Some, None};
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use option::Option;
use old_path::{Path, GenericPath, BytesContainer};
use path::{self, PathBuf};
use ptr::PtrExt;
use ptr;
use result::Result::{Err, Ok};
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use result::Result;
2014-12-06 20:34:37 -06:00
use slice::{AsSlice, SliceExt};
2014-12-10 21:46:38 -06:00
use str::{Str, StrExt};
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use str;
use string::{String, ToString};
use sync::atomic::{AtomicIsize, ATOMIC_ISIZE_INIT, Ordering};
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use sys::os as os_imp;
use sys;
use vec::Vec;
#[cfg(unix)] use ffi::{self, CString};
#[cfg(unix)] pub use sys::ext as unix;
#[cfg(windows)] pub use sys::ext as windows;
fn err2old(new: ::io::Error) -> IoError {
IoError {
kind: ::old_io::OtherIoError,
desc: "os error",
detail: Some(new.to_string()),
}
}
#[cfg(windows)]
fn path2new(path: &Path) -> PathBuf {
PathBuf::new(path.as_str().unwrap())
}
#[cfg(unix)]
fn path2new(path: &Path) -> PathBuf {
use os::unix::prelude::*;
PathBuf::new(<OsStr as OsStrExt>::from_bytes(path.as_vec()))
}
#[cfg(unix)]
fn path2old(path: &path::Path) -> Path {
use os::unix::prelude::*;
use ffi::AsOsStr;
Path::new(path.as_os_str().as_bytes())
}
#[cfg(windows)]
fn path2old(path: &path::Path) -> Path {
Path::new(path.to_str().unwrap())
}
/// Get the number of cores available
pub fn num_cpus() -> uint {
unsafe {
return rust_get_num_cpus() as uint;
}
extern {
fn rust_get_num_cpus() -> libc::uintptr_t;
}
}
pub const TMPBUF_SZ : uint = 1000;
/// Returns the current working directory as a `Path`.
///
/// # Errors
///
/// Returns an `Err` if the current working directory value is invalid.
/// Possible cases:
///
/// * Current directory does not exist.
/// * There are insufficient permissions to access the current directory.
/// * The internal buffer is not large enough to hold the path.
///
/// # Examples
///
/// ```rust
2014-06-11 10:52:12 -05:00
/// use std::os;
///
2014-11-24 18:21:39 -06:00
/// // We assume that we are in a valid directory.
/// let current_working_directory = os::getcwd().unwrap();
/// println!("The current directory is {:?}", current_working_directory.display());
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn getcwd() -> IoResult<Path> {
env::current_dir().map_err(err2old).map(|s| path2old(&s))
2012-07-25 16:37:40 -05:00
}
2014-06-11 10:52:12 -05:00
/// Returns a vector of (variable, value) pairs, for all the environment
/// variables of the current process.
///
/// Invalid UTF-8 bytes are replaced with \uFFFD. See `String::from_utf8_lossy()`
/// for details.
2014-06-05 10:36:15 -05:00
///
/// # Examples
2014-06-05 10:36:15 -05:00
///
/// ```rust
2014-06-11 10:52:12 -05:00
/// use std::os;
///
/// // We will iterate through the references to the element returned by os::env();
/// for &(ref key, ref value) in os::env().iter() {
2014-06-05 10:36:15 -05:00
/// println!("'{}': '{}'", key, value );
/// }
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "use env::vars instead")]
#[unstable(feature = "os")]
pub fn env() -> Vec<(String,String)> {
env::vars_os().map(|(k, v)| {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
(k.to_string_lossy().into_owned(), v.to_string_lossy().into_owned())
}).collect()
}
/// Returns a vector of (variable, value) byte-vector pairs for all the
/// environment variables of the current process.
#[deprecated(since = "1.0.0", reason = "use env::vars_os instead")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn env_as_bytes() -> Vec<(Vec<u8>, Vec<u8>)> {
env::vars_os().map(|(k, v)| (byteify(k), byteify(v))).collect()
}
2012-04-30 19:42:41 -05:00
/// Fetches the environment variable `n` from the current process, returning
/// None if the variable isn't set.
///
/// Any invalid UTF-8 bytes in the value are replaced by \uFFFD. See
/// `String::from_utf8_lossy()` for details.
///
/// # Panics
///
/// Panics if `n` has any interior NULs.
///
/// # Examples
///
/// ```rust
2014-06-11 10:52:12 -05:00
/// use std::os;
///
/// let key = "HOME";
2014-06-11 10:52:12 -05:00
/// match os::getenv(key) {
/// Some(val) => println!("{}: {}", key, val),
2014-06-08 12:22:49 -05:00
/// None => println!("{} is not defined in the environment.", key)
/// }
/// ```
#[deprecated(since = "1.0.0", reason = "use env::var instead")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn getenv(n: &str) -> Option<String> {
env::var(n).ok()
}
/// Fetches the environment variable `n` byte vector from the current process,
/// returning None if the variable isn't set.
///
/// # Panics
///
/// Panics if `n` has any interior NULs.
#[deprecated(since = "1.0.0", reason = "use env::var_os instead")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
env::var_os(n).map(byteify)
}
2012-04-30 19:42:41 -05:00
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[cfg(unix)]
fn byteify(s: OsString) -> Vec<u8> {
use os::unix::*;
s.into_vec()
}
#[cfg(windows)]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
fn byteify(s: OsString) -> Vec<u8> {
s.to_string_lossy().as_bytes().to_vec()
}
/// Sets the environment variable `n` to the value `v` for the currently running
2014-06-11 10:52:12 -05:00
/// process.
///
/// # Examples
///
2014-06-11 10:52:12 -05:00
/// ```rust
/// use std::os;
///
/// let key = "KEY";
/// os::setenv(key, "VALUE");
/// match os::getenv(key) {
/// Some(ref val) => println!("{}: {}", key, val),
/// None => println!("{} is not defined in the environment.", key)
/// }
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::set_var")]
#[unstable(feature = "os")]
pub fn setenv<T: BytesContainer>(n: &str, v: T) {
2014-06-11 10:52:12 -05:00
#[cfg(unix)]
fn _setenv(n: &str, v: &[u8]) {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
use os::unix::*;
let v: OsString = OsStringExt::from_vec(v.to_vec());
env::set_var(n, &v)
}
2012-04-30 19:42:41 -05:00
2014-06-11 10:52:12 -05:00
#[cfg(windows)]
fn _setenv(n: &str, v: &[u8]) {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
let v = str::from_utf8(v).unwrap();
env::set_var(n, v)
2012-04-30 19:42:41 -05:00
}
_setenv(n, v.container_as_bytes())
2012-04-30 19:42:41 -05:00
}
2014-06-11 10:52:12 -05:00
/// Remove a variable from the environment entirely.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::remove_var")]
#[unstable(feature = "os")]
2013-05-15 12:39:53 -05:00
pub fn unsetenv(n: &str) {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
env::remove_var(n)
2013-05-15 12:39:53 -05:00
}
/// Parses input according to platform conventions for the `PATH`
/// environment variable.
2014-06-11 10:52:12 -05:00
///
/// # Examples
2014-06-11 10:52:12 -05:00
/// ```rust
/// use std::os;
///
/// let key = "PATH";
/// match os::getenv_as_bytes(key) {
2014-06-11 10:52:12 -05:00
/// Some(paths) => {
/// for path in os::split_paths(paths).iter() {
/// println!("'{}'", path.display());
/// }
/// }
2014-07-02 20:27:07 -05:00
/// None => println!("{} is not defined in the environment.", key)
2014-06-11 10:52:12 -05:00
/// }
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
let b = unparsed.container_as_bytes();
let s = str::from_utf8(b).unwrap();
env::split_paths(s).map(|s| path2old(&s)).collect()
}
/// Joins a collection of `Path`s appropriately for the `PATH`
/// environment variable.
///
/// Returns a `Vec<u8>` on success, since `Path`s are not utf-8
/// encoded on all platforms.
///
/// Returns an `Err` (containing an error message) if one of the input
/// `Path`s contains an invalid character for constructing the `PATH`
/// variable (a double quote on Windows or a colon on Unix).
///
/// # Examples
///
/// ```rust
/// use std::os;
/// use std::old_path::Path;
///
/// let key = "PATH";
/// let mut paths = os::getenv_as_bytes(key).map_or(Vec::new(), os::split_paths);
/// paths.push(Path::new("/home/xyz/bin"));
/// os::setenv(key, os::join_paths(paths.as_slice()).unwrap());
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn join_paths<T: BytesContainer>(paths: &[T]) -> Result<Vec<u8>, &'static str> {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
env::join_paths(paths.iter().map(|s| {
str::from_utf8(s.container_as_bytes()).unwrap()
})).map(|s| {
s.to_string_lossy().into_owned().into_bytes()
}).map_err(|_| "failed to join paths")
}
/// A low-level OS in-memory pipe.
#[derive(Copy)]
pub struct Pipe {
/// A file descriptor representing the reading end of the pipe. Data written
/// on the `out` file descriptor can be read from this file descriptor.
pub reader: c_int,
/// A file descriptor representing the write end of the pipe. Data written
/// to this file descriptor can be read from the `input` file descriptor.
pub writer: c_int,
}
/// Creates a new low-level OS in-memory pipe.
///
/// This function can fail to succeed if there are no more resources available
/// to allocate a pipe.
///
/// This function is also unsafe as there is no destructor associated with the
/// `Pipe` structure will return. If it is not arranged for the returned file
/// descriptors to be closed, the file descriptors will leak. For safe handling
2015-01-22 18:31:00 -06:00
/// of this scenario, use `std::old_io::PipeStream` instead.
pub unsafe fn pipe() -> IoResult<Pipe> {
let (reader, writer) = try!(sys::os::pipe());
Ok(Pipe {
reader: reader.unwrap(),
writer: writer.unwrap(),
})
}
2014-06-11 10:52:12 -05:00
/// Returns the proper dll filename for the given basename of a file
/// as a String.
2014-05-05 02:07:49 -05:00
#[cfg(not(target_os="ios"))]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "this function will be removed, use the constants directly")]
#[unstable(feature = "os")]
#[allow(deprecated)]
pub fn dll_filename(base: &str) -> String {
format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
}
2014-06-11 10:52:12 -05:00
/// Optionally returns the filesystem path to the current executable which is
/// running but with the executable name.
///
/// # Examples
///
/// ```rust
/// use std::os;
///
/// match os::self_exe_name() {
/// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
/// None => println!("Unable to get the path of this executable!")
/// };
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
2014-01-22 15:41:53 -06:00
pub fn self_exe_name() -> Option<Path> {
env::current_exe().ok().map(|p| path2old(&p))
2014-01-22 15:41:53 -06:00
}
/// Optionally returns the filesystem path to the current executable which is
2014-06-11 10:52:12 -05:00
/// running.
///
/// Like self_exe_name() but without the binary's name.
///
/// # Examples
2014-06-11 10:52:12 -05:00
///
/// ```rust
/// use std::os;
///
/// match os::self_exe_path() {
/// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
/// None => println!("Impossible to fetch the path of this executable.")
/// };
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
2014-01-22 15:41:53 -06:00
pub fn self_exe_path() -> Option<Path> {
env::current_exe().ok().map(|p| { let mut p = path2old(&p); p.pop(); p })
}
2014-06-11 10:52:12 -05:00
/// Optionally returns the path to the current user's home directory if known.
///
/// # Unix
///
/// Returns the value of the 'HOME' environment variable if it is set
/// and not equal to the empty string.
///
/// # Windows
///
/// Returns the value of the 'HOME' environment variable if it is
/// set and not equal to the empty string. Otherwise, returns the value of the
/// 'USERPROFILE' environment variable if it is set and not equal to the empty
/// string.
///
/// # Examples
2014-06-11 10:52:12 -05:00
///
/// ```rust
/// use std::os;
///
/// match os::homedir() {
/// Some(ref p) => println!("{}", p.display()),
/// None => println!("Impossible to get your home dir!")
/// }
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
#[allow(deprecated)]
2012-09-27 16:08:37 -05:00
pub fn homedir() -> Option<Path> {
2014-06-11 10:52:12 -05:00
#[inline]
#[cfg(unix)]
2014-06-11 10:52:12 -05:00
fn _homedir() -> Option<Path> {
aux_homedir("HOME")
}
2014-06-11 10:52:12 -05:00
#[inline]
#[cfg(windows)]
2014-06-11 10:52:12 -05:00
fn _homedir() -> Option<Path> {
aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
}
#[inline]
fn aux_homedir(home_name: &str) -> Option<Path> {
match getenv_as_bytes(home_name) {
Some(p) => {
if p.is_empty() { None } else { Path::new_opt(p) }
},
_ => None
}
}
2014-06-11 10:52:12 -05:00
_homedir()
}
/// Returns the path to a temporary directory.
///
/// On Unix, returns the value of the 'TMPDIR' environment variable if it is
/// set, otherwise for non-Android it returns '/tmp'. If Android, since there
/// is no global temporary folder (it is usually allocated per-app), we return
/// '/data/local/tmp'.
///
/// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
/// 'USERPROFILE' environment variable if any are set and not the empty
/// string. Otherwise, tmpdir returns the path to the Windows directory.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
#[allow(deprecated)]
2012-09-27 16:08:37 -05:00
pub fn tmpdir() -> Path {
return lookup();
2012-08-20 14:23:37 -05:00
fn getenv_nonempty(v: &str) -> Option<Path> {
match getenv(v) {
2013-02-15 02:51:28 -06:00
Some(x) =>
if x.is_empty() {
2012-08-20 14:23:37 -05:00
None
} else {
Path::new_opt(x)
},
2012-08-20 14:23:37 -05:00
_ => None
}
}
#[cfg(unix)]
fn lookup() -> Path {
let default = if cfg!(target_os = "android") {
Path::new("/data/local/tmp")
} else {
Path::new("/tmp")
};
getenv_nonempty("TMPDIR").unwrap_or(default)
}
#[cfg(windows)]
fn lookup() -> Path {
getenv_nonempty("TMP").or(
getenv_nonempty("TEMP").or(
getenv_nonempty("USERPROFILE").or(
getenv_nonempty("WINDIR")))).unwrap_or(Path::new("C:\\Windows"))
}
}
2013-05-19 21:46:54 -05:00
/// Convert a relative path to an absolute path
///
/// If the given path is relative, return it prepended with the current working
/// directory. If the given path is already an absolute path, return it
/// as is.
///
/// # Examples
/// ```rust
/// use std::os;
/// use std::old_path::Path;
///
/// // Assume we're in a path like /home/someuser
/// let rel_path = Path::new("..");
/// let abs_path = os::make_absolute(&rel_path).unwrap();
/// println!("The absolute path is {}", abs_path.display());
/// // Prints "The absolute path is /home"
/// ```
// NB: this is here rather than in path because it is a form of environment
// querying; what it does depends on the process working directory, not just
// the input paths.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "use env::current_dir + .join directly")]
#[unstable(feature = "os")]
pub fn make_absolute(p: &Path) -> IoResult<Path> {
if p.is_absolute() {
Ok(p.clone())
2013-03-01 21:57:05 -06:00
} else {
env::current_dir().map_err(err2old).map(|cwd| {
let mut cwd = path2old(&cwd);
cwd.push(p);
cwd
})
2013-03-01 21:57:05 -06:00
}
}
/// Changes the current working directory to the specified path, returning
/// whether the change was completed successfully or not.
///
/// # Examples
/// ```rust
/// use std::os;
/// use std::old_path::Path;
///
/// let root = Path::new("/");
/// assert!(os::change_dir(&root).is_ok());
2014-08-01 18:40:21 -05:00
/// println!("Successfully changed working directory to {}!", root.display());
/// ```
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn change_dir(p: &Path) -> IoResult<()> {
sys::os::chdir(&path2new(p)).map_err(err2old)
}
/// Returns the platform-specific value of errno
pub fn errno() -> i32 {
sys::os::errno() as i32
}
/// Return the string corresponding to an `errno()` value of `errnum`.
///
/// # Examples
/// ```rust
/// use std::os;
///
/// // Same as println!("{}", last_os_error());
/// println!("{}", os::error_string(os::errno() as i32));
/// ```
pub fn error_string(errnum: i32) -> String {
2015-02-04 22:16:18 -06:00
return sys::os::error_string(errnum);
}
/// Get a string representing the platform-dependent last error
pub fn last_os_error() -> String {
2015-02-04 22:16:18 -06:00
error_string(errno())
}
/// Sets the process exit code
///
/// Sets the exit code returned by the process if all supervised tasks
/// terminate successfully (without panicking). If the current root task panics
/// and is supervised by the scheduler then any user-specified exit status is
/// ignored and the process exits with the default panic status.
///
/// Note that this is not synchronized against modifications of other threads.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::set_exit_status")]
#[unstable(feature = "os")]
2012-09-27 16:08:37 -05:00
pub fn set_exit_status(code: int) {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
env::set_exit_status(code as i32)
}
/// Fetches the process's current exit code. This defaults to 0 and can change
/// by calling `set_exit_status`.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::get_exit_status")]
#[unstable(feature = "os")]
pub fn get_exit_status() -> int {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
env::get_exit_status() as isize
}
2013-12-08 01:55:28 -06:00
#[cfg(target_os = "macos")]
2014-06-25 14:47:34 -05:00
unsafe fn load_argc_and_argv(argc: int,
argv: *const *const c_char) -> Vec<Vec<u8>> {
use ffi::CStr;
2014-12-30 12:51:18 -06:00
use iter::range;
(0..argc).map(|i| {
CStr::from_ptr(*argv.offset(i)).to_bytes().to_vec()
2014-12-30 12:51:18 -06:00
}).collect()
}
/// Returns the command line arguments
///
/// Returns a list of the command line arguments.
#[cfg(target_os = "macos")]
fn real_args_as_bytes() -> Vec<Vec<u8>> {
unsafe {
let (argc, argv) = (*_NSGetArgc() as int,
2014-06-25 14:47:34 -05:00
*_NSGetArgv() as *const *const c_char);
load_argc_and_argv(argc, argv)
}
}
2014-05-05 02:07:49 -05:00
// As _NSGetArgc and _NSGetArgv aren't mentioned in iOS docs
// and use underscores in their names - they're most probably
// are considered private and therefore should be avoided
// Here is another way to get arguments using Objective C
// runtime
//
// In general it looks like:
// res = Vec::new()
// let args = [[NSProcessInfo processInfo] arguments]
// for i in 0..[args count]
2014-05-05 02:07:49 -05:00
// res.push([args objectAtIndex:i])
// res
#[cfg(target_os = "ios")]
fn real_args_as_bytes() -> Vec<Vec<u8>> {
2015-02-20 10:03:10 -06:00
use ffi::CStr;
2014-05-05 02:07:49 -05:00
use iter::range;
use mem;
#[link(name = "objc")]
extern {
2014-06-25 14:47:34 -05:00
fn sel_registerName(name: *const libc::c_uchar) -> Sel;
2014-05-05 02:07:49 -05:00
fn objc_msgSend(obj: NsId, sel: Sel, ...) -> NsId;
2014-06-25 14:47:34 -05:00
fn objc_getClass(class_name: *const libc::c_uchar) -> NsId;
2014-05-05 02:07:49 -05:00
}
#[link(name = "Foundation", kind = "framework")]
extern {}
2014-06-25 14:47:34 -05:00
type Sel = *const libc::c_void;
type NsId = *const libc::c_void;
2014-05-05 02:07:49 -05:00
let mut res = Vec::new();
unsafe {
let processInfoSel = sel_registerName("processInfo\0".as_ptr());
let argumentsSel = sel_registerName("arguments\0".as_ptr());
let utf8Sel = sel_registerName("UTF8String\0".as_ptr());
let countSel = sel_registerName("count\0".as_ptr());
let objectAtSel = sel_registerName("objectAtIndex:\0".as_ptr());
let klass = objc_getClass("NSProcessInfo\0".as_ptr());
let info = objc_msgSend(klass, processInfoSel);
let args = objc_msgSend(info, argumentsSel);
let cnt: int = mem::transmute(objc_msgSend(args, countSel));
for i in 0..cnt {
2014-05-05 02:07:49 -05:00
let tmp = objc_msgSend(args, objectAtSel, i);
2014-06-25 14:47:34 -05:00
let utf_c_str: *const libc::c_char =
mem::transmute(objc_msgSend(tmp, utf8Sel));
2015-02-20 10:03:10 -06:00
res.push(CStr::from_ptr(utf_c_str).to_bytes().to_vec());
2014-05-05 02:07:49 -05:00
}
}
res
}
2014-09-29 00:31:50 -05:00
#[cfg(any(target_os = "linux",
target_os = "android",
target_os = "freebsd",
2015-01-29 01:19:28 -06:00
target_os = "dragonfly",
2015-01-17 01:51:04 -06:00
target_os = "bitrig",
2015-01-29 01:19:28 -06:00
target_os = "openbsd"))]
fn real_args_as_bytes() -> Vec<Vec<u8>> {
use rt;
rt::args::clone().unwrap_or_else(|| vec![])
}
#[cfg(not(windows))]
fn real_args() -> Vec<String> {
2014-09-14 22:27:36 -05:00
real_args_as_bytes().into_iter()
.map(|v| {
String::from_utf8_lossy(&v).into_owned()
}).collect()
}
#[cfg(windows)]
fn real_args() -> Vec<String> {
use slice;
2014-12-30 18:29:27 -06:00
use iter::range;
let mut nArgs: c_int = 0;
2013-06-08 14:02:32 -05:00
let lpArgCount: *mut c_int = &mut nArgs;
2013-01-24 22:38:43 -06:00
let lpCmdLine = unsafe { GetCommandLineW() };
let szArgList = unsafe { CommandLineToArgvW(lpCmdLine, lpArgCount) };
let args: Vec<_> = (0..nArgs as uint).map(|i| unsafe {
// Determine the length of this argument.
let ptr = *szArgList.offset(i as int);
let mut len = 0;
while *ptr.offset(len as int) != 0 { len += 1; }
// Push it onto the list.
let ptr = ptr as *const u16;
let buf = slice::from_raw_parts(ptr, len);
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
let opt_s = String::from_utf16(sys::truncate_utf16_at_nul(buf));
2014-12-29 18:38:07 -06:00
opt_s.ok().expect("CommandLineToArgvW returned invalid UTF-16")
2014-12-30 12:51:18 -06:00
}).collect();
unsafe {
2014-06-25 14:47:34 -05:00
LocalFree(szArgList as *mut c_void);
}
return args
}
#[cfg(windows)]
fn real_args_as_bytes() -> Vec<Vec<u8>> {
2014-09-14 22:27:36 -05:00
real_args().into_iter().map(|s| s.into_bytes()).collect()
}
2014-06-25 14:47:34 -05:00
type LPCWSTR = *const u16;
2013-11-10 16:57:53 -06:00
#[cfg(windows)]
#[link_name="kernel32"]
2013-11-10 16:57:53 -06:00
extern "system" {
fn GetCommandLineW() -> LPCWSTR;
2014-06-25 14:47:34 -05:00
fn LocalFree(ptr: *mut c_void);
}
2013-11-10 16:57:53 -06:00
#[cfg(windows)]
#[link_name="shell32"]
2013-11-10 16:57:53 -06:00
extern "system" {
2014-06-25 14:47:34 -05:00
fn CommandLineToArgvW(lpCmdLine: LPCWSTR,
pNumArgs: *mut c_int) -> *mut *mut u16;
}
/// Returns the arguments which this program was started with (normally passed
/// via the command line).
///
2014-11-14 00:26:13 -06:00
/// The first element is traditionally the path to the executable, but it can be
/// set to arbitrary text, and it may not even exist, so this property should not
2014-11-21 20:34:38 -06:00
/// be relied upon for security purposes.
2014-11-14 00:26:13 -06:00
///
/// The arguments are interpreted as utf-8, with invalid bytes replaced with \uFFFD.
/// See `String::from_utf8_lossy` for details.
/// # Examples
///
/// ```rust
/// use std::os;
///
/// // Prints each argument on a separate line
/// for argument in os::args().iter() {
/// println!("{}", argument);
/// }
/// ```
#[deprecated(since = "1.0.0", reason = "use std::env::args() instead")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn args() -> Vec<String> {
real_args()
}
/// Returns the arguments which this program was started with (normally passed
/// via the command line) as byte vectors.
#[deprecated(since = "1.0.0", reason = "use env::args_os instead")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[unstable(feature = "os")]
pub fn args_as_bytes() -> Vec<Vec<u8>> {
real_args_as_bytes()
}
#[cfg(target_os = "macos")]
extern {
// These functions are in crt_externs.h.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
fn _NSGetArgc() -> *mut c_int;
fn _NSGetArgv() -> *mut *mut *mut c_char;
}
/// Returns the page size of the current architecture in bytes.
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::page_size")]
#[unstable(feature = "os")]
pub fn page_size() -> uint {
2014-11-24 18:21:39 -06:00
sys::os::page_size()
}
2014-01-23 13:38:22 -06:00
/// A memory mapped file or chunk of memory. This is a very system-specific
/// interface to the OS's memory mapping facilities (`mmap` on POSIX,
2014-08-23 03:12:59 -05:00
/// `VirtualAlloc`/`CreateFileMapping` on Windows). It makes no attempt at
2014-01-23 13:38:22 -06:00
/// abstracting platform differences, besides in error values returned. Consider
2013-11-08 08:18:52 -06:00
/// yourself warned.
///
2014-01-23 13:38:22 -06:00
/// The memory map is released (unmapped) when the destructor is run, so don't
/// let it leave scope by accident if you want it to stick around.
pub struct MemoryMap {
data: *mut u8,
len: uint,
kind: MemoryMapKind,
}
2013-11-08 08:18:52 -06:00
/// Type of memory map
2015-01-24 15:36:30 -06:00
#[allow(raw_pointer_derive)]
#[derive(Copy)]
pub enum MemoryMapKind {
2014-01-23 13:38:22 -06:00
/// Virtual memory map. Usually used to change the permissions of a given
/// chunk of memory. Corresponds to `VirtualAlloc` on Windows.
2014-06-25 14:47:34 -05:00
MapFile(*const u8),
2014-01-23 13:38:22 -06:00
/// Virtual memory map. Usually used to change the permissions of a given
/// chunk of memory, or for allocation. Corresponds to `VirtualAlloc` on
/// Windows.
MapVirtual
}
2013-11-08 08:18:52 -06:00
/// Options the memory map is created with
2015-01-24 15:36:30 -06:00
#[allow(raw_pointer_derive)]
#[derive(Copy)]
pub enum MapOption {
2013-11-08 08:18:52 -06:00
/// The memory should be readable
MapReadable,
2013-11-08 08:18:52 -06:00
/// The memory should be writable
MapWritable,
2013-11-08 08:18:52 -06:00
/// The memory should be executable
MapExecutable,
2014-01-23 13:38:22 -06:00
/// Create a map for a specific address range. Corresponds to `MAP_FIXED` on
/// POSIX.
2014-06-25 14:47:34 -05:00
MapAddr(*const u8),
/// Create a memory mapping for a file with a given HANDLE.
#[cfg(windows)]
MapFd(libc::HANDLE),
2013-11-08 08:18:52 -06:00
/// Create a memory mapping for a file with a given fd.
#[cfg(not(windows))]
MapFd(c_int),
2014-01-23 13:38:22 -06:00
/// When using `MapFd`, the start of the map is `uint` bytes from the start
/// of the file.
MapOffset(uint),
2014-01-23 13:38:22 -06:00
/// On POSIX, this can be used to specify the default flags passed to
/// `mmap`. By default it uses `MAP_PRIVATE` and, if not using `MapFd`,
/// `MAP_ANON`. This will override both of those. This is platform-specific
/// (the exact values used) and ignored on Windows.
MapNonStandardFlags(c_int),
}
2013-11-08 08:18:52 -06:00
/// Possible errors when creating a map.
2015-01-28 07:34:18 -06:00
#[derive(Copy, Debug)]
pub enum MapError {
/// # The following are POSIX-specific
2013-11-08 08:18:52 -06:00
///
2014-01-23 13:38:22 -06:00
/// fd was not open for reading or, if using `MapWritable`, was not open for
/// writing.
ErrFdNotAvail,
2013-11-08 08:18:52 -06:00
/// fd was not valid
ErrInvalidFd,
2014-01-23 13:38:22 -06:00
/// Either the address given by `MapAddr` or offset given by `MapOffset` was
/// not a multiple of `MemoryMap::granularity` (unaligned to page size).
ErrUnaligned,
2013-11-08 08:18:52 -06:00
/// With `MapFd`, the fd does not support mapping.
ErrNoMapSupport,
2014-01-23 13:38:22 -06:00
/// If using `MapAddr`, the address + `min_len` was outside of the process's
/// address space. If using `MapFd`, the target of the fd didn't have enough
/// resources to fulfill the request.
ErrNoMem,
2014-01-18 16:50:49 -06:00
/// A zero-length map was requested. This is invalid according to
2014-01-23 13:38:22 -06:00
/// [POSIX](http://pubs.opengroup.org/onlinepubs/9699919799/functions/mmap.html).
/// Not all platforms obey this, but this wrapper does.
2014-01-18 16:50:49 -06:00
ErrZeroLength,
2013-11-08 08:18:52 -06:00
/// Unrecognized error. The inner value is the unrecognized errno.
ErrUnknown(int),
/// # The following are Windows-specific
2013-11-08 08:18:52 -06:00
///
2014-01-23 13:38:22 -06:00
/// Unsupported combination of protection flags
/// (`MapReadable`/`MapWritable`/`MapExecutable`).
ErrUnsupProt,
2014-01-23 13:38:22 -06:00
/// When using `MapFd`, `MapOffset` was given (Windows does not support this
/// at all)
ErrUnsupOffset,
2013-11-08 08:18:52 -06:00
/// When using `MapFd`, there was already a mapping to the file.
ErrAlreadyExists,
2014-01-23 13:38:22 -06:00
/// Unrecognized error from `VirtualAlloc`. The inner value is the return
/// value of GetLastError.
ErrVirtualAlloc(i32),
2014-01-23 13:38:22 -06:00
/// Unrecognized error from `CreateFileMapping`. The inner value is the
/// return value of `GetLastError`.
ErrCreateFileMappingW(i32),
2014-01-23 13:38:22 -06:00
/// Unrecognized error from `MapViewOfFile`. The inner value is the return
/// value of `GetLastError`.
ErrMapViewOfFile(i32)
}
#[stable(feature = "rust1", since = "1.0.0")]
std: Rename Show/String to Debug/Display This commit is an implementation of [RFC 565][rfc] which is a stabilization of the `std::fmt` module and the implementations of various formatting traits. Specifically, the following changes were performed: [rfc]: https://github.com/rust-lang/rfcs/blob/master/text/0565-show-string-guidelines.md * The `Show` trait is now deprecated, it was renamed to `Debug` * The `String` trait is now deprecated, it was renamed to `Display` * Many `Debug` and `Display` implementations were audited in accordance with the RFC and audited implementations now have the `#[stable]` attribute * Integers and floats no longer print a suffix * Smart pointers no longer print details that they are a smart pointer * Paths with `Debug` are now quoted and escape characters * The `unwrap` methods on `Result` now require `Display` instead of `Debug` * The `Error` trait no longer has a `detail` method and now requires that `Display` must be implemented. With the loss of `String`, this has moved into libcore. * `impl<E: Error> FromError<E> for Box<Error>` now exists * `derive(Show)` has been renamed to `derive(Debug)`. This is not currently warned about due to warnings being emitted on stage1+ While backwards compatibility is attempted to be maintained with a blanket implementation of `Display` for the old `String` trait (and the same for `Show`/`Debug`) this is still a breaking change due to primitives no longer implementing `String` as well as modifications such as `unwrap` and the `Error` trait. Most code is fairly straightforward to update with a rename or tweaks of method calls. [breaking-change] Closes #21436
2015-01-20 17:45:07 -06:00
impl fmt::Display for MapError {
fn fmt(&self, out: &mut fmt::Formatter) -> fmt::Result {
let str = match *self {
ErrFdNotAvail => "fd not available for reading or writing",
ErrInvalidFd => "Invalid fd",
2014-01-23 13:38:22 -06:00
ErrUnaligned => {
"Unaligned address, invalid flags, negative length or \
unaligned offset"
}
ErrNoMapSupport=> "File doesn't support mapping",
ErrNoMem => "Invalid address, or not enough available memory",
ErrUnsupProt => "Protection mode unsupported",
ErrUnsupOffset => "Offset in virtual memory mode is unsupported",
ErrAlreadyExists => "File mapping for specified file already exists",
2014-01-18 16:50:49 -06:00
ErrZeroLength => "Zero-length mapping not allowed",
2014-01-23 13:38:22 -06:00
ErrUnknown(code) => {
return write!(out, "Unknown error = {}", code)
2014-01-23 13:38:22 -06:00
},
ErrVirtualAlloc(code) => {
return write!(out, "VirtualAlloc failure = {}", code)
2014-01-23 13:38:22 -06:00
},
ErrCreateFileMappingW(code) => {
return write!(out, "CreateFileMappingW failure = {}", code)
},
ErrMapViewOfFile(code) => {
return write!(out, "MapViewOfFile failure = {}", code)
}
};
write!(out, "{}", str)
}
}
impl Error for MapError {
fn description(&self) -> &str { "memory map error" }
}
2014-11-24 18:21:39 -06:00
// Round up `from` to be divisible by `to`
fn round_up(from: uint, to: uint) -> uint {
let r = if from % to == 0 {
from
} else {
from + to - (from % to)
};
if r == 0 {
to
} else {
r
}
}
#[cfg(unix)]
impl MemoryMap {
2014-01-23 13:38:22 -06:00
/// Create a new mapping with the given `options`, at least `min_len` bytes
/// long. `min_len` must be greater than zero; see the note on
/// `ErrZeroLength`.
2013-09-30 00:14:09 -05:00
pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
use libc::off_t;
2014-01-18 16:50:49 -06:00
if min_len == 0 {
return Err(ErrZeroLength)
}
2014-06-25 14:47:34 -05:00
let mut addr: *const u8 = ptr::null();
let mut prot = 0;
let mut flags = libc::MAP_PRIVATE;
let mut fd = -1;
let mut offset = 0;
let mut custom_flags = false;
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
let len = round_up(min_len, env::page_size());
2015-01-31 11:20:46 -06:00
for &o in options {
match o {
MapReadable => { prot |= libc::PROT_READ; },
MapWritable => { prot |= libc::PROT_WRITE; },
MapExecutable => { prot |= libc::PROT_EXEC; },
MapAddr(addr_) => {
flags |= libc::MAP_FIXED;
addr = addr_;
},
MapFd(fd_) => {
flags |= libc::MAP_FILE;
fd = fd_;
},
MapOffset(offset_) => { offset = offset_ as off_t; },
MapNonStandardFlags(f) => { custom_flags = true; flags = f },
}
}
if fd == -1 && !custom_flags { flags |= libc::MAP_ANON; }
let r = unsafe {
libc::mmap(addr as *mut c_void, len as libc::size_t, prot, flags,
fd, offset)
};
if r == libc::MAP_FAILED {
Err(match errno() as c_int {
libc::EACCES => ErrFdNotAvail,
libc::EBADF => ErrInvalidFd,
libc::EINVAL => ErrUnaligned,
libc::ENODEV => ErrNoMapSupport,
libc::ENOMEM => ErrNoMem,
code => ErrUnknown(code as int)
})
} else {
2013-09-30 00:14:09 -05:00
Ok(MemoryMap {
data: r as *mut u8,
len: len,
kind: if fd == -1 {
MapVirtual
} else {
MapFile(ptr::null())
}
})
}
}
2013-08-28 03:41:26 -05:00
2014-01-23 13:38:22 -06:00
/// Granularity that the offset or address must be for `MapOffset` and
/// `MapAddr` respectively.
2013-08-28 03:41:26 -05:00
pub fn granularity() -> uint {
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
env::page_size()
2013-08-28 03:41:26 -05:00
}
}
#[cfg(unix)]
impl Drop for MemoryMap {
/// Unmap the mapping. Panics the task if `munmap` panics.
2013-09-16 20:18:07 -05:00
fn drop(&mut self) {
2014-01-18 16:50:49 -06:00
if self.len == 0 { /* workaround for dummy_stack */ return; }
unsafe {
// `munmap` only panics due to logic errors
libc::munmap(self.data as *mut c_void, self.len as libc::size_t);
}
}
}
#[cfg(windows)]
impl MemoryMap {
2013-11-08 08:18:52 -06:00
/// Create a new mapping with the given `options`, at least `min_len` bytes long.
2013-09-30 00:14:09 -05:00
pub fn new(min_len: uint, options: &[MapOption]) -> Result<MemoryMap, MapError> {
use libc::types::os::arch::extra::{LPVOID, DWORD, SIZE_T, HANDLE};
2014-09-14 22:27:36 -05:00
let mut lpAddress: LPVOID = ptr::null_mut();
let mut readable = false;
let mut writable = false;
let mut executable = false;
let mut handle: HANDLE = libc::INVALID_HANDLE_VALUE;
let mut offset: uint = 0;
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
let len = round_up(min_len, env::page_size());
2015-01-31 11:20:46 -06:00
for &o in options {
match o {
MapReadable => { readable = true; },
MapWritable => { writable = true; },
MapExecutable => { executable = true; }
MapAddr(addr_) => { lpAddress = addr_ as LPVOID; },
MapFd(handle_) => { handle = handle_; },
MapOffset(offset_) => { offset = offset_; },
MapNonStandardFlags(..) => {}
}
}
let flProtect = match (executable, readable, writable) {
(false, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_NOACCESS,
(false, true, false) => libc::PAGE_READONLY,
(false, true, true) => libc::PAGE_READWRITE,
(true, false, false) if handle == libc::INVALID_HANDLE_VALUE => libc::PAGE_EXECUTE,
(true, true, false) => libc::PAGE_EXECUTE_READ,
(true, true, true) => libc::PAGE_EXECUTE_READWRITE,
_ => return Err(ErrUnsupProt)
};
if handle == libc::INVALID_HANDLE_VALUE {
if offset != 0 {
return Err(ErrUnsupOffset);
}
let r = unsafe {
libc::VirtualAlloc(lpAddress,
len as SIZE_T,
libc::MEM_COMMIT | libc::MEM_RESERVE,
flProtect)
};
match r as uint {
0 => Err(ErrVirtualAlloc(errno())),
2013-09-30 00:14:09 -05:00
_ => Ok(MemoryMap {
data: r as *mut u8,
len: len,
kind: MapVirtual
})
}
} else {
2013-08-28 03:41:26 -05:00
let dwDesiredAccess = match (executable, readable, writable) {
(false, true, false) => libc::FILE_MAP_READ,
(false, true, true) => libc::FILE_MAP_WRITE,
(true, true, false) => libc::FILE_MAP_READ | libc::FILE_MAP_EXECUTE,
(true, true, true) => libc::FILE_MAP_WRITE | libc::FILE_MAP_EXECUTE,
_ => return Err(ErrUnsupProt) // Actually, because of the check above,
// we should never get here.
};
unsafe {
let hFile = handle;
let mapping = libc::CreateFileMappingW(hFile,
2014-09-14 22:27:36 -05:00
ptr::null_mut(),
flProtect,
2013-08-28 03:41:26 -05:00
0,
0,
ptr::null());
2014-09-14 22:27:36 -05:00
if mapping == ptr::null_mut() {
return Err(ErrCreateFileMappingW(errno()));
}
if errno() as c_int == libc::ERROR_ALREADY_EXISTS {
return Err(ErrAlreadyExists);
}
let r = libc::MapViewOfFile(mapping,
dwDesiredAccess,
2013-08-28 03:41:26 -05:00
((len as u64) >> 32) as DWORD,
(offset & 0xffff_ffff) as DWORD,
0);
match r as uint {
0 => Err(ErrMapViewOfFile(errno())),
2013-09-30 00:14:09 -05:00
_ => Ok(MemoryMap {
data: r as *mut u8,
len: len,
2014-06-25 14:47:34 -05:00
kind: MapFile(mapping as *const u8)
})
}
}
}
}
2013-08-28 03:41:26 -05:00
/// Granularity of MapAddr() and MapOffset() parameter values.
/// This may be greater than the value returned by page_size().
pub fn granularity() -> uint {
2014-02-26 11:58:41 -06:00
use mem;
2013-08-28 03:41:26 -05:00
unsafe {
let mut info = mem::zeroed();
2013-08-28 03:41:26 -05:00
libc::GetSystemInfo(&mut info);
return info.dwAllocationGranularity as uint;
}
}
}
#[cfg(windows)]
impl Drop for MemoryMap {
/// Unmap the mapping. Panics the task if any of `VirtualFree`,
2014-01-23 13:38:22 -06:00
/// `UnmapViewOfFile`, or `CloseHandle` fail.
2013-09-16 20:18:07 -05:00
fn drop(&mut self) {
use libc::types::os::arch::extra::{LPCVOID, HANDLE};
2013-08-28 03:41:26 -05:00
use libc::consts::os::extra::FALSE;
2014-01-23 13:38:22 -06:00
if self.len == 0 { return }
unsafe {
match self.kind {
2013-08-28 03:41:26 -05:00
MapVirtual => {
if libc::VirtualFree(self.data as *mut c_void, 0,
2014-01-23 13:38:22 -06:00
libc::MEM_RELEASE) == 0 {
println!("VirtualFree failed: {}", errno());
2013-08-28 03:41:26 -05:00
}
},
MapFile(mapping) => {
2013-08-28 03:41:26 -05:00
if libc::UnmapViewOfFile(self.data as LPCVOID) == FALSE {
println!("UnmapViewOfFile failed: {}", errno());
}
2013-08-28 03:41:26 -05:00
if libc::CloseHandle(mapping as HANDLE) == FALSE {
println!("CloseHandle failed: {}", errno());
}
}
}
}
}
}
impl MemoryMap {
/// Returns the pointer to the memory created or modified by this map.
pub fn data(&self) -> *mut u8 { self.data }
/// Returns the number of bytes this map applies to.
pub fn len(&self) -> uint { self.len }
/// Returns the type of mapping this represents.
pub fn kind(&self) -> MemoryMapKind { self.kind }
}
#[cfg(target_os = "linux")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `linux`.
pub const SYSNAME: &'static str = "linux";
2012-12-20 03:26:27 -06:00
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
2012-12-20 03:26:27 -06:00
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
2012-12-20 03:26:27 -06:00
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "macos")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `macos`.
pub const SYSNAME: &'static str = "macos";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.dylib`.
pub const DLL_SUFFIX: &'static str = ".dylib";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `dylib`.
pub const DLL_EXTENSION: &'static str = "dylib";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
2014-05-05 02:07:49 -05:00
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
2014-05-05 02:07:49 -05:00
}
#[cfg(target_os = "ios")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
2014-05-05 02:07:49 -05:00
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
2014-05-05 02:07:49 -05:00
/// A string describing the specific operating system in use: in this
/// case, `ios`.
pub const SYSNAME: &'static str = "ios";
2014-05-05 02:07:49 -05:00
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "freebsd")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `freebsd`.
pub const SYSNAME: &'static str = "freebsd";
2012-12-20 03:26:27 -06:00
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "dragonfly")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `dragonfly`.
pub const SYSNAME: &'static str = "dragonfly";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
2015-01-17 01:51:04 -06:00
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "bitrig")]
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `bitrig`.
pub const SYSNAME: &'static str = "bitrig";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
2015-01-29 01:19:28 -06:00
#[cfg(target_os = "openbsd")]
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
2015-01-29 01:19:28 -06:00
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `openbsd`.
pub const SYSNAME: &'static str = "openbsd";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "android")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
2012-12-20 03:26:27 -06:00
pub const FAMILY: &'static str = "unix";
/// A string describing the specific operating system in use: in this
/// case, `android`.
pub const SYSNAME: &'static str = "android";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, `lib`.
pub const DLL_PREFIX: &'static str = "lib";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.so`.
pub const DLL_SUFFIX: &'static str = ".so";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `so`.
pub const DLL_EXTENSION: &'static str = "so";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, the empty string.
pub const EXE_SUFFIX: &'static str = "";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, the empty string.
pub const EXE_EXTENSION: &'static str = "";
}
#[cfg(target_os = "windows")]
std: Add a new `env` module This is an implementation of [RFC 578][rfc] which adds a new `std::env` module to replace most of the functionality in the current `std::os` module. More details can be found in the RFC itself, but as a summary the following methods have all been deprecated: [rfc]: https://github.com/rust-lang/rfcs/pull/578 * `os::args_as_bytes` => `env::args` * `os::args` => `env::args` * `os::consts` => `env::consts` * `os::dll_filename` => no replacement, use `env::consts` directly * `os::page_size` => `env::page_size` * `os::make_absolute` => use `env::current_dir` + `join` instead * `os::getcwd` => `env::current_dir` * `os::change_dir` => `env::set_current_dir` * `os::homedir` => `env::home_dir` * `os::tmpdir` => `env::temp_dir` * `os::join_paths` => `env::join_paths` * `os::split_paths` => `env::split_paths` * `os::self_exe_name` => `env::current_exe` * `os::self_exe_path` => use `env::current_exe` + `pop` * `os::set_exit_status` => `env::set_exit_status` * `os::get_exit_status` => `env::get_exit_status` * `os::env` => `env::vars` * `os::env_as_bytes` => `env::vars` * `os::getenv` => `env::var` or `env::var_string` * `os::getenv_as_bytes` => `env::var` * `os::setenv` => `env::set_var` * `os::unsetenv` => `env::remove_var` Many function signatures have also been tweaked for various purposes, but the main changes were: * `Vec`-returning APIs now all return iterators instead * All APIs are now centered around `OsString` instead of `Vec<u8>` or `String`. There is currently on convenience API, `env::var_string`, which can be used to get the value of an environment variable as a unicode `String`. All old APIs are `#[deprecated]` in-place and will remain for some time to allow for migrations. The semantics of the APIs have been tweaked slightly with regard to dealing with invalid unicode (panic instead of replacement). The new `std::env` module is all contained within the `env` feature, so crates must add the following to access the new APIs: #![feature(env)] [breaking-change]
2015-01-27 14:20:58 -06:00
#[deprecated(since = "1.0.0", reason = "renamed to env::consts")]
#[unstable(feature = "os")]
pub mod consts {
pub use os::arch_consts::ARCH;
pub const FAMILY: &'static str = "windows";
/// A string describing the specific operating system in use: in this
2014-08-23 03:12:59 -05:00
/// case, `windows`.
pub const SYSNAME: &'static str = "windows";
/// Specifies the filename prefix used for shared libraries on this
/// platform: in this case, the empty string.
pub const DLL_PREFIX: &'static str = "";
/// Specifies the filename suffix used for shared libraries on this
/// platform: in this case, `.dll`.
pub const DLL_SUFFIX: &'static str = ".dll";
/// Specifies the file extension used for shared libraries on this
/// platform that goes after the dot: in this case, `dll`.
pub const DLL_EXTENSION: &'static str = "dll";
/// Specifies the filename suffix used for executable binaries on this
/// platform: in this case, `.exe`.
pub const EXE_SUFFIX: &'static str = ".exe";
/// Specifies the file extension, if any, used for executable binaries
/// on this platform: in this case, `exe`.
pub const EXE_EXTENSION: &'static str = "exe";
}
#[cfg(target_arch = "x86")]
mod arch_consts {
pub const ARCH: &'static str = "x86";
}
#[cfg(target_arch = "x86_64")]
mod arch_consts {
pub const ARCH: &'static str = "x86_64";
}
#[cfg(target_arch = "arm")]
mod arch_consts {
pub const ARCH: &'static str = "arm";
}
2012-12-20 03:26:27 -06:00
#[cfg(target_arch = "aarch64")]
mod arch_consts {
pub const ARCH: &'static str = "aarch64";
}
#[cfg(target_arch = "mips")]
mod arch_consts {
pub const ARCH: &'static str = "mips";
2012-12-20 03:26:27 -06:00
}
2014-06-17 02:16:03 -05:00
#[cfg(target_arch = "mipsel")]
mod arch_consts {
pub const ARCH: &'static str = "mipsel";
2014-06-17 02:16:03 -05:00
}
2015-01-09 22:20:15 -06:00
#[cfg(target_arch = "powerpc")]
mod arch_consts {
pub const ARCH: &'static str = "powerpc";
}
#[cfg(test)]
mod tests {
#![allow(deprecated)] // rand
use prelude::v1::*;
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
use iter::repeat;
use os::{env, getcwd, getenv, make_absolute};
use os::{split_paths, join_paths, setenv, unsetenv};
use os;
use rand::Rng;
use rand;
#[test]
2012-09-27 16:08:37 -05:00
pub fn last_os_error() {
debug!("{}", os::last_os_error());
}
fn make_rand_name() -> String {
let mut rng = rand::thread_rng();
let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
std: Recreate a `rand` module This commit shuffles around some of the `rand` code, along with some reorganization. The new state of the world is as follows: * The librand crate now only depends on libcore. This interface is experimental. * The standard library has a new module, `std::rand`. This interface will eventually become stable. Unfortunately, this entailed more of a breaking change than just shuffling some names around. The following breaking changes were made to the rand library: * Rng::gen_vec() was removed. This has been replaced with Rng::gen_iter() which will return an infinite stream of random values. Previous behavior can be regained with `rng.gen_iter().take(n).collect()` * Rng::gen_ascii_str() was removed. This has been replaced with Rng::gen_ascii_chars() which will return an infinite stream of random ascii characters. Similarly to gen_iter(), previous behavior can be emulated with `rng.gen_ascii_chars().take(n).collect()` * {IsaacRng, Isaac64Rng, XorShiftRng}::new() have all been removed. These all relied on being able to use an OSRng for seeding, but this is no longer available in librand (where these types are defined). To retain the same functionality, these types now implement the `Rand` trait so they can be generated with a random seed from another random number generator. This allows the stdlib to use an OSRng to create seeded instances of these RNGs. * Rand implementations for `Box<T>` and `@T` were removed. These seemed to be pretty rare in the codebase, and it allows for librand to not depend on liballoc. Additionally, other pointer types like Rc<T> and Arc<T> were not supported. If this is undesirable, librand can depend on liballoc and regain these implementations. * The WeightedChoice structure is no longer built with a `Vec<Weighted<T>>`, but rather a `&mut [Weighted<T>]`. This means that the WeightedChoice structure now has a lifetime associated with it. * The `sample` method on `Rng` has been moved to a top-level function in the `rand` module due to its dependence on `Vec`. cc #13851 [breaking-change]
2014-05-25 03:39:37 -05:00
.collect::<String>());
assert!(getenv(&n).is_none());
n
}
#[test]
fn test_num_cpus() {
assert!(os::num_cpus() > 0);
}
#[test]
fn test_setenv() {
let n = make_rand_name();
setenv(&n, "VALUE");
assert_eq!(getenv(&n), Some("VALUE".to_string()));
}
2013-05-15 12:39:53 -05:00
#[test]
fn test_unsetenv() {
let n = make_rand_name();
setenv(&n, "VALUE");
unsetenv(&n);
assert_eq!(getenv(&n), None);
2013-05-15 12:39:53 -05:00
}
#[test]
#[ignore]
fn test_setenv_overwrite() {
let n = make_rand_name();
setenv(&n, "1");
setenv(&n, "2");
assert_eq!(getenv(&n), Some("2".to_string()));
setenv(&n, "");
assert_eq!(getenv(&n), Some("".to_string()));
}
// Windows GetEnvironmentVariable requires some extra work to make sure
// the buffer the variable is copied into is the right size
#[test]
#[ignore]
fn test_getenv_big() {
let mut s = "".to_string();
2015-01-25 15:05:03 -06:00
let mut i = 0;
while i < 100 {
s.push_str("aaaaaaaaaa");
i += 1;
}
let n = make_rand_name();
setenv(&n, &s);
debug!("{}", s.clone());
assert_eq!(getenv(&n), Some(s));
}
2014-01-22 15:41:53 -06:00
#[test]
fn test_self_exe_name() {
let path = os::self_exe_name();
assert!(path.is_some());
let path = path.unwrap();
2014-10-15 02:07:48 -05:00
debug!("{}", path.display());
2014-01-22 15:41:53 -06:00
// Hard to test this function
assert!(path.is_absolute());
}
#[test]
fn test_self_exe_path() {
let path = os::self_exe_path();
2013-03-28 20:39:09 -05:00
assert!(path.is_some());
let path = path.unwrap();
2014-10-15 02:07:48 -05:00
debug!("{}", path.display());
// Hard to test this function
assert!(path.is_absolute());
}
#[test]
#[ignore]
fn test_env_getenv() {
let e = env();
assert!(e.len() > 0);
2015-01-31 11:20:46 -06:00
for p in &e {
2013-07-02 14:47:32 -05:00
let (n, v) = (*p).clone();
2014-10-15 02:07:48 -05:00
debug!("{}", n);
let v2 = getenv(&n);
// MingW seems to set some funky environment variables like
// "=C:=C:\MinGW\msys\1.0\bin" and "!::=::\" that are returned
// from env() but not visible from getenv().
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
assert!(v2.is_none() || v2 == Some(v));
}
}
#[test]
fn test_env_set_get_huge() {
let n = make_rand_name();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
let s = repeat("x").take(10000).collect::<String>();
setenv(&n, &s);
assert_eq!(getenv(&n), Some(s));
unsetenv(&n);
assert_eq!(getenv(&n), None);
}
#[test]
fn test_env_setenv() {
let n = make_rand_name();
let mut e = env();
setenv(&n, "VALUE");
assert!(!e.contains(&(n.clone(), "VALUE".to_string())));
e = env();
assert!(e.contains(&(n, "VALUE".to_string())));
}
#[test]
fn test() {
assert!((!Path::new("test-path").is_absolute()));
let cwd = getcwd().unwrap();
debug!("Current working directory: {}", cwd.display());
debug!("{}", make_absolute(&Path::new("test-path")).unwrap().display());
debug!("{}", make_absolute(&Path::new("/usr/bin")).unwrap().display());
}
#[test]
#[cfg(unix)]
fn homedir() {
2013-05-23 11:39:17 -05:00
let oldhome = getenv("HOME");
2013-05-23 11:39:17 -05:00
setenv("HOME", "/home/MountainView");
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2013-05-23 11:39:17 -05:00
setenv("HOME", "");
2013-03-28 20:39:09 -05:00
assert!(os::homedir().is_none());
2015-01-31 11:20:46 -06:00
if let Some(s) = oldhome {
setenv("HOME", s);
}
}
#[test]
#[cfg(windows)]
fn homedir() {
2013-05-23 11:39:17 -05:00
let oldhome = getenv("HOME");
let olduserprofile = getenv("USERPROFILE");
2013-05-23 11:39:17 -05:00
setenv("HOME", "");
setenv("USERPROFILE", "");
2013-03-28 20:39:09 -05:00
assert!(os::homedir().is_none());
2013-05-23 11:39:17 -05:00
setenv("HOME", "/home/MountainView");
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2013-05-23 11:39:17 -05:00
setenv("HOME", "");
2013-05-23 11:39:17 -05:00
setenv("USERPROFILE", "/home/MountainView");
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2013-05-23 11:39:17 -05:00
setenv("HOME", "/home/MountainView");
setenv("USERPROFILE", "/home/PaloAlto");
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
2015-01-31 11:20:46 -06:00
if let Some(s) = oldhome {
setenv("HOME", &s);
}
2015-01-31 11:20:46 -06:00
if let Some(s) = olduserprofile {
setenv("USERPROFILE", &s);
}
}
#[test]
fn memory_map_rw() {
use result::Result::{Ok, Err};
2014-11-17 02:39:01 -06:00
let chunk = match os::MemoryMap::new(16, &[
os::MapOption::MapReadable,
os::MapOption::MapWritable
]) {
Ok(chunk) => chunk,
2015-01-06 18:16:35 -06:00
Err(msg) => panic!("{:?}", msg)
};
assert!(chunk.len >= 16);
unsafe {
*chunk.data = 0xBE;
assert!(*chunk.data == 0xBE);
}
}
#[test]
fn memory_map_file() {
use libc;
use os::*;
2015-01-22 18:31:00 -06:00
use old_io::fs::{File, unlink};
use old_io::SeekStyle::SeekSet;
use old_io::FileMode::Open;
use old_io::FileAccess::ReadWrite;
#[cfg(not(windows))]
fn get_fd(file: &File) -> libc::c_int {
use os::unix::AsRawFd;
file.as_raw_fd()
}
#[cfg(windows)]
fn get_fd(file: &File) -> libc::HANDLE {
use os::windows::AsRawHandle;
file.as_raw_handle()
}
let mut path = tmpdir();
path.push("mmap_file.tmp");
2013-08-28 03:41:26 -05:00
let size = MemoryMap::granularity() * 2;
let mut file = File::open_mode(&path, Open, ReadWrite).unwrap();
std: Second pass stabilization for `comm` This commit is a second pass stabilization for the `std::comm` module, performing the following actions: * The entire `std::comm` module was moved under `std::sync::mpsc`. This movement reflects that channels are just yet another synchronization primitive, and they don't necessarily deserve a special place outside of the other concurrency primitives that the standard library offers. * The `send` and `recv` methods have all been removed. * The `send_opt` and `recv_opt` methods have been renamed to `send` and `recv`. This means that all send/receive operations return a `Result` now indicating whether the operation was successful or not. * The error type of `send` is now a `SendError` to implement a custom error message and allow for `unwrap()`. The error type contains an `into_inner` method to extract the value. * The error type of `recv` is now `RecvError` for the same reasons as `send`. * The `TryRecvError` and `TrySendError` types have had public reexports removed of their variants and the variant names have been tweaked with enum namespacing rules. * The `Messages` iterator is renamed to `Iter` This functionality is now all `#[stable]`: * `Sender` * `SyncSender` * `Receiver` * `std::sync::mpsc` * `channel` * `sync_channel` * `Iter` * `Sender::send` * `Sender::clone` * `SyncSender::send` * `SyncSender::try_send` * `SyncSender::clone` * `Receiver::recv` * `Receiver::try_recv` * `Receiver::iter` * `SendError` * `RecvError` * `TrySendError::{mod, Full, Disconnected}` * `TryRecvError::{mod, Empty, Disconnected}` * `SendError::into_inner` * `TrySendError::into_inner` This is a breaking change due to the modification of where this module is located, as well as the changing of the semantics of `send` and `recv`. Most programs just need to rename imports of `std::comm` to `std::sync::mpsc` and add calls to `unwrap` after a send or a receive operation. [breaking-change]
2014-12-23 13:53:35 -06:00
file.seek(size as i64, SeekSet).unwrap();
file.write_u8(0).unwrap();
let chunk = MemoryMap::new(size / 2, &[
MapOption::MapReadable,
MapOption::MapWritable,
MapOption::MapFd(get_fd(&file)),
MapOption::MapOffset(size / 2)
]).unwrap();
assert!(chunk.len > 0);
unsafe {
*chunk.data = 0xbe;
assert!(*chunk.data == 0xbe);
}
drop(chunk);
unlink(&path).unwrap();
}
#[test]
#[cfg(windows)]
fn split_paths_windows() {
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed) ==
2014-11-21 00:20:04 -06:00
parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
}
2014-11-17 02:39:01 -06:00
assert!(check_parse("", &mut [""]));
assert!(check_parse(r#""""#, &mut [""]));
assert!(check_parse(";;", &mut ["", "", ""]));
assert!(check_parse(r"c:\", &mut [r"c:\"]));
assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
assert!(check_parse(r"c:\;c:\Program Files\",
2014-11-17 02:39:01 -06:00
&mut [r"c:\", r"c:\Program Files\"]));
assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
2014-11-17 02:39:01 -06:00
&mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
}
#[test]
#[cfg(unix)]
fn split_paths_unix() {
fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
split_paths(unparsed) ==
2014-11-21 00:20:04 -06:00
parsed.iter().map(|s| Path::new(*s)).collect::<Vec<_>>()
}
2014-11-17 02:39:01 -06:00
assert!(check_parse("", &mut [""]));
assert!(check_parse("::", &mut ["", "", ""]));
assert!(check_parse("/", &mut ["/"]));
assert!(check_parse("/:", &mut ["/", ""]));
assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
}
#[test]
#[cfg(unix)]
fn join_paths_unix() {
fn test_eq(input: &[&str], output: &str) -> bool {
join_paths(input).unwrap() == output.as_bytes()
}
2014-11-17 02:39:01 -06:00
assert!(test_eq(&[], ""));
assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
"/bin:/usr/bin:/usr/local/bin"));
assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
":/bin:::/usr/bin:"));
assert!(join_paths(&["/te:st"]).is_err());
}
#[test]
#[cfg(windows)]
fn join_paths_windows() {
fn test_eq(input: &[&str], output: &str) -> bool {
join_paths(input).unwrap() == output.as_bytes()
}
2014-11-17 18:49:09 -06:00
assert!(test_eq(&[], ""));
assert!(test_eq(&[r"c:\windows", r"c:\"],
r"c:\windows;c:\"));
2014-11-17 18:49:09 -06:00
assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
r";c:\windows;;;c:\;"));
2014-11-17 18:49:09 -06:00
assert!(test_eq(&[r"c:\te;st", r"c:\"],
r#""c:\te;st";c:\"#));
2014-11-17 02:39:01 -06:00
assert!(join_paths(&[r#"c:\te"st"#]).is_err());
}
// More recursive_mkdir tests are in extra::tempfile
}