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::split_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);
487 /// [`env::split_paths`]: fn.split_paths.html
488 #[stable(feature = "env", since = "1.0.0")]
489 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
490 where I: IntoIterator<Item=T>, T: AsRef<OsStr>
492 os_imp::join_paths(paths.into_iter()).map_err(|e| {
493 JoinPathsError { inner: e }
497 #[stable(feature = "env", since = "1.0.0")]
498 impl fmt::Display for JoinPathsError {
499 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
504 #[stable(feature = "env", since = "1.0.0")]
505 impl Error for JoinPathsError {
506 fn description(&self) -> &str { self.inner.description() }
509 /// Returns the path of the current user's home directory if known.
513 /// - Returns the value of the 'HOME' environment variable if it is set
514 /// (including to an empty string).
515 /// - Otherwise, it tries to determine the home directory by invoking the `getpwuid_r` function
516 /// using the UID of the current user. An empty home directory field returned from the
517 /// `getpwuid_r` function is considered to be a valid value.
518 /// - Returns `None` if the current user has no entry in the /etc/passwd file.
522 /// - Returns the value of the 'HOME' environment variable if it is set
523 /// (including to an empty string).
524 /// - Otherwise, returns the value of the 'USERPROFILE' environment variable if it is set
525 /// (including to an empty string).
526 /// - If both do not exist, [`GetUserProfileDirectory`][msdn] is used to return the path.
528 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
535 /// match env::home_dir() {
536 /// Some(path) => println!("Your home directory, probably: {}", path.display()),
537 /// None => println!("Impossible to get your home dir!"),
540 #[rustc_deprecated(since = "1.29.0",
541 reason = "This function's behavior is unexpected and probably not what you want. \
542 Consider using the home_dir function from https://crates.io/crates/dirs instead.")]
543 #[stable(feature = "env", since = "1.0.0")]
544 pub fn home_dir() -> Option<PathBuf> {
548 /// Returns the path of a temporary directory.
552 /// Returns the value of the `TMPDIR` environment variable if it is
553 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
554 /// is no global temporary folder (it is usually allocated per-app), it returns
555 /// `/data/local/tmp`.
559 /// Returns the value of, in order, the `TMP`, `TEMP`,
560 /// `USERPROFILE` environment variable if any are set and not the empty
561 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
562 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
563 /// function uses internally.
565 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
569 /// use std::fs::File;
571 /// fn main() -> std::io::Result<()> {
572 /// let mut dir = env::temp_dir();
573 /// dir.push("foo.txt");
575 /// let f = File::create(dir)?;
579 #[stable(feature = "env", since = "1.0.0")]
580 pub fn temp_dir() -> PathBuf {
584 /// Returns the full filesystem path of the current running executable.
586 /// # Platform-specific behavior
588 /// If the executable was invoked through a symbolic link, some platforms will
589 /// return the path of the symbolic link and other platforms will return the
590 /// path of the symbolic link’s target.
594 /// Acquiring the path of the current executable is a platform-specific operation
595 /// that can fail for a good number of reasons. Some errors can include, but not
596 /// be limited to, filesystem operations failing or general syscall failures.
600 /// The output of this function should not be used in anything that might have
601 /// security implications. For example:
605 /// println!("{:?}", std::env::current_exe());
609 /// On Linux systems, if this is compiled as `foo`:
614 /// Ok("/home/alex/foo")
617 /// And you make a hard link of the program:
623 /// When you run it, you won’t get the path of the original executable, you’ll
624 /// get the path of the hard link:
628 /// Ok("/home/alex/bar")
631 /// This sort of behavior has been known to [lead to privilege escalation] when
632 /// used incorrectly.
634 /// [lead to privilege escalation]: https://securityvulns.com/Wdocument183.html
641 /// match env::current_exe() {
642 /// Ok(exe_path) => println!("Path of this executable is: {}",
643 /// exe_path.display()),
644 /// Err(e) => println!("failed to get current exe path: {}", e),
647 #[stable(feature = "env", since = "1.0.0")]
648 pub fn current_exe() -> io::Result<PathBuf> {
649 os_imp::current_exe()
652 /// An iterator over the arguments of a process, yielding a [`String`] value for
655 /// This struct is created by the [`std::env::args`] function. See its
656 /// documentation for more.
658 /// The first element is traditionally the path of the executable, but it can be
659 /// set to arbitrary text, and may not even exist. This means this property
660 /// should not be relied upon for security purposes.
662 /// [`String`]: ../string/struct.String.html
663 /// [`std::env::args`]: ./fn.args.html
664 #[stable(feature = "env", since = "1.0.0")]
665 pub struct Args { inner: ArgsOs }
667 /// An iterator over the arguments of a process, yielding an [`OsString`] value
668 /// for each argument.
670 /// This struct is created by the [`std::env::args_os`] function. See its
671 /// documentation for more.
673 /// The first element is traditionally the path of the executable, but it can be
674 /// set to arbitrary text, and may not even exist. This means this property
675 /// should not be relied upon for security purposes.
677 /// [`OsString`]: ../ffi/struct.OsString.html
678 /// [`std::env::args_os`]: ./fn.args_os.html
679 #[stable(feature = "env", since = "1.0.0")]
680 pub struct ArgsOs { inner: sys::args::Args }
682 /// Returns the arguments which this program was started with (normally passed
683 /// via the command line).
685 /// The first element is traditionally the path of the executable, but it can be
686 /// set to arbitrary text, and may not even exist. This means this property should
687 /// not be relied upon for security purposes.
689 /// On Unix systems shell usually expands unquoted arguments with glob patterns
690 /// (such as `*` and `?`). On Windows this is not done, and such arguments are
695 /// The returned iterator will panic during iteration if any argument to the
696 /// process is not valid unicode. If this is not desired,
697 /// use the [`args_os`] function instead.
704 /// // Prints each argument on a separate line
705 /// for argument in env::args() {
706 /// println!("{}", argument);
710 /// [`args_os`]: ./fn.args_os.html
711 #[stable(feature = "env", since = "1.0.0")]
712 pub fn args() -> Args {
713 Args { inner: args_os() }
716 /// Returns the arguments which this program was started with (normally passed
717 /// via the command line).
719 /// The first element is traditionally the path of the executable, but it can be
720 /// set to arbitrary text, and it may not even exist, so this property should
721 /// not be relied upon for security purposes.
728 /// // Prints each argument on a separate line
729 /// for argument in env::args_os() {
730 /// println!("{:?}", argument);
733 #[stable(feature = "env", since = "1.0.0")]
734 pub fn args_os() -> ArgsOs {
735 ArgsOs { inner: sys::args::args() }
738 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
739 impl !Send for Args {}
741 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
742 impl !Sync for Args {}
744 #[stable(feature = "env", since = "1.0.0")]
745 impl Iterator for Args {
747 fn next(&mut self) -> Option<String> {
748 self.inner.next().map(|s| s.into_string().unwrap())
750 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
753 #[stable(feature = "env", since = "1.0.0")]
754 impl ExactSizeIterator for Args {
755 fn len(&self) -> usize { self.inner.len() }
756 fn is_empty(&self) -> bool { self.inner.is_empty() }
759 #[stable(feature = "env_iterators", since = "1.12.0")]
760 impl DoubleEndedIterator for Args {
761 fn next_back(&mut self) -> Option<String> {
762 self.inner.next_back().map(|s| s.into_string().unwrap())
766 #[stable(feature = "std_debug", since = "1.16.0")]
767 impl fmt::Debug for Args {
768 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
769 f.debug_struct("Args")
770 .field("inner", &self.inner.inner.inner_debug())
775 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
776 impl !Send for ArgsOs {}
778 #[stable(feature = "env_unimpl_send_sync", since = "1.26.0")]
779 impl !Sync for ArgsOs {}
781 #[stable(feature = "env", since = "1.0.0")]
782 impl Iterator for ArgsOs {
783 type Item = OsString;
784 fn next(&mut self) -> Option<OsString> { self.inner.next() }
785 fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
788 #[stable(feature = "env", since = "1.0.0")]
789 impl ExactSizeIterator for ArgsOs {
790 fn len(&self) -> usize { self.inner.len() }
791 fn is_empty(&self) -> bool { self.inner.is_empty() }
794 #[stable(feature = "env_iterators", since = "1.12.0")]
795 impl DoubleEndedIterator for ArgsOs {
796 fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
799 #[stable(feature = "std_debug", since = "1.16.0")]
800 impl fmt::Debug for ArgsOs {
801 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
802 f.debug_struct("ArgsOs")
803 .field("inner", &self.inner.inner_debug())
808 /// Constants associated with the current target
809 #[stable(feature = "env", since = "1.0.0")]
811 use crate::sys::env::os;
813 /// A string describing the architecture of the CPU that is currently
816 /// Some possible values:
828 #[stable(feature = "env", since = "1.0.0")]
829 pub const ARCH: &str = super::arch::ARCH;
831 /// The family of the operating system. Example value is `unix`.
833 /// Some possible values:
837 #[stable(feature = "env", since = "1.0.0")]
838 pub const FAMILY: &str = os::FAMILY;
840 /// A string describing the specific operating system in use.
841 /// Example value is `linux`.
843 /// Some possible values:
855 #[stable(feature = "env", since = "1.0.0")]
856 pub const OS: &str = os::OS;
858 /// Specifies the filename prefix used for shared libraries on this
859 /// platform. Example value is `lib`.
861 /// Some possible values:
864 /// - `""` (an empty string)
865 #[stable(feature = "env", since = "1.0.0")]
866 pub const DLL_PREFIX: &str = os::DLL_PREFIX;
868 /// Specifies the filename suffix used for shared libraries on this
869 /// platform. Example value is `.so`.
871 /// Some possible values:
876 #[stable(feature = "env", since = "1.0.0")]
877 pub const DLL_SUFFIX: &str = os::DLL_SUFFIX;
879 /// Specifies the file extension used for shared libraries on this
880 /// platform that goes after the dot. Example value is `so`.
882 /// Some possible values:
887 #[stable(feature = "env", since = "1.0.0")]
888 pub const DLL_EXTENSION: &str = os::DLL_EXTENSION;
890 /// Specifies the filename suffix used for executable binaries on this
891 /// platform. Example value is `.exe`.
893 /// Some possible values:
898 /// - `""` (an empty string)
899 #[stable(feature = "env", since = "1.0.0")]
900 pub const EXE_SUFFIX: &str = os::EXE_SUFFIX;
902 /// Specifies the file extension, if any, used for executable binaries
903 /// on this platform. Example value is `exe`.
905 /// Some possible values:
908 /// - `""` (an empty string)
909 #[stable(feature = "env", since = "1.0.0")]
910 pub const EXE_EXTENSION: &str = os::EXE_EXTENSION;
913 #[cfg(target_arch = "x86")]
915 pub const ARCH: &str = "x86";
918 #[cfg(target_arch = "x86_64")]
920 pub const ARCH: &str = "x86_64";
923 #[cfg(target_arch = "arm")]
925 pub const ARCH: &str = "arm";
928 #[cfg(target_arch = "aarch64")]
930 pub const ARCH: &str = "aarch64";
933 #[cfg(target_arch = "mips")]
935 pub const ARCH: &str = "mips";
938 #[cfg(target_arch = "mips64")]
940 pub const ARCH: &str = "mips64";
943 #[cfg(target_arch = "powerpc")]
945 pub const ARCH: &str = "powerpc";
948 #[cfg(target_arch = "powerpc64")]
950 pub const ARCH: &str = "powerpc64";
953 #[cfg(target_arch = "s390x")]
955 pub const ARCH: &str = "s390x";
958 #[cfg(target_arch = "sparc64")]
960 pub const ARCH: &str = "sparc64";
963 #[cfg(target_arch = "le32")]
965 pub const ARCH: &str = "le32";
968 #[cfg(target_arch = "asmjs")]
970 pub const ARCH: &str = "asmjs";
973 #[cfg(target_arch = "wasm32")]
975 pub const ARCH: &str = "wasm32";
982 use crate::path::Path;
985 #[cfg_attr(any(target_os = "emscripten", target_env = "sgx"), ignore)]
986 fn test_self_exe_path() {
987 let path = current_exe();
988 assert!(path.is_ok());
989 let path = path.unwrap();
991 // Hard to test this function
992 assert!(path.is_absolute());
997 assert!((!Path::new("test-path").is_absolute()));
999 #[cfg(not(target_env = "sgx"))]
1000 current_dir().unwrap();
1005 fn split_paths_windows() {
1006 use crate::path::PathBuf;
1008 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1009 split_paths(unparsed).collect::<Vec<_>>() ==
1010 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1013 assert!(check_parse("", &mut [""]));
1014 assert!(check_parse(r#""""#, &mut [""]));
1015 assert!(check_parse(";;", &mut ["", "", ""]));
1016 assert!(check_parse(r"c:\", &mut [r"c:\"]));
1017 assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
1018 assert!(check_parse(r"c:\;c:\Program Files\",
1019 &mut [r"c:\", r"c:\Program Files\"]));
1020 assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
1021 assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1022 &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1027 fn split_paths_unix() {
1028 use crate::path::PathBuf;
1030 fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1031 split_paths(unparsed).collect::<Vec<_>>() ==
1032 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1035 assert!(check_parse("", &mut [""]));
1036 assert!(check_parse("::", &mut ["", "", ""]));
1037 assert!(check_parse("/", &mut ["/"]));
1038 assert!(check_parse("/:", &mut ["/", ""]));
1039 assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1044 fn join_paths_unix() {
1045 use crate::ffi::OsStr;
1047 fn test_eq(input: &[&str], output: &str) -> bool {
1048 &*join_paths(input.iter().cloned()).unwrap() ==
1052 assert!(test_eq(&[], ""));
1053 assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1054 "/bin:/usr/bin:/usr/local/bin"));
1055 assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1056 ":/bin:::/usr/bin:"));
1057 assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1062 fn join_paths_windows() {
1063 use crate::ffi::OsStr;
1065 fn test_eq(input: &[&str], output: &str) -> bool {
1066 &*join_paths(input.iter().cloned()).unwrap() ==
1070 assert!(test_eq(&[], ""));
1071 assert!(test_eq(&[r"c:\windows", r"c:\"],
1072 r"c:\windows;c:\"));
1073 assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1074 r";c:\windows;;;c:\;"));
1075 assert!(test_eq(&[r"c:\te;st", r"c:\"],
1076 r#""c:\te;st";c:\"#));
1077 assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1083 format!("Args {{ inner: {:?} }}", args().collect::<Vec<_>>()),
1084 format!("{:?}", args()));
1086 format!("ArgsOs {{ inner: {:?} }}", args_os().collect::<Vec<_>>()),
1087 format!("{:?}", args_os()));