1 // Copyright 2012-2015 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! Inspection and manipulation of the process's environment.
13 //! This module contains methods to inspect various aspects such as
14 //! environment varibles, process arguments, the current directory, and various
15 //! other important directories.
17 #![stable(feature = "env", since = "1.0.0")]
22 use ffi
::{OsStr, OsString}
;
25 use path
::{Path, PathBuf}
;
26 use sync
::atomic
::{AtomicIsize, Ordering}
;
27 use sync
::StaticMutex
;
28 use sys
::os
as os_imp
;
30 /// Returns the current working directory as a `PathBuf`.
34 /// Returns an `Err` if the current working directory value is invalid.
37 /// * Current directory does not exist.
38 /// * There are insufficient permissions to access the current directory.
39 /// * The internal buffer is not large enough to hold the path.
46 /// // We assume that we are in a valid directory.
47 /// let p = env::current_dir().unwrap();
48 /// println!("The current directory is {}", p.display());
50 #[stable(feature = "env", since = "1.0.0")]
51 pub fn current_dir() -> io
::Result
<PathBuf
> {
55 /// Changes the current working directory to the specified path, returning
56 /// whether the change was completed successfully or not.
62 /// use std::path::Path;
64 /// let root = Path::new("/");
65 /// assert!(env::set_current_dir(&root).is_ok());
66 /// println!("Successfully changed working directory to {}!", root.display());
68 #[stable(feature = "env", since = "1.0.0")]
69 pub fn set_current_dir
<P
: AsRef
<Path
>>(p
: P
) -> io
::Result
<()> {
70 os_imp
::chdir(p
.as_ref())
73 static ENV_LOCK
: StaticMutex
= StaticMutex
::new();
75 /// An iterator over a snapshot of the environment variables of this process.
77 /// This iterator is created through `std::env::vars()` and yields `(String,
79 #[stable(feature = "env", since = "1.0.0")]
80 pub struct Vars { inner: VarsOs }
82 /// An iterator over a snapshot of the environment variables of this process.
84 /// This iterator is created through `std::env::vars_os()` and yields
85 /// `(OsString, OsString)` pairs.
86 #[stable(feature = "env", since = "1.0.0")]
87 pub struct VarsOs { inner: os_imp::Env }
89 /// Returns an iterator of (variable, value) pairs of strings, for all the
90 /// environment variables of the current process.
92 /// The returned iterator contains a snapshot of the process's environment
93 /// variables at the time of this invocation, modifications to environment
94 /// variables afterwards will not be reflected in the returned iterator.
98 /// While iterating, the returned iterator will panic if any key or value in the
99 /// environment is not valid unicode. If this is not desired, consider using the
100 /// `env::vars_os` function.
107 /// // We will iterate through the references to the element returned by
109 /// for (key, value) in env::vars() {
110 /// println!("{}: {}", key, value);
113 #[stable(feature = "env", since = "1.0.0")]
114 pub fn vars() -> Vars
{
115 Vars { inner: vars_os() }
118 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
119 /// environment variables of the current process.
121 /// The returned iterator contains a snapshot of the process's environment
122 /// variables at the time of this invocation, modifications to environment
123 /// variables afterwards will not be reflected in the returned iterator.
130 /// // We will iterate through the references to the element returned by
131 /// // env::vars_os();
132 /// for (key, value) in env::vars_os() {
133 /// println!("{:?}: {:?}", key, value);
136 #[stable(feature = "env", since = "1.0.0")]
137 pub fn vars_os() -> VarsOs
{
138 let _g
= ENV_LOCK
.lock();
139 VarsOs { inner: os_imp::env() }
142 #[stable(feature = "env", since = "1.0.0")]
143 impl Iterator
for Vars
{
144 type Item
= (String
, String
);
145 fn next(&mut self) -> Option
<(String
, String
)> {
146 self.inner
.next().map(|(a
, b
)| {
147 (a
.into_string().unwrap(), b
.into_string().unwrap())
150 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
153 #[stable(feature = "env", since = "1.0.0")]
154 impl Iterator
for VarsOs
{
155 type Item
= (OsString
, OsString
);
156 fn next(&mut self) -> Option
<(OsString
, OsString
)> { self.inner.next() }
157 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
160 /// Fetches the environment variable `key` from the current process.
162 /// The returned result is `Ok(s)` if the environment variable is present and is
163 /// valid unicode. If the environment variable is not present, or it is not
164 /// valid unicode, then `Err` will be returned.
171 /// let key = "HOME";
172 /// match env::var(key) {
173 /// Ok(val) => println!("{}: {:?}", key, val),
174 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
177 #[stable(feature = "env", since = "1.0.0")]
178 pub fn var
<K
: AsRef
<OsStr
>>(key
: K
) -> Result
<String
, VarError
> {
180 Some(s
) => s
.into_string().map_err(VarError
::NotUnicode
),
181 None
=> Err(VarError
::NotPresent
)
185 /// Fetches the environment variable `key` from the current process, returning
186 /// None if the variable isn't set.
193 /// let key = "HOME";
194 /// match env::var_os(key) {
195 /// Some(val) => println!("{}: {:?}", key, val),
196 /// None => println!("{} is not defined in the environment.", key)
199 #[stable(feature = "env", since = "1.0.0")]
200 pub fn var_os
<K
: AsRef
<OsStr
>>(key
: K
) -> Option
<OsString
> {
201 let _g
= ENV_LOCK
.lock();
202 os_imp
::getenv(key
.as_ref())
205 /// Possible errors from the `env::var` method.
206 #[derive(Debug, PartialEq, Eq, Clone)]
207 #[stable(feature = "env", since = "1.0.0")]
209 /// The specified environment variable was not present in the current
210 /// process's environment.
211 #[stable(feature = "env", since = "1.0.0")]
214 /// The specified environment variable was found, but it did not contain
215 /// valid unicode data. The found data is returned as a payload of this
217 #[stable(feature = "env", since = "1.0.0")]
218 NotUnicode(OsString
),
221 #[stable(feature = "env", since = "1.0.0")]
222 impl fmt
::Display
for VarError
{
223 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
225 VarError
::NotPresent
=> write
!(f
, "environment variable not found"),
226 VarError
::NotUnicode(ref s
) => {
227 write
!(f
, "environment variable was not valid unicode: {:?}", s
)
233 #[stable(feature = "env", since = "1.0.0")]
234 impl Error
for VarError
{
235 fn description(&self) -> &str {
237 VarError
::NotPresent
=> "environment variable not found",
238 VarError
::NotUnicode(..) => "environment variable was not valid unicode",
243 /// Sets the environment variable `k` to the value `v` for the currently running
246 /// Note that while concurrent access to environment variables is safe in Rust,
247 /// some platforms only expose inherently unsafe non-threadsafe APIs for
248 /// inspecting the environment. As a result extra care needs to be taken when
249 /// auditing calls to unsafe external FFI functions to ensure that any external
250 /// environment accesses are properly synchronized with accesses in Rust.
252 /// Discussion of this unsafety on Unix may be found in:
254 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
255 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
263 /// env::set_var(key, "VALUE");
264 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
266 #[stable(feature = "env", since = "1.0.0")]
267 pub fn set_var
<K
: AsRef
<OsStr
>, V
: AsRef
<OsStr
>>(k
: K
, v
: V
) {
268 let _g
= ENV_LOCK
.lock();
269 os_imp
::setenv(k
.as_ref(), v
.as_ref())
272 /// Removes an environment variable from the environment of the currently running process.
274 /// Note that while concurrent access to environment variables is safe in Rust,
275 /// some platforms only expose inherently unsafe non-threadsafe APIs for
276 /// inspecting the environment. As a result extra care needs to be taken when
277 /// auditing calls to unsafe external FFI functions to ensure that any external
278 /// environment accesses are properly synchronized with accesses in Rust.
280 /// Discussion of this unsafety on Unix may be found in:
282 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
283 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
291 /// env::set_var(key, "VALUE");
292 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
294 /// env::remove_var(key);
295 /// assert!(env::var(key).is_err());
297 #[stable(feature = "env", since = "1.0.0")]
298 pub fn remove_var
<K
: AsRef
<OsStr
>>(k
: K
) {
299 let _g
= ENV_LOCK
.lock();
300 os_imp
::unsetenv(k
.as_ref())
303 /// An iterator over `Path` instances for parsing an environment variable
304 /// according to platform-specific conventions.
306 /// This structure is returned from `std::env::split_paths`.
307 #[stable(feature = "env", since = "1.0.0")]
308 pub struct SplitPaths
<'a
> { inner: os_imp::SplitPaths<'a> }
310 /// Parses input according to platform conventions for the `PATH`
311 /// environment variable.
313 /// Returns an iterator over the paths contained in `unparsed`.
320 /// let key = "PATH";
321 /// match env::var_os(key) {
323 /// for path in env::split_paths(&paths) {
324 /// println!("'{}'", path.display());
327 /// None => println!("{} is not defined in the environment.", key)
330 #[stable(feature = "env", since = "1.0.0")]
331 pub fn split_paths
<T
: AsRef
<OsStr
> + ?Sized
>(unparsed
: &T
) -> SplitPaths
{
332 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
335 #[stable(feature = "env", since = "1.0.0")]
336 impl<'a
> Iterator
for SplitPaths
<'a
> {
338 fn next(&mut self) -> Option
<PathBuf
> { self.inner.next() }
339 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
342 /// Error type returned from `std::env::join_paths` when paths fail to be
345 #[stable(feature = "env", since = "1.0.0")]
346 pub struct JoinPathsError
{
347 inner
: os_imp
::JoinPathsError
350 /// Joins a collection of `Path`s appropriately for the `PATH`
351 /// environment variable.
353 /// Returns an `OsString` on success.
355 /// Returns an `Err` (containing an error message) if one of the input
356 /// `Path`s contains an invalid character for constructing the `PATH`
357 /// variable (a double quote on Windows or a colon on Unix).
363 /// use std::path::PathBuf;
365 /// if let Some(path) = env::var_os("PATH") {
366 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
367 /// paths.push(PathBuf::from("/home/xyz/bin"));
368 /// let new_path = env::join_paths(paths).unwrap();
369 /// env::set_var("PATH", &new_path);
372 #[stable(feature = "env", since = "1.0.0")]
373 pub fn join_paths
<I
, T
>(paths
: I
) -> Result
<OsString
, JoinPathsError
>
374 where I
: IntoIterator
<Item
=T
>, T
: AsRef
<OsStr
>
376 os_imp
::join_paths(paths
.into_iter()).map_err(|e
| {
377 JoinPathsError { inner: e }
381 #[stable(feature = "env", since = "1.0.0")]
382 impl fmt
::Display
for JoinPathsError
{
383 fn fmt(&self, f
: &mut fmt
::Formatter
) -> fmt
::Result
{
388 #[stable(feature = "env", since = "1.0.0")]
389 impl Error
for JoinPathsError
{
390 fn description(&self) -> &str { self.inner.description() }
393 /// Optionally returns the path to the current user's home directory if known.
397 /// Returns the value of the 'HOME' environment variable if it is set
398 /// and not equal to the empty string.
402 /// Returns the value of the 'HOME' environment variable if it is
403 /// set and not equal to the empty string. Otherwise, returns the value of the
404 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
412 /// match env::home_dir() {
413 /// Some(ref p) => println!("{}", p.display()),
414 /// None => println!("Impossible to get your home dir!")
417 #[stable(feature = "env", since = "1.0.0")]
418 pub fn home_dir() -> Option
<PathBuf
> {
422 /// Returns the path to a temporary directory.
424 /// On Unix, returns the value of the 'TMPDIR' environment variable if it is
425 /// set, otherwise for non-Android it returns '/tmp'. If Android, since there
426 /// is no global temporary folder (it is usually allocated per-app), we return
427 /// '/data/local/tmp'.
429 /// On Windows, returns the value of, in order, the 'TMP', 'TEMP',
430 /// 'USERPROFILE' environment variable if any are set and not the empty
431 /// string. Otherwise, tmpdir returns the path to the Windows directory.
435 /// use std::fs::File;
437 /// # fn foo() -> std::io::Result<()> {
438 /// let mut dir = env::temp_dir();
439 /// dir.push("foo.txt");
441 /// let f = try!(File::create(dir));
445 #[stable(feature = "env", since = "1.0.0")]
446 pub fn temp_dir() -> PathBuf
{
450 /// Optionally returns the filesystem path to the current executable which is
451 /// running but with the executable name.
453 /// The path returned is not necessarily a "real path" to the executable as
454 /// there may be intermediate symlinks.
458 /// Acquiring the path to the current executable is a platform-specific operation
459 /// that can fail for a good number of reasons. Some errors can include, but not
460 /// be limited to filesystem operations failing or general syscall failures.
467 /// match env::current_exe() {
468 /// Ok(exe_path) => println!("Path of this executable is: {}",
469 /// exe_path.display()),
470 /// Err(e) => println!("failed to get current exe path: {}", e),
473 #[stable(feature = "env", since = "1.0.0")]
474 pub fn current_exe() -> io
::Result
<PathBuf
> {
475 os_imp
::current_exe()
478 static EXIT_STATUS
: AtomicIsize
= AtomicIsize
::new(0);
480 /// Sets the process exit code
482 /// Sets the exit code returned by the process if all supervised threads
483 /// terminate successfully (without panicking). If the current root thread panics
484 /// and is supervised by the scheduler then any user-specified exit status is
485 /// ignored and the process exits with the default panic status.
487 /// Note that this is not synchronized against modifications of other threads.
488 #[unstable(feature = "exit_status", reason = "managing the exit status may change")]
489 #[deprecated(since = "1.2.0", reason = "use process::exit instead")]
490 pub fn set_exit_status(code
: i32) {
491 EXIT_STATUS
.store(code
as isize, Ordering
::SeqCst
)
494 /// Fetches the process's current exit code. This defaults to 0 and can change
495 /// by calling `set_exit_status`.
496 #[unstable(feature = "exit_status", reason = "managing the exit status may change")]
497 #[deprecated(since = "1.2.0", reason = "use process::exit instead")]
498 pub fn get_exit_status() -> i32 {
499 EXIT_STATUS
.load(Ordering
::SeqCst
) as i32
502 /// An iterator over the arguments of a process, yielding a `String` value
503 /// for each argument.
505 /// This structure is created through the `std::env::args` method.
506 #[stable(feature = "env", since = "1.0.0")]
507 pub struct Args { inner: ArgsOs }
509 /// An iterator over the arguments of a process, yielding an `OsString` value
510 /// for each argument.
512 /// This structure is created through the `std::env::args_os` method.
513 #[stable(feature = "env", since = "1.0.0")]
514 pub struct ArgsOs { inner: os_imp::Args }
516 /// Returns the arguments which this program was started with (normally passed
517 /// via the command line).
519 /// The first element is traditionally the path to the executable, but it can be
520 /// set to arbitrary text, and it may not even exist, so this property should
521 /// not be relied upon for security purposes.
525 /// The returned iterator will panic during iteration if any argument to the
526 /// process is not valid unicode. If this is not desired it is recommended to
527 /// use the `args_os` function instead.
534 /// // Prints each argument on a separate line
535 /// for argument in env::args() {
536 /// println!("{}", argument);
539 #[stable(feature = "env", since = "1.0.0")]
540 pub fn args() -> Args
{
541 Args { inner: args_os() }
544 /// Returns the arguments which this program was started with (normally passed
545 /// via the command line).
547 /// The first element is traditionally the path to the executable, but it can be
548 /// set to arbitrary text, and it may not even exist, so this property should
549 /// not be relied upon for security purposes.
556 /// // Prints each argument on a separate line
557 /// for argument in env::args_os() {
558 /// println!("{:?}", argument);
561 #[stable(feature = "env", since = "1.0.0")]
562 pub fn args_os() -> ArgsOs
{
563 ArgsOs { inner: os_imp::args() }
566 #[stable(feature = "env", since = "1.0.0")]
567 impl Iterator
for Args
{
569 fn next(&mut self) -> Option
<String
> {
570 self.inner
.next().map(|s
| s
.into_string().unwrap())
572 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
575 #[stable(feature = "env", since = "1.0.0")]
576 impl ExactSizeIterator
for Args
{
577 fn len(&self) -> usize { self.inner.len() }
580 #[stable(feature = "env", since = "1.0.0")]
581 impl Iterator
for ArgsOs
{
582 type Item
= OsString
;
583 fn next(&mut self) -> Option
<OsString
> { self.inner.next() }
584 fn size_hint(&self) -> (usize, Option
<usize>) { self.inner.size_hint() }
587 #[stable(feature = "env", since = "1.0.0")]
588 impl ExactSizeIterator
for ArgsOs
{
589 fn len(&self) -> usize { self.inner.len() }
592 /// Returns the page size of the current architecture in bytes.
593 #[unstable(feature = "page_size", reason = "naming and/or location may change")]
594 pub fn page_size() -> usize {
598 /// Constants associated with the current target
599 #[stable(feature = "env", since = "1.0.0")]
601 /// A string describing the architecture of the CPU that this is currently
604 /// Some possible values:
613 #[stable(feature = "env", since = "1.0.0")]
614 pub const ARCH
: &'
static str = super::arch
::ARCH
;
616 /// The family of the operating system. In this case, `unix`.
618 /// Some possible values:
622 #[stable(feature = "env", since = "1.0.0")]
623 pub const FAMILY
: &'
static str = super::os
::FAMILY
;
625 /// A string describing the specific operating system in use: in this
628 /// Some possible values:
639 #[stable(feature = "env", since = "1.0.0")]
640 pub const OS
: &'
static str = super::os
::OS
;
642 /// Specifies the filename prefix used for shared libraries on this
643 /// platform: in this case, `lib`.
645 /// Some possible values:
648 /// - `""` (an empty string)
649 #[stable(feature = "env", since = "1.0.0")]
650 pub const DLL_PREFIX
: &'
static str = super::os
::DLL_PREFIX
;
652 /// Specifies the filename suffix used for shared libraries on this
653 /// platform: in this case, `.so`.
655 /// Some possible values:
660 #[stable(feature = "env", since = "1.0.0")]
661 pub const DLL_SUFFIX
: &'
static str = super::os
::DLL_SUFFIX
;
663 /// Specifies the file extension used for shared libraries on this
664 /// platform that goes after the dot: in this case, `so`.
666 /// Some possible values:
671 #[stable(feature = "env", since = "1.0.0")]
672 pub const DLL_EXTENSION
: &'
static str = super::os
::DLL_EXTENSION
;
674 /// Specifies the filename suffix used for executable binaries on this
675 /// platform: in this case, the empty string.
677 /// Some possible values:
680 /// - `""` (an empty string)
681 #[stable(feature = "env", since = "1.0.0")]
682 pub const EXE_SUFFIX
: &'
static str = super::os
::EXE_SUFFIX
;
684 /// Specifies the file extension, if any, used for executable binaries
685 /// on this platform: in this case, the empty string.
687 /// Some possible values:
690 /// - `""` (an empty string)
691 #[stable(feature = "env", since = "1.0.0")]
692 pub const EXE_EXTENSION
: &'
static str = super::os
::EXE_EXTENSION
;
696 #[cfg(target_os = "linux")]
698 pub const FAMILY
: &'
static str = "unix";
699 pub const OS
: &'
static str = "linux";
700 pub const DLL_PREFIX
: &'
static str = "lib";
701 pub const DLL_SUFFIX
: &'
static str = ".so";
702 pub const DLL_EXTENSION
: &'
static str = "so";
703 pub const EXE_SUFFIX
: &'
static str = "";
704 pub const EXE_EXTENSION
: &'
static str = "";
707 #[cfg(target_os = "macos")]
709 pub const FAMILY
: &'
static str = "unix";
710 pub const OS
: &'
static str = "macos";
711 pub const DLL_PREFIX
: &'
static str = "lib";
712 pub const DLL_SUFFIX
: &'
static str = ".dylib";
713 pub const DLL_EXTENSION
: &'
static str = "dylib";
714 pub const EXE_SUFFIX
: &'
static str = "";
715 pub const EXE_EXTENSION
: &'
static str = "";
718 #[cfg(target_os = "ios")]
720 pub const FAMILY
: &'
static str = "unix";
721 pub const OS
: &'
static str = "ios";
722 pub const DLL_PREFIX
: &'
static str = "lib";
723 pub const DLL_SUFFIX
: &'
static str = ".dylib";
724 pub const DLL_EXTENSION
: &'
static str = "dylib";
725 pub const EXE_SUFFIX
: &'
static str = "";
726 pub const EXE_EXTENSION
: &'
static str = "";
729 #[cfg(target_os = "freebsd")]
731 pub const FAMILY
: &'
static str = "unix";
732 pub const OS
: &'
static str = "freebsd";
733 pub const DLL_PREFIX
: &'
static str = "lib";
734 pub const DLL_SUFFIX
: &'
static str = ".so";
735 pub const DLL_EXTENSION
: &'
static str = "so";
736 pub const EXE_SUFFIX
: &'
static str = "";
737 pub const EXE_EXTENSION
: &'
static str = "";
740 #[cfg(target_os = "dragonfly")]
742 pub const FAMILY
: &'
static str = "unix";
743 pub const OS
: &'
static str = "dragonfly";
744 pub const DLL_PREFIX
: &'
static str = "lib";
745 pub const DLL_SUFFIX
: &'
static str = ".so";
746 pub const DLL_EXTENSION
: &'
static str = "so";
747 pub const EXE_SUFFIX
: &'
static str = "";
748 pub const EXE_EXTENSION
: &'
static str = "";
751 #[cfg(target_os = "bitrig")]
753 pub const FAMILY
: &'
static str = "unix";
754 pub const OS
: &'
static str = "bitrig";
755 pub const DLL_PREFIX
: &'
static str = "lib";
756 pub const DLL_SUFFIX
: &'
static str = ".so";
757 pub const DLL_EXTENSION
: &'
static str = "so";
758 pub const EXE_SUFFIX
: &'
static str = "";
759 pub const EXE_EXTENSION
: &'
static str = "";
762 #[cfg(target_os = "openbsd")]
764 pub const FAMILY
: &'
static str = "unix";
765 pub const OS
: &'
static str = "openbsd";
766 pub const DLL_PREFIX
: &'
static str = "lib";
767 pub const DLL_SUFFIX
: &'
static str = ".so";
768 pub const DLL_EXTENSION
: &'
static str = "so";
769 pub const EXE_SUFFIX
: &'
static str = "";
770 pub const EXE_EXTENSION
: &'
static str = "";
773 #[cfg(target_os = "android")]
775 pub const FAMILY
: &'
static str = "unix";
776 pub const OS
: &'
static str = "android";
777 pub const DLL_PREFIX
: &'
static str = "lib";
778 pub const DLL_SUFFIX
: &'
static str = ".so";
779 pub const DLL_EXTENSION
: &'
static str = "so";
780 pub const EXE_SUFFIX
: &'
static str = "";
781 pub const EXE_EXTENSION
: &'
static str = "";
784 #[cfg(target_os = "windows")]
786 pub const FAMILY
: &'
static str = "windows";
787 pub const OS
: &'
static str = "windows";
788 pub const DLL_PREFIX
: &'
static str = "";
789 pub const DLL_SUFFIX
: &'
static str = ".dll";
790 pub const DLL_EXTENSION
: &'
static str = "dll";
791 pub const EXE_SUFFIX
: &'
static str = ".exe";
792 pub const EXE_EXTENSION
: &'
static str = "exe";
795 #[cfg(target_arch = "x86")]
797 pub const ARCH
: &'
static str = "x86";
800 #[cfg(target_arch = "x86_64")]
802 pub const ARCH
: &'
static str = "x86_64";
805 #[cfg(target_arch = "arm")]
807 pub const ARCH
: &'
static str = "arm";
810 #[cfg(target_arch = "aarch64")]
812 pub const ARCH
: &'
static str = "aarch64";
815 #[cfg(target_arch = "mips")]
817 pub const ARCH
: &'
static str = "mips";
820 #[cfg(target_arch = "mipsel")]
822 pub const ARCH
: &'
static str = "mipsel";
825 #[cfg(target_arch = "powerpc")]
827 pub const ARCH
: &'
static str = "powerpc";
836 use rand
::{self, Rng}
;
837 use ffi
::{OsString, OsStr}
;
838 use path
::{Path, PathBuf}
;
840 fn make_rand_name() -> OsString
{
841 let mut rng
= rand
::thread_rng();
842 let n
= format
!("TEST{}", rng
.gen_ascii_chars().take(10)
843 .collect
::<String
>());
844 let n
= OsString
::from(n
);
845 assert
!(var_os(&n
).is_none());
849 fn eq(a
: Option
<OsString
>, b
: Option
<&str>) {
850 assert_eq
!(a
.as_ref().map(|s
| &**s
), b
.map(OsStr
::new
).map(|s
| &*s
));
855 let n
= make_rand_name();
856 set_var(&n
, "VALUE");
857 eq(var_os(&n
), Some("VALUE"));
861 fn test_remove_var() {
862 let n
= make_rand_name();
863 set_var(&n
, "VALUE");
865 eq(var_os(&n
), None
);
869 fn test_set_var_overwrite() {
870 let n
= make_rand_name();
873 eq(var_os(&n
), Some("2"));
875 eq(var_os(&n
), Some(""));
880 let mut s
= "".to_string();
883 s
.push_str("aaaaaaaaaa");
886 let n
= make_rand_name();
888 eq(var_os(&n
), Some(&s
));
892 fn test_self_exe_path() {
893 let path
= current_exe();
894 assert
!(path
.is_ok());
895 let path
= path
.unwrap();
897 // Hard to test this function
898 assert
!(path
.is_absolute());
902 fn test_env_set_get_huge() {
903 let n
= make_rand_name();
904 let s
= repeat("x").take(10000).collect
::<String
>();
906 eq(var_os(&n
), Some(&s
));
908 eq(var_os(&n
), None
);
912 fn test_env_set_var() {
913 let n
= make_rand_name();
915 let mut e
= vars_os();
916 set_var(&n
, "VALUE");
917 assert
!(!e
.any(|(k
, v
)| {
918 &*k
== &*n
&& &*v
== "VALUE"
921 assert
!(vars_os().any(|(k
, v
)| {
922 &*k
== &*n
&& &*v
== "VALUE"
928 assert
!((!Path
::new("test-path").is_absolute()));
930 current_dir().unwrap();
935 fn split_paths_windows() {
936 fn check_parse(unparsed
: &str, parsed
: &[&str]) -> bool
{
937 split_paths(unparsed
).collect
::<Vec
<_
>>() ==
938 parsed
.iter().map(|s
| PathBuf
::from(*s
)).collect
::<Vec
<_
>>()
941 assert
!(check_parse("", &mut [""]));
942 assert
!(check_parse(r
#""""#, &mut [""]));
943 assert
!(check_parse(";;", &mut ["", "", ""]));
944 assert
!(check_parse(r
"c:\", &mut [r
"c:\"]));
945 assert
!(check_parse(r
"c:\;", &mut [r
"c:\", ""]));
946 assert
!(check_parse(r
"c:\;c:\Program Files\",
947 &mut [r
"c:\", r
"c:\Program Files\"]));
948 assert
!(check_parse(r
#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
949 assert
!(check_parse(r
#"c:\;c:\"foo;bar"\;c:\baz"#,
950 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
955 fn split_paths_unix() {
956 fn check_parse(unparsed
: &str, parsed
: &[&str]) -> bool
{
957 split_paths(unparsed
).collect
::<Vec
<_
>>() ==
958 parsed
.iter().map(|s
| PathBuf
::from(*s
)).collect
::<Vec
<_
>>()
961 assert
!(check_parse("", &mut [""]));
962 assert
!(check_parse("::", &mut ["", "", ""]));
963 assert
!(check_parse("/", &mut ["/"]));
964 assert
!(check_parse("/:", &mut ["/", ""]));
965 assert
!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
970 fn join_paths_unix() {
971 fn test_eq(input
: &[&str], output
: &str) -> bool
{
972 &*join_paths(input
.iter().cloned()).unwrap() ==
976 assert
!(test_eq(&[], ""));
977 assert
!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
978 "/bin:/usr/bin:/usr/local/bin"));
979 assert
!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
980 ":/bin:::/usr/bin:"));
981 assert
!(join_paths(["/te:st"].iter().cloned()).is_err());
986 fn join_paths_windows() {
987 fn test_eq(input
: &[&str], output
: &str) -> bool
{
988 &*join_paths(input
.iter().cloned()).unwrap() ==
992 assert
!(test_eq(&[], ""));
993 assert
!(test_eq(&[r
"c:\windows", r
"c:\"],
995 assert
!(test_eq(&["", r
"c:\windows", "", "", r
"c:\", ""],
996 r
";c:\windows;;;c:\;"));
997 assert
!(test_eq(&[r
"c:\te;st", r
"c:\"],
998 r
#""c:\te;st";c:\"#));
999 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());