1 //! Inspection and manipulation of the process's environment.
3 //! This module contains functions to inspect various aspects such as
4 //! environment variables, process arguments, the current directory, and various
5 //! other important directories.
7 //! There are several functions and structs in this module that have a
8 //! counterpart ending in `os`. Those ending in `os` will return an [`OsString`]
9 //! and those without will be returning a [`String`].
11 //! [`OsString`]: ../../std/ffi/struct.OsString.html
12 //! [`String`]: ../string/struct.String.html
14 #![stable(feature = "env", since = "1.0.0")]
16 use crate::error::Error;
17 use crate::ffi::{OsStr, OsString};
20 use crate::path::{Path, PathBuf};
22 use crate::sys::os as os_imp;
24 /// Returns the current working directory as a [`PathBuf`].
28 /// Returns an [`Err`] if the current working directory value is invalid.
31 /// * Current directory does not exist.
32 /// * There are insufficient permissions to access the current directory.
34 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
35 /// [`Err`]: ../../std/result/enum.Result.html#method.err
42 /// fn main() -> std::io::Result<()> {
43 /// let path = env::current_dir()?;
44 /// println!("The current directory is {}", path.display());
48 #[stable(feature = "env", since = "1.0.0")]
49 pub fn current_dir() -> io::Result<PathBuf> {
53 /// Changes the current working directory to the specified path.
55 /// Returns an [`Err`] if the operation fails.
57 /// [`Err`]: ../../std/result/enum.Result.html#method.err
63 /// use std::path::Path;
65 /// let root = Path::new("/");
66 /// assert!(env::set_current_dir(&root).is_ok());
67 /// println!("Successfully changed working directory to {}!", root.display());
69 #[stable(feature = "env", since = "1.0.0")]
70 pub fn set_current_dir<P: AsRef<Path>>(path: P) -> io::Result<()> {
71 os_imp::chdir(path.as_ref())
74 /// An iterator over a snapshot of the environment variables of this process.
76 /// This structure is created by the [`std::env::vars`] function. See its
77 /// documentation for more.
79 /// [`std::env::vars`]: fn.vars.html
80 #[stable(feature = "env", since = "1.0.0")]
81 pub struct Vars { inner: VarsOs }
83 /// An iterator over a snapshot of the environment variables of this process.
85 /// This structure is created by the [`std::env::vars_os`] function. See
86 /// its documentation for more.
88 /// [`std::env::vars_os`]: fn.vars_os.html
89 #[stable(feature = "env", since = "1.0.0")]
90 pub struct VarsOs { inner: os_imp::Env }
92 /// Returns an iterator of (variable, value) pairs of strings, for all the
93 /// environment variables of the current process.
95 /// The returned iterator contains a snapshot of the process's environment
96 /// variables at the time of this invocation. Modifications to environment
97 /// variables afterwards will not be reflected in the returned iterator.
101 /// While iterating, the returned iterator will panic if any key or value in the
102 /// environment is not valid unicode. If this is not desired, consider using the
103 /// [`env::vars_os`] function.
105 /// [`env::vars_os`]: fn.vars_os.html
112 /// // We will iterate through the references to the element returned by
114 /// for (key, value) in env::vars() {
115 /// println!("{}: {}", key, value);
118 #[stable(feature = "env", since = "1.0.0")]
119 pub fn vars() -> Vars {
120 Vars { inner: vars_os() }
123 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
124 /// environment variables of the current process.
126 /// The returned iterator contains a snapshot of the process's environment
127 /// variables at the time of this invocation. Modifications to environment
128 /// variables afterwards will not be reflected in the returned iterator.
135 /// // We will iterate through the references to the element returned by
136 /// // env::vars_os();
137 /// for (key, value) in env::vars_os() {
138 /// println!("{:?}: {:?}", key, value);
141 #[stable(feature = "env", since = "1.0.0")]
142 pub fn vars_os() -> VarsOs {
143 VarsOs { inner: os_imp::env() }
146 #[stable(feature = "env", since = "1.0.0")]
147 impl Iterator for Vars {
148 type Item = (String, String);
149 fn next(&mut self) -> Option<(String, String)> {
150 self.inner.next().map(|(a, b)| {
151 (a.into_string().unwrap(), b.into_string().unwrap())
154 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
157 #[stable(feature = "std_debug", since = "1.16.0")]
158 impl fmt::Debug for Vars {
159 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
164 #[stable(feature = "env", since = "1.0.0")]
165 impl Iterator for VarsOs {
166 type Item = (OsString, OsString);
167 fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
168 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
171 #[stable(feature = "std_debug", since = "1.16.0")]
172 impl fmt::Debug for VarsOs {
173 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
174 f.pad("VarsOs { .. }")
178 /// Fetches the environment variable `key` from the current process.
182 /// * Environment variable is not present
183 /// * Environment variable is not valid unicode
190 /// let key = "HOME";
191 /// match env::var(key) {
192 /// Ok(val) => println!("{}: {:?}", key, val),
193 /// Err(e) => println!("couldn't interpret {}: {}", key, e),
196 #[stable(feature = "env", since = "1.0.0")]
197 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
201 fn _var(key: &OsStr) -> Result<String, VarError> {
203 Some(s) => s.into_string().map_err(VarError::NotUnicode),
204 None => Err(VarError::NotPresent),
208 /// Fetches the environment variable `key` from the current process, returning
209 /// [`None`] if the variable isn't set.
211 /// [`None`]: ../option/enum.Option.html#variant.None
218 /// let key = "HOME";
219 /// match env::var_os(key) {
220 /// Some(val) => println!("{}: {:?}", key, val),
221 /// None => println!("{} is not defined in the environment.", key)
224 #[stable(feature = "env", since = "1.0.0")]
225 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
226 _var_os(key.as_ref())
229 fn _var_os(key: &OsStr) -> Option<OsString> {
230 os_imp::getenv(key).unwrap_or_else(|e| {
231 panic!("failed to get environment variable `{:?}`: {}", key, e)
235 /// The error type for operations interacting with environment variables.
236 /// Possibly returned from the [`env::var`] function.
238 /// [`env::var`]: fn.var.html
239 #[derive(Debug, PartialEq, Eq, Clone)]
240 #[stable(feature = "env", since = "1.0.0")]
242 /// The specified environment variable was not present in the current
243 /// process's environment.
244 #[stable(feature = "env", since = "1.0.0")]
247 /// The specified environment variable was found, but it did not contain
248 /// valid unicode data. The found data is returned as a payload of this
250 #[stable(feature = "env", since = "1.0.0")]
251 NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
254 #[stable(feature = "env", since = "1.0.0")]
255 impl fmt::Display for VarError {
256 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258 VarError::NotPresent => write!(f, "environment variable not found"),
259 VarError::NotUnicode(ref s) => {
260 write!(f, "environment variable was not valid unicode: {:?}", s)
266 #[stable(feature = "env", since = "1.0.0")]
267 impl Error for VarError {
268 fn description(&self) -> &str {
270 VarError::NotPresent => "environment variable not found",
271 VarError::NotUnicode(..) => "environment variable was not valid unicode",
276 /// Sets the environment variable `k` to the value `v` for the currently running
279 /// Note that while concurrent access to environment variables is safe in Rust,
280 /// some platforms only expose inherently unsafe non-threadsafe APIs for
281 /// inspecting the environment. As a result extra care needs to be taken when
282 /// auditing calls to unsafe external FFI functions to ensure that any external
283 /// environment accesses are properly synchronized with accesses in Rust.
285 /// Discussion of this unsafety on Unix may be found in:
287 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
288 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
292 /// This function may panic if `key` is empty, contains an ASCII equals sign
293 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
302 /// env::set_var(key, "VALUE");
303 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
305 #[stable(feature = "env", since = "1.0.0")]
306 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
307 _set_var(k.as_ref(), v.as_ref())
310 fn _set_var(k: &OsStr, v: &OsStr) {
311 os_imp::setenv(k, v).unwrap_or_else(|e| {
312 panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
317 /// Removes an environment variable from the environment of the currently running process.
319 /// Note that while concurrent access to environment variables is safe in Rust,
320 /// some platforms only expose inherently unsafe non-threadsafe APIs for
321 /// inspecting the environment. As a result extra care needs to be taken when
322 /// auditing calls to unsafe external FFI functions to ensure that any external
323 /// environment accesses are properly synchronized with accesses in Rust.
325 /// Discussion of this unsafety on Unix may be found in:
327 /// - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
328 /// - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
332 /// This function may panic if `key` is empty, contains an ASCII equals sign
333 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
342 /// env::set_var(key, "VALUE");
343 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
345 /// env::remove_var(key);
346 /// assert!(env::var(key).is_err());
348 #[stable(feature = "env", since = "1.0.0")]
349 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
350 _remove_var(k.as_ref())
353 fn _remove_var(k: &OsStr) {
354 os_imp::unsetenv(k).unwrap_or_else(|e| {
355 panic!("failed to remove environment variable `{:?}`: {}", k, e)
359 /// An iterator that splits an environment variable into paths according to
360 /// platform-specific conventions.
362 /// The iterator element type is [`PathBuf`].
364 /// This structure is created by the [`std::env::split_paths`] function. See its
365 /// documentation for more.
367 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
368 /// [`std::env::split_paths`]: fn.split_paths.html
369 #[stable(feature = "env", since = "1.0.0")]
370 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
372 /// Parses input according to platform conventions for the `PATH`
373 /// environment variable.
375 /// Returns an iterator over the paths contained in `unparsed`. The iterator
376 /// element type is [`PathBuf`].
383 /// let key = "PATH";
384 /// match env::var_os(key) {
386 /// for path in env::split_paths(&paths) {
387 /// println!("'{}'", path.display());
390 /// None => println!("{} is not defined in the environment.", key)
394 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
395 #[stable(feature = "env", since = "1.0.0")]
396 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths<'_> {
397 SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
400 #[stable(feature = "env", since = "1.0.0")]
401 impl<'a> Iterator for SplitPaths<'a> {
403 fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
404 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
407 #[stable(feature = "std_debug", since = "1.16.0")]
408 impl fmt::Debug for SplitPaths<'_> {
409 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
410 f.pad("SplitPaths { .. }")
414 /// The error type for operations on the `PATH` variable. Possibly returned from
415 /// the [`env::join_paths`] function.
417 /// [`env::join_paths`]: fn.join_paths.html
419 #[stable(feature = "env", since = "1.0.0")]
420 pub struct JoinPathsError {
421 inner: os_imp::JoinPathsError
424 /// Joins a collection of [`Path`]s appropriately for the `PATH`
425 /// environment variable.
429 /// Returns an [`Err`][err] (containing an error message) if one of the input
430 /// [`Path`]s contains an invalid character for constructing the `PATH`
431 /// variable (a double quote on Windows or a colon on Unix).
433 /// [`Path`]: ../../std/path/struct.Path.html
434 /// [`OsString`]: ../../std/ffi/struct.OsString.html
435 /// [err]: ../../std/result/enum.Result.html#variant.Err
439 /// Joining paths on a Unix-like platform:
443 /// use std::ffi::OsString;
444 /// use std::path::Path;
446 /// fn main() -> Result<(), env::JoinPathsError> {
447 /// # if cfg!(unix) {
448 /// let paths = [Path::new("/bin"), Path::new("/usr/bin")];
449 /// let path_os_string = env::join_paths(paths.iter())?;
450 /// assert_eq!(path_os_string, OsString::from("/bin:/usr/bin"));
456 /// Joining a path containing a colon on a Unix-like platform results in an error:
459 /// # if cfg!(unix) {
461 /// use std::path::Path;
463 /// let paths = [Path::new("/bin"), Path::new("/usr/bi:n")];
464 /// assert!(env::join_paths(paths.iter()).is_err());
468 /// Using `env::join_paths` with `env::spit_paths` to append an item to the `PATH` environment
473 /// use std::path::PathBuf;
475 /// fn main() -> Result<(), env::JoinPathsError> {
476 /// if let Some(path) = env::var_os("PATH") {
477 /// let mut paths = env::split_paths(&path).collect::<Vec<_>>();
478 /// paths.push(PathBuf::from("/home/xyz/bin"));
479 /// let new_path = env::join_paths(paths)?;
480 /// env::set_var("PATH", &new_path);
486 #[stable(feature = "env", since = "1.0.0")]
487 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
488 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
490 os_imp::join_paths(paths.into_iter()).map_err(|e| {
491 JoinPathsError { inner: e }
495 #[stable(feature = "env", since = "1.0.0")]
496 impl fmt::Display for JoinPathsError {
497 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
502 #[stable(feature = "env", since = "1.0.0")]
503 impl Error for JoinPathsError {
504 fn description(&self) -> &str { self.inner.description() }
507 /// Returns the path of the current user's home directory if known.
511 /// - Returns the value of the 'HOME' environment variable if it is set
512 /// (including to an empty string).
513 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
514 /// using the UID of the current user. An empty home directory field returned from the
515 /// `getpwuid_r` function is considered to be a valid value.
516 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
520 /// - Returns the value of the 'HOME' environment variable if it is set
521 /// (including to an empty string).
522 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
523 /// (including to an empty string).
524 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
526 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
533 /// match env::home_dir() {
534 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
535 /// None => println!("Impossible to get your home dir!"),
538 #[rustc_deprecated(since = "1.29.0",
539 reason = "This function's behavior is unexpected and probably not what you want. \
540 Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
541 #[stable(feature = "env", since = "1.0.0")]
542 pub fn home_dir() -> Option<PathBuf> {
546 /// Returns the path of a temporary directory.
550 /// Returns the value of the `TMPDIR` environment variable if it is
551 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
552 /// is no global temporary folder (it is usually allocated per-app), it returns
553 /// `/data/local/tmp`.
557 /// Returns the value of, in order, the `TMP`, `TEMP`,
558 /// `USERPROFILE` environment variable if any are set and not the empty
559 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
560 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
561 /// function uses internally.
563 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
567 /// use std::fs::File;
569 /// fn main() -> std::io::Result<()> {
570 /// let mut dir = env::temp_dir();
571 /// dir.push("foo.txt");
573 /// let f = File::create(dir)?;
577 #[stable(feature = "env", since = "1.0.0")]
578 pub fn temp_dir() -> PathBuf {
582 /// Returns the full filesystem path of the current running executable.
584 /// # Platform-specific behavior
586 /// If the executable was invoked through a symbolic link, some platforms will
587 /// return the path of the symbolic link and other platforms will return the
588 /// path of the symbolic link’s target.
592 /// Acquiring the path of the current executable is a platform-specific operation
593 /// that can fail for a good number of reasons. Some errors can include, but not
594 /// be limited to, filesystem operations failing or general syscall failures.
598 /// The output of this function should not be used in anything that might have
599 /// security implications. For example:
603 /// println!("{:?}", std::env::current_exe());
607 /// On Linux systems, if this is compiled as `foo`:
612 /// Ok("/home/alex/foo")
615 /// And you make a hard link of the program:
621 /// When you run it, you won’t get the path of the original executable, you’ll
622 /// get the path of the hard link:
626 /// Ok("/home/alex/bar")
629 /// This sort of behavior has been known to [lead to privilege escalation] when
630 /// used incorrectly.
632 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
639 /// match env::current_exe() {
640 /// Ok(exe_path) => println!("Path of this executable is: {}",
641 /// exe_path.display()),
642 /// Err(e) => println!("failed to get current exe path: {}", e),
645 #[stable(feature = "env", since = "1.0.0")]
646 pub fn current_exe() -> io::Result<PathBuf> {
647 os_imp::current_exe()
650 /// An iterator over the arguments of a process, yielding a [`String`] value for
653 /// This struct is created by the [`std::env::args`] function. See its
654 /// documentation for more.
656 /// The first element is traditionally the path of the executable, but it can be
657 /// set to arbitrary text, and may not even exist. This means this property
658 /// should not be relied upon for security purposes.
660 /// [`String`]: ../string/struct.String.html
661 /// [`std::env::args`]: ./fn.args.html
662 #[stable(feature = "env", since = "1.0.0")]
663 pub struct Args { inner: ArgsOs }
665 /// An iterator over the arguments of a process, yielding an [`OsString`] value
666 /// for each argument.
668 /// This struct is created by the [`std::env::args_os`] function. See its
669 /// documentation for more.
671 /// The first element is traditionally the path of the executable, but it can be
672 /// set to arbitrary text, and may not even exist. This means this property
673 /// should not be relied upon for security purposes.
675 /// [`OsString`]: ../ffi/struct.OsString.html
676 /// [`std::env::args_os`]: ./fn.args_os.html
677 #[stable(feature = "env", since = "1.0.0")]
678 pub struct ArgsOs { inner: sys::args::Args }
680 /// Returns the arguments which this program was started with (normally passed
681 /// via the command line).
683 /// The first element is traditionally the path of the executable, but it can be
684 /// set to arbitrary text, and may not even exist. This means this property should
685 /// not be relied upon for security purposes.
687 /// On Unix systems shell usually expands unquoted arguments with glob patterns
688 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
693 /// The returned iterator will panic during iteration if any argument to the
694 /// process is not valid unicode. If this is not desired,
695 /// use the [`args_os`] function instead.
702 /// // Prints each argument on a separate line
703 /// for argument in env::args() {
704 /// println!("{}", argument);
708 /// [`args_os`]: ./fn.args_os.html
709 #[stable(feature = "env", since = "1.0.0")]
710 pub fn args() -> Args {
711 Args { inner: args_os() }
714 /// Returns the arguments which this program was started with (normally passed
715 /// via the command line).
717 /// The first element is traditionally the path of the executable, but it can be
718 /// set to arbitrary text, and it may not even exist, so this property should
719 /// not be relied upon for security purposes.
726 /// // Prints each argument on a separate line
727 /// for argument in env::args_os() {
728 /// println!("{:?}", argument);
731 #[stable(feature = "env", since = "1.0.0")]
732 pub fn args_os() -> ArgsOs {
733 ArgsOs { inner: sys::args::args() }
736 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
737 impl !Send for Args {}
739 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
740 impl !Sync for Args {}
742 #[stable(feature = "env", since = "1.0.0")]
743 impl Iterator for Args {
745 fn next(&mut self) -> Option<String> {
746 self.inner.next().map(|s| s.into_string().unwrap())
748 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
750 fn last(mut self) -> Option<String> {
755 #[stable(feature = "env", since = "1.0.0")]
756 impl ExactSizeIterator for Args {
757 fn len(&self) -> usize { self.inner.len() }
758 fn is_empty(&self) -> bool { self.inner.is_empty() }
761 #[stable(feature = "env_iterators", since = "1.12.0")]
762 impl DoubleEndedIterator for Args {
763 fn next_back(&mut self) -> Option<String> {
764 self.inner.next_back().map(|s| s.into_string().unwrap())
768 #[stable(feature = "std_debug", since = "1.16.0")]
769 impl fmt::Debug for Args {
770 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
771 f.debug_struct("Args")
772 .field("inner", &self.inner.inner.inner_debug())
777 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
778 impl !Send for ArgsOs {}
780 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
781 impl !Sync for ArgsOs {}
783 #[stable(feature = "env", since = "1.0.0")]
784 impl Iterator for ArgsOs {
785 type Item = OsString;
786 fn next(&mut self) -> Option<OsString> { self.inner.next() }
787 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
789 fn last(mut self) -> Option<OsString> { self.next_back() }
792 #[stable(feature = "env", since = "1.0.0")]
793 impl ExactSizeIterator for ArgsOs {
794 fn len(&self) -> usize { self.inner.len() }
795 fn is_empty(&self) -> bool { self.inner.is_empty() }
798 #[stable(feature = "env_iterators", since = "1.12.0")]
799 impl DoubleEndedIterator for ArgsOs {
800 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
803 #[stable(feature = "std_debug", since = "1.16.0")]
804 impl fmt::Debug for ArgsOs {
805 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
806 f.debug_struct("ArgsOs")
807 .field("inner", &self.inner.inner_debug())
812 /// Constants associated with the current target
813 #[stable(feature = "env", since = "1.0.0")]
815 use crate::sys::env::os;
817 /// A string describing the architecture of the CPU that is currently
820 /// Some possible values:
832 #[stable(feature = "env", since = "1.0.0")]
833 pub const ARCH: &str = super::arch::ARCH;
835 /// The family of the operating system. Example value is `unix`.
837 /// Some possible values:
841 #[stable(feature = "env", since = "1.0.0")]
842 pub const FAMILY: &str = os::FAMILY;
844 /// A string describing the specific operating system in use.
845 /// Example value is `linux`.
847 /// Some possible values:
859 #[stable(feature = "env", since = "1.0.0")]
860 pub const OS: &str = os::OS;
862 /// Specifies the filename prefix used for shared libraries on this
863 /// platform. Example value is `lib`.
865 /// Some possible values:
868 /// - `""` (an empty string)
869 #[stable(feature = "env", since = "1.0.0")]
870 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
872 /// Specifies the filename suffix used for shared libraries on this
873 /// platform. Example value is `.so`.
875 /// Some possible values:
880 #[stable(feature = "env", since = "1.0.0")]
881 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
883 /// Specifies the file extension used for shared libraries on this
884 /// platform that goes after the dot. Example value is `so`.
886 /// Some possible values:
891 #[stable(feature = "env", since = "1.0.0")]
892 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
894 /// Specifies the filename suffix used for executable binaries on this
895 /// platform. Example value is `.exe`.
897 /// Some possible values:
902 /// - `""` (an empty string)
903 #[stable(feature = "env", since = "1.0.0")]
904 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
906 /// Specifies the file extension, if any, used for executable binaries
907 /// on this platform. Example value is `exe`.
909 /// Some possible values:
912 /// - `""` (an empty string)
913 #[stable(feature = "env", since = "1.0.0")]
914 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
917 #[cfg(target_arch = "x86")]
919 pub const ARCH: &str = "x86";
922 #[cfg(target_arch = "x86_64")]
924 pub const ARCH: &str = "x86_64";
927 #[cfg(target_arch = "arm")]
929 pub const ARCH: &str = "arm";
932 #[cfg(target_arch = "aarch64")]
934 pub const ARCH: &str = "aarch64";
937 #[cfg(target_arch = "mips")]
939 pub const ARCH: &str = "mips";
942 #[cfg(target_arch = "mips64")]
944 pub const ARCH: &str = "mips64";
947 #[cfg(target_arch = "powerpc")]
949 pub const ARCH: &str = "powerpc";
952 #[cfg(target_arch = "powerpc64")]
954 pub const ARCH: &str = "powerpc64";
957 #[cfg(target_arch = "s390x")]
959 pub const ARCH: &str = "s390x";
962 #[cfg(target_arch = "sparc64")]
964 pub const ARCH: &str = "sparc64";
967 #[cfg(target_arch = "le32")]
969 pub const ARCH: &str = "le32";
972 #[cfg(target_arch = "asmjs")]
974 pub const ARCH: &str = "asmjs";
977 #[cfg(target_arch = "wasm32")]
979 pub const ARCH: &str = "wasm32";
986 use crate::path::Path;
989 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
990 fn test_self_exe_path() {
991 let path = current_exe();
992 assert!(path.is_ok());
993 let path = path.unwrap();
995 // Hard to test this function
996 assert!(path.is_absolute());
1001 assert!((!Path::new("test-path").is_absolute()));
1003 #[cfg(not(target_env = "sgx"))]
1004 current_dir().unwrap();
1009 fn split_paths_windows() {
1010 use crate::path::PathBuf;
1012 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1013 split_paths(unparsed).collect::<Vec<_>>() ==
1014 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1017 assert!(check_parse("", &mut [""]));
1018 assert!(check_parse(r#""""#, &mut [""]));
1019 assert!(check_parse(";;", &mut ["", "", ""]));
1020 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1021 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1022 assert!(check_parse(r"c:\;c:\Program Files\",
1023 &mut [r"c:\", r"c:\Program Files\"]));
1024 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1025 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1026 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1031 fn split_paths_unix() {
1032 use crate::path::PathBuf;
1034 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1035 split_paths(unparsed).collect::<Vec<_>>() ==
1036 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1039 assert!(check_parse("", &mut [""]));
1040 assert!(check_parse("::", &mut ["", "", ""]));
1041 assert!(check_parse("/", &mut ["/"]));
1042 assert!(check_parse("/:", &mut ["/", ""]));
1043 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1048 fn join_paths_unix() {
1049 use crate::ffi::OsStr;
1051 fn test_eq(input: &[&str], output: &str) -> bool {
1052 &*join_paths(input.iter().cloned()).unwrap() ==
1056 assert!(test_eq(&[], ""));
1057 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1058 "/bin:/usr/bin:/usr/local/bin"));
1059 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1060 ":/bin:::/usr/bin:"));
1061 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1066 fn join_paths_windows() {
1067 use crate::ffi::OsStr;
1069 fn test_eq(input: &[&str], output: &str) -> bool {
1070 &*join_paths(input.iter().cloned()).unwrap() ==
1074 assert!(test_eq(&[], ""));
1075 assert!(test_eq(&[r"c:\windows", r"c:\"],
1076 r"c:\windows;c:\"));
1077 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1078 r";c:\windows;;;c:\;"));
1079 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1080 r#""c:\te;st";c:\"#));
1081 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1087 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1088 format!("{:?}", args()));
1090 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1091 format!("{:?}", args_os()));