]> git.lizzy.rs Git - rust.git/blob - src/libstd/env.rs
Rollup merge of #39604 - est31:i128_tests, r=alexcrichton
[rust.git] / src / libstd / env.rs
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.
4 //
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.
10
11 //! Inspection and manipulation of the process's environment.
12 //!
13 //! This module contains functions to inspect various aspects such as
14 //! environment variables, process arguments, the current directory, and various
15 //! other important directories.
16
17 #![stable(feature = "env", since = "1.0.0")]
18
19 use error::Error;
20 use ffi::{OsStr, OsString};
21 use fmt;
22 use io;
23 use path::{Path, PathBuf};
24 use sys;
25 use sys::os as os_imp;
26
27 /// Returns the current working directory as a [`PathBuf`].
28 ///
29 /// # Errors
30 ///
31 /// Returns an [`Err`] if the current working directory value is invalid.
32 /// Possible cases:
33 ///
34 /// * Current directory does not exist.
35 /// * There are insufficient permissions to access the current directory.
36 ///
37 /// [`PathBuf`]: ../../std/path/struct.PathBuf.html
38 /// [`Err`]: ../../std/result/enum.Result.html#method.err
39 ///
40 /// # Examples
41 ///
42 /// ```
43 /// use std::env;
44 ///
45 /// // We assume that we are in a valid directory.
46 /// let p = env::current_dir().unwrap();
47 /// println!("The current directory is {}", p.display());
48 /// ```
49 #[stable(feature = "env", since = "1.0.0")]
50 pub fn current_dir() -> io::Result<PathBuf> {
51     os_imp::getcwd()
52 }
53
54 /// Changes the current working directory to the specified path, returning
55 /// whether the change was completed successfully or not.
56 ///
57 /// # Examples
58 ///
59 /// ```
60 /// use std::env;
61 /// use std::path::Path;
62 ///
63 /// let root = Path::new("/");
64 /// assert!(env::set_current_dir(&root).is_ok());
65 /// println!("Successfully changed working directory to {}!", root.display());
66 /// ```
67 #[stable(feature = "env", since = "1.0.0")]
68 pub fn set_current_dir<P: AsRef<Path>>(p: P) -> io::Result<()> {
69     os_imp::chdir(p.as_ref())
70 }
71
72 /// An iterator over a snapshot of the environment variables of this process.
73 ///
74 /// This structure is created through the [`std::env::vars`] function.
75 ///
76 /// [`std::env::vars`]: fn.vars.html
77 #[stable(feature = "env", since = "1.0.0")]
78 pub struct Vars { inner: VarsOs }
79
80 /// An iterator over a snapshot of the environment variables of this process.
81 ///
82 /// This structure is created through the [`std::env::vars_os`] function.
83 ///
84 /// [`std::env::vars_os`]: fn.vars_os.html
85 #[stable(feature = "env", since = "1.0.0")]
86 pub struct VarsOs { inner: os_imp::Env }
87
88 /// Returns an iterator of (variable, value) pairs of strings, for all the
89 /// environment variables of the current process.
90 ///
91 /// The returned iterator contains a snapshot of the process's environment
92 /// variables at the time of this invocation. Modifications to environment
93 /// variables afterwards will not be reflected in the returned iterator.
94 ///
95 /// # Panics
96 ///
97 /// While iterating, the returned iterator will panic if any key or value in the
98 /// environment is not valid unicode. If this is not desired, consider using the
99 /// `env::vars_os` function.
100 ///
101 /// # Examples
102 ///
103 /// ```
104 /// use std::env;
105 ///
106 /// // We will iterate through the references to the element returned by
107 /// // env::vars();
108 /// for (key, value) in env::vars() {
109 ///     println!("{}: {}", key, value);
110 /// }
111 /// ```
112 #[stable(feature = "env", since = "1.0.0")]
113 pub fn vars() -> Vars {
114     Vars { inner: vars_os() }
115 }
116
117 /// Returns an iterator of (variable, value) pairs of OS strings, for all the
118 /// environment variables of the current process.
119 ///
120 /// The returned iterator contains a snapshot of the process's environment
121 /// variables at the time of this invocation. Modifications to environment
122 /// variables afterwards will not be reflected in the returned iterator.
123 ///
124 /// # Examples
125 ///
126 /// ```
127 /// use std::env;
128 ///
129 /// // We will iterate through the references to the element returned by
130 /// // env::vars_os();
131 /// for (key, value) in env::vars_os() {
132 ///     println!("{:?}: {:?}", key, value);
133 /// }
134 /// ```
135 #[stable(feature = "env", since = "1.0.0")]
136 pub fn vars_os() -> VarsOs {
137     VarsOs { inner: os_imp::env() }
138 }
139
140 #[stable(feature = "env", since = "1.0.0")]
141 impl Iterator for Vars {
142     type Item = (String, String);
143     fn next(&mut self) -> Option<(String, String)> {
144         self.inner.next().map(|(a, b)| {
145             (a.into_string().unwrap(), b.into_string().unwrap())
146         })
147     }
148     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
149 }
150
151 #[stable(feature = "std_debug", since = "1.16.0")]
152 impl fmt::Debug for Vars {
153     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
154         f.pad("Vars { .. }")
155     }
156 }
157
158 #[stable(feature = "env", since = "1.0.0")]
159 impl Iterator for VarsOs {
160     type Item = (OsString, OsString);
161     fn next(&mut self) -> Option<(OsString, OsString)> { self.inner.next() }
162     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
163 }
164
165 #[stable(feature = "std_debug", since = "1.16.0")]
166 impl fmt::Debug for VarsOs {
167     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
168         f.pad("VarsOs { .. }")
169     }
170 }
171
172 /// Fetches the environment variable `key` from the current process.
173 ///
174 /// The returned result is `Ok(s)` if the environment variable is present and is
175 /// valid unicode. If the environment variable is not present, or it is not
176 /// valid unicode, then `Err` will be returned.
177 ///
178 /// # Examples
179 ///
180 /// ```
181 /// use std::env;
182 ///
183 /// let key = "HOME";
184 /// match env::var(key) {
185 ///     Ok(val) => println!("{}: {:?}", key, val),
186 ///     Err(e) => println!("couldn't interpret {}: {}", key, e),
187 /// }
188 /// ```
189 #[stable(feature = "env", since = "1.0.0")]
190 pub fn var<K: AsRef<OsStr>>(key: K) -> Result<String, VarError> {
191     _var(key.as_ref())
192 }
193
194 fn _var(key: &OsStr) -> Result<String, VarError> {
195     match var_os(key) {
196         Some(s) => s.into_string().map_err(VarError::NotUnicode),
197         None => Err(VarError::NotPresent)
198     }
199 }
200
201 /// Fetches the environment variable `key` from the current process, returning
202 /// `None` if the variable isn't set.
203 ///
204 /// # Examples
205 ///
206 /// ```
207 /// use std::env;
208 ///
209 /// let key = "HOME";
210 /// match env::var_os(key) {
211 ///     Some(val) => println!("{}: {:?}", key, val),
212 ///     None => println!("{} is not defined in the environment.", key)
213 /// }
214 /// ```
215 #[stable(feature = "env", since = "1.0.0")]
216 pub fn var_os<K: AsRef<OsStr>>(key: K) -> Option<OsString> {
217     _var_os(key.as_ref())
218 }
219
220 fn _var_os(key: &OsStr) -> Option<OsString> {
221     os_imp::getenv(key).unwrap_or_else(|e| {
222         panic!("failed to get environment variable `{:?}`: {}", key, e)
223     })
224 }
225
226 /// Possible errors from the [`env::var`] function.
227 ///
228 /// [`env::var`]: fn.var.html
229 #[derive(Debug, PartialEq, Eq, Clone)]
230 #[stable(feature = "env", since = "1.0.0")]
231 pub enum VarError {
232     /// The specified environment variable was not present in the current
233     /// process's environment.
234     #[stable(feature = "env", since = "1.0.0")]
235     NotPresent,
236
237     /// The specified environment variable was found, but it did not contain
238     /// valid unicode data. The found data is returned as a payload of this
239     /// variant.
240     #[stable(feature = "env", since = "1.0.0")]
241     NotUnicode(#[stable(feature = "env", since = "1.0.0")] OsString),
242 }
243
244 #[stable(feature = "env", since = "1.0.0")]
245 impl fmt::Display for VarError {
246     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
247         match *self {
248             VarError::NotPresent => write!(f, "environment variable not found"),
249             VarError::NotUnicode(ref s) => {
250                 write!(f, "environment variable was not valid unicode: {:?}", s)
251             }
252         }
253     }
254 }
255
256 #[stable(feature = "env", since = "1.0.0")]
257 impl Error for VarError {
258     fn description(&self) -> &str {
259         match *self {
260             VarError::NotPresent => "environment variable not found",
261             VarError::NotUnicode(..) => "environment variable was not valid unicode",
262         }
263     }
264 }
265
266 /// Sets the environment variable `k` to the value `v` for the currently running
267 /// process.
268 ///
269 /// Note that while concurrent access to environment variables is safe in Rust,
270 /// some platforms only expose inherently unsafe non-threadsafe APIs for
271 /// inspecting the environment. As a result extra care needs to be taken when
272 /// auditing calls to unsafe external FFI functions to ensure that any external
273 /// environment accesses are properly synchronized with accesses in Rust.
274 ///
275 /// Discussion of this unsafety on Unix may be found in:
276 ///
277 ///  - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
278 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
279 ///
280 /// # Panics
281 ///
282 /// This function may panic if `key` is empty, contains an ASCII equals sign
283 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
284 /// character.
285 ///
286 /// # Examples
287 ///
288 /// ```
289 /// use std::env;
290 ///
291 /// let key = "KEY";
292 /// env::set_var(key, "VALUE");
293 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
294 /// ```
295 #[stable(feature = "env", since = "1.0.0")]
296 pub fn set_var<K: AsRef<OsStr>, V: AsRef<OsStr>>(k: K, v: V) {
297     _set_var(k.as_ref(), v.as_ref())
298 }
299
300 fn _set_var(k: &OsStr, v: &OsStr) {
301     os_imp::setenv(k, v).unwrap_or_else(|e| {
302         panic!("failed to set environment variable `{:?}` to `{:?}`: {}",
303                k, v, e)
304     })
305 }
306
307 /// Removes an environment variable from the environment of the currently running process.
308 ///
309 /// Note that while concurrent access to environment variables is safe in Rust,
310 /// some platforms only expose inherently unsafe non-threadsafe APIs for
311 /// inspecting the environment. As a result extra care needs to be taken when
312 /// auditing calls to unsafe external FFI functions to ensure that any external
313 /// environment accesses are properly synchronized with accesses in Rust.
314 ///
315 /// Discussion of this unsafety on Unix may be found in:
316 ///
317 ///  - [Austin Group Bugzilla](http://austingroupbugs.net/view.php?id=188)
318 ///  - [GNU C library Bugzilla](https://sourceware.org/bugzilla/show_bug.cgi?id=15607#c2)
319 ///
320 /// # Panics
321 ///
322 /// This function may panic if `key` is empty, contains an ASCII equals sign
323 /// `'='` or the NUL character `'\0'`, or when the value contains the NUL
324 /// character.
325 ///
326 /// # Examples
327 ///
328 /// ```
329 /// use std::env;
330 ///
331 /// let key = "KEY";
332 /// env::set_var(key, "VALUE");
333 /// assert_eq!(env::var(key), Ok("VALUE".to_string()));
334 ///
335 /// env::remove_var(key);
336 /// assert!(env::var(key).is_err());
337 /// ```
338 #[stable(feature = "env", since = "1.0.0")]
339 pub fn remove_var<K: AsRef<OsStr>>(k: K) {
340     _remove_var(k.as_ref())
341 }
342
343 fn _remove_var(k: &OsStr) {
344     os_imp::unsetenv(k).unwrap_or_else(|e| {
345         panic!("failed to remove environment variable `{:?}`: {}", k, e)
346     })
347 }
348
349 /// An iterator over `PathBuf` instances for parsing an environment variable
350 /// according to platform-specific conventions.
351 ///
352 /// This structure is returned from `std::env::split_paths`.
353 #[stable(feature = "env", since = "1.0.0")]
354 pub struct SplitPaths<'a> { inner: os_imp::SplitPaths<'a> }
355
356 /// Parses input according to platform conventions for the `PATH`
357 /// environment variable.
358 ///
359 /// Returns an iterator over the paths contained in `unparsed`.
360 ///
361 /// # Examples
362 ///
363 /// ```
364 /// use std::env;
365 ///
366 /// let key = "PATH";
367 /// match env::var_os(key) {
368 ///     Some(paths) => {
369 ///         for path in env::split_paths(&paths) {
370 ///             println!("'{}'", path.display());
371 ///         }
372 ///     }
373 ///     None => println!("{} is not defined in the environment.", key)
374 /// }
375 /// ```
376 #[stable(feature = "env", since = "1.0.0")]
377 pub fn split_paths<T: AsRef<OsStr> + ?Sized>(unparsed: &T) -> SplitPaths {
378     SplitPaths { inner: os_imp::split_paths(unparsed.as_ref()) }
379 }
380
381 #[stable(feature = "env", since = "1.0.0")]
382 impl<'a> Iterator for SplitPaths<'a> {
383     type Item = PathBuf;
384     fn next(&mut self) -> Option<PathBuf> { self.inner.next() }
385     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
386 }
387
388 #[stable(feature = "std_debug", since = "1.16.0")]
389 impl<'a> fmt::Debug for SplitPaths<'a> {
390     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
391         f.pad("SplitPaths { .. }")
392     }
393 }
394
395 /// Error type returned from `std::env::join_paths` when paths fail to be
396 /// joined.
397 #[derive(Debug)]
398 #[stable(feature = "env", since = "1.0.0")]
399 pub struct JoinPathsError {
400     inner: os_imp::JoinPathsError
401 }
402
403 /// Joins a collection of [`Path`]s appropriately for the `PATH`
404 /// environment variable.
405 ///
406 /// Returns an [`OsString`] on success.
407 ///
408 /// Returns an [`Err`][err] (containing an error message) if one of the input
409 /// [`Path`]s contains an invalid character for constructing the `PATH`
410 /// variable (a double quote on Windows or a colon on Unix).
411 ///
412 /// [`Path`]: ../../std/path/struct.Path.html
413 /// [`OsString`]: ../../std/ffi/struct.OsString.html
414 /// [err]: ../../std/result/enum.Result.html#variant.Err
415 ///
416 /// # Examples
417 ///
418 /// ```
419 /// use std::env;
420 /// use std::path::PathBuf;
421 ///
422 /// if let Some(path) = env::var_os("PATH") {
423 ///     let mut paths = env::split_paths(&path).collect::<Vec<_>>();
424 ///     paths.push(PathBuf::from("/home/xyz/bin"));
425 ///     let new_path = env::join_paths(paths).unwrap();
426 ///     env::set_var("PATH", &new_path);
427 /// }
428 /// ```
429 #[stable(feature = "env", since = "1.0.0")]
430 pub fn join_paths<I, T>(paths: I) -> Result<OsString, JoinPathsError>
431     where I: IntoIterator<Item=T>, T: AsRef<OsStr>
432 {
433     os_imp::join_paths(paths.into_iter()).map_err(|e| {
434         JoinPathsError { inner: e }
435     })
436 }
437
438 #[stable(feature = "env", since = "1.0.0")]
439 impl fmt::Display for JoinPathsError {
440     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
441         self.inner.fmt(f)
442     }
443 }
444
445 #[stable(feature = "env", since = "1.0.0")]
446 impl Error for JoinPathsError {
447     fn description(&self) -> &str { self.inner.description() }
448 }
449
450 /// Returns the path of the current user's home directory if known.
451 ///
452 /// # Unix
453 ///
454 /// Returns the value of the 'HOME' environment variable if it is set
455 /// and not equal to the empty string. Otherwise, it tries to determine the
456 /// home directory by invoking the `getpwuid_r` function on the UID of the
457 /// current user.
458 ///
459 /// # Windows
460 ///
461 /// Returns the value of the 'HOME' environment variable if it is
462 /// set and not equal to the empty string. Otherwise, returns the value of the
463 /// 'USERPROFILE' environment variable if it is set and not equal to the empty
464 /// string. If both do not exist, [`GetUserProfileDirectory`][msdn] is used to
465 /// return the appropriate path.
466 ///
467 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/bb762280(v=vs.85).aspx
468 ///
469 /// # Examples
470 ///
471 /// ```
472 /// use std::env;
473 ///
474 /// match env::home_dir() {
475 ///     Some(path) => println!("{}", path.display()),
476 ///     None => println!("Impossible to get your home dir!"),
477 /// }
478 /// ```
479 #[stable(feature = "env", since = "1.0.0")]
480 pub fn home_dir() -> Option<PathBuf> {
481     os_imp::home_dir()
482 }
483
484 /// Returns the path of a temporary directory.
485 ///
486 /// On Unix, returns the value of the `TMPDIR` environment variable if it is
487 /// set, otherwise for non-Android it returns `/tmp`. If Android, since there
488 /// is no global temporary folder (it is usually allocated per-app), it returns
489 /// `/data/local/tmp`.
490 ///
491 /// On Windows, returns the value of, in order, the `TMP`, `TEMP`,
492 /// `USERPROFILE` environment variable if any are set and not the empty
493 /// string. Otherwise, `temp_dir` returns the path of the Windows directory.
494 /// This behavior is identical to that of [`GetTempPath`][msdn], which this
495 /// function uses internally.
496 ///
497 /// [msdn]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa364992(v=vs.85).aspx
498 ///
499 /// ```
500 /// use std::env;
501 /// use std::fs::File;
502 ///
503 /// # fn foo() -> std::io::Result<()> {
504 /// let mut dir = env::temp_dir();
505 /// dir.push("foo.txt");
506 ///
507 /// let f = File::create(dir)?;
508 /// # Ok(())
509 /// # }
510 /// ```
511 #[stable(feature = "env", since = "1.0.0")]
512 pub fn temp_dir() -> PathBuf {
513     os_imp::temp_dir()
514 }
515
516 /// Returns the full filesystem path of the current running executable.
517 ///
518 /// The path returned is not necessarily a "real path" of the executable as
519 /// there may be intermediate symlinks.
520 ///
521 /// # Errors
522 ///
523 /// Acquiring the path of the current executable is a platform-specific operation
524 /// that can fail for a good number of reasons. Some errors can include, but not
525 /// be limited to, filesystem operations failing or general syscall failures.
526 ///
527 /// # Security
528 ///
529 /// The output of this function should not be used in anything that might have
530 /// security implications. For example:
531 ///
532 /// ```
533 /// fn main() {
534 ///     println!("{:?}", std::env::current_exe());
535 /// }
536 /// ```
537 ///
538 /// On Linux systems, if this is compiled as `foo`:
539 ///
540 /// ```bash
541 /// $ rustc foo.rs
542 /// $ ./foo
543 /// Ok("/home/alex/foo")
544 /// ```
545 ///
546 /// And you make a symbolic link of the program:
547 ///
548 /// ```bash
549 /// $ ln foo bar
550 /// ```
551 ///
552 /// When you run it, you won't get the original executable, you'll get the
553 /// symlink:
554 ///
555 /// ```bash
556 /// $ ./bar
557 /// Ok("/home/alex/bar")
558 /// ```
559 ///
560 /// This sort of behavior has been known to [lead to privilege escalation] when
561 /// used incorrectly, for example.
562 ///
563 /// [lead to privilege escalation]: http://securityvulns.com/Wdocument183.html
564 ///
565 /// # Examples
566 ///
567 /// ```
568 /// use std::env;
569 ///
570 /// match env::current_exe() {
571 ///     Ok(exe_path) => println!("Path of this executable is: {}",
572 ///                               exe_path.display()),
573 ///     Err(e) => println!("failed to get current exe path: {}", e),
574 /// };
575 /// ```
576 #[stable(feature = "env", since = "1.0.0")]
577 pub fn current_exe() -> io::Result<PathBuf> {
578     os_imp::current_exe()
579 }
580
581 /// An iterator over the arguments of a process, yielding a [`String`] value
582 /// for each argument.
583 ///
584 /// This structure is created through the [`std::env::args`] function.
585 ///
586 /// [`String`]: ../string/struct.String.html
587 /// [`std::env::args`]: ./fn.args.html
588 #[stable(feature = "env", since = "1.0.0")]
589 pub struct Args { inner: ArgsOs }
590
591 /// An iterator over the arguments of a process, yielding an [`OsString`] value
592 /// for each argument.
593 ///
594 /// This structure is created through the [`std::env::args_os`] function.
595 ///
596 /// [`OsString`]: ../ffi/struct.OsString.html
597 /// [`std::env::args_os`]: ./fn.args_os.html
598 #[stable(feature = "env", since = "1.0.0")]
599 pub struct ArgsOs { inner: sys::args::Args }
600
601 /// Returns the arguments which this program was started with (normally passed
602 /// via the command line).
603 ///
604 /// The first element is traditionally the path of the executable, but it can be
605 /// set to arbitrary text, and may not even exist. This means this property should
606 /// not be relied upon for security purposes.
607 ///
608 /// # Panics
609 ///
610 /// The returned iterator will panic during iteration if any argument to the
611 /// process is not valid unicode. If this is not desired,
612 /// use the [`args_os`] function instead.
613 ///
614 /// # Examples
615 ///
616 /// ```
617 /// use std::env;
618 ///
619 /// // Prints each argument on a separate line
620 /// for argument in env::args() {
621 ///     println!("{}", argument);
622 /// }
623 /// ```
624 ///
625 /// [`args_os`]: ./fn.args_os.html
626 #[stable(feature = "env", since = "1.0.0")]
627 pub fn args() -> Args {
628     Args { inner: args_os() }
629 }
630
631 /// Returns the arguments which this program was started with (normally passed
632 /// via the command line).
633 ///
634 /// The first element is traditionally the path of the executable, but it can be
635 /// set to arbitrary text, and it may not even exist, so this property should
636 /// not be relied upon for security purposes.
637 ///
638 /// # Examples
639 ///
640 /// ```
641 /// use std::env;
642 ///
643 /// // Prints each argument on a separate line
644 /// for argument in env::args_os() {
645 ///     println!("{:?}", argument);
646 /// }
647 /// ```
648 #[stable(feature = "env", since = "1.0.0")]
649 pub fn args_os() -> ArgsOs {
650     ArgsOs { inner: sys::args::args() }
651 }
652
653 #[stable(feature = "env", since = "1.0.0")]
654 impl Iterator for Args {
655     type Item = String;
656     fn next(&mut self) -> Option<String> {
657         self.inner.next().map(|s| s.into_string().unwrap())
658     }
659     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
660 }
661
662 #[stable(feature = "env", since = "1.0.0")]
663 impl ExactSizeIterator for Args {
664     fn len(&self) -> usize { self.inner.len() }
665     fn is_empty(&self) -> bool { self.inner.is_empty() }
666 }
667
668 #[stable(feature = "env_iterators", since = "1.11.0")]
669 impl DoubleEndedIterator for Args {
670     fn next_back(&mut self) -> Option<String> {
671         self.inner.next_back().map(|s| s.into_string().unwrap())
672     }
673 }
674
675 #[stable(feature = "std_debug", since = "1.16.0")]
676 impl fmt::Debug for Args {
677     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
678         f.pad("Args { .. }")
679     }
680 }
681
682 #[stable(feature = "env", since = "1.0.0")]
683 impl Iterator for ArgsOs {
684     type Item = OsString;
685     fn next(&mut self) -> Option<OsString> { self.inner.next() }
686     fn size_hint(&self) -> (usize, Option<usize>) { self.inner.size_hint() }
687 }
688
689 #[stable(feature = "env", since = "1.0.0")]
690 impl ExactSizeIterator for ArgsOs {
691     fn len(&self) -> usize { self.inner.len() }
692     fn is_empty(&self) -> bool { self.inner.is_empty() }
693 }
694
695 #[stable(feature = "env_iterators", since = "1.11.0")]
696 impl DoubleEndedIterator for ArgsOs {
697     fn next_back(&mut self) -> Option<OsString> { self.inner.next_back() }
698 }
699
700 #[stable(feature = "std_debug", since = "1.16.0")]
701 impl fmt::Debug for ArgsOs {
702     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
703         f.pad("ArgsOs { .. }")
704     }
705 }
706
707 /// Constants associated with the current target
708 #[stable(feature = "env", since = "1.0.0")]
709 pub mod consts {
710     use sys::env::os;
711
712     /// A string describing the architecture of the CPU that is currently
713     /// in use.
714     ///
715     /// Some possible values:
716     ///
717     /// - x86
718     /// - x86_64
719     /// - arm
720     /// - aarch64
721     /// - mips
722     /// - mips64
723     /// - powerpc
724     /// - powerpc64
725     /// - s390x
726     /// - sparc64
727     #[stable(feature = "env", since = "1.0.0")]
728     pub const ARCH: &'static str = super::arch::ARCH;
729
730     /// The family of the operating system. Example value is `unix`.
731     ///
732     /// Some possible values:
733     ///
734     /// - unix
735     /// - windows
736     #[stable(feature = "env", since = "1.0.0")]
737     pub const FAMILY: &'static str = os::FAMILY;
738
739     /// A string describing the specific operating system in use.
740     /// Example value is `linux`.
741     ///
742     /// Some possible values:
743     ///
744     /// - linux
745     /// - macos
746     /// - ios
747     /// - freebsd
748     /// - dragonfly
749     /// - bitrig
750     /// - netbsd
751     /// - openbsd
752     /// - solaris
753     /// - android
754     /// - windows
755     #[stable(feature = "env", since = "1.0.0")]
756     pub const OS: &'static str = os::OS;
757
758     /// Specifies the filename prefix used for shared libraries on this
759     /// platform. Example value is `lib`.
760     ///
761     /// Some possible values:
762     ///
763     /// - lib
764     /// - `""` (an empty string)
765     #[stable(feature = "env", since = "1.0.0")]
766     pub const DLL_PREFIX: &'static str = os::DLL_PREFIX;
767
768     /// Specifies the filename suffix used for shared libraries on this
769     /// platform. Example value is `.so`.
770     ///
771     /// Some possible values:
772     ///
773     /// - .so
774     /// - .dylib
775     /// - .dll
776     #[stable(feature = "env", since = "1.0.0")]
777     pub const DLL_SUFFIX: &'static str = os::DLL_SUFFIX;
778
779     /// Specifies the file extension used for shared libraries on this
780     /// platform that goes after the dot. Example value is `so`.
781     ///
782     /// Some possible values:
783     ///
784     /// - so
785     /// - dylib
786     /// - dll
787     #[stable(feature = "env", since = "1.0.0")]
788     pub const DLL_EXTENSION: &'static str = os::DLL_EXTENSION;
789
790     /// Specifies the filename suffix used for executable binaries on this
791     /// platform. Example value is `.exe`.
792     ///
793     /// Some possible values:
794     ///
795     /// - .exe
796     /// - .nexe
797     /// - .pexe
798     /// - `""` (an empty string)
799     #[stable(feature = "env", since = "1.0.0")]
800     pub const EXE_SUFFIX: &'static str = os::EXE_SUFFIX;
801
802     /// Specifies the file extension, if any, used for executable binaries
803     /// on this platform. Example value is `exe`.
804     ///
805     /// Some possible values:
806     ///
807     /// - exe
808     /// - `""` (an empty string)
809     #[stable(feature = "env", since = "1.0.0")]
810     pub const EXE_EXTENSION: &'static str = os::EXE_EXTENSION;
811 }
812
813 #[cfg(target_arch = "x86")]
814 mod arch {
815     pub const ARCH: &'static str = "x86";
816 }
817
818 #[cfg(target_arch = "x86_64")]
819 mod arch {
820     pub const ARCH: &'static str = "x86_64";
821 }
822
823 #[cfg(target_arch = "arm")]
824 mod arch {
825     pub const ARCH: &'static str = "arm";
826 }
827
828 #[cfg(target_arch = "aarch64")]
829 mod arch {
830     pub const ARCH: &'static str = "aarch64";
831 }
832
833 #[cfg(target_arch = "mips")]
834 mod arch {
835     pub const ARCH: &'static str = "mips";
836 }
837
838 #[cfg(target_arch = "mips64")]
839 mod arch {
840     pub const ARCH: &'static str = "mips64";
841 }
842
843 #[cfg(target_arch = "powerpc")]
844 mod arch {
845     pub const ARCH: &'static str = "powerpc";
846 }
847
848 #[cfg(target_arch = "powerpc64")]
849 mod arch {
850     pub const ARCH: &'static str = "powerpc64";
851 }
852
853 #[cfg(target_arch = "s390x")]
854 mod arch {
855     pub const ARCH: &'static str = "s390x";
856 }
857
858 #[cfg(target_arch = "sparc64")]
859 mod arch {
860     pub const ARCH: &'static str = "sparc64";
861 }
862
863 #[cfg(target_arch = "le32")]
864 mod arch {
865     pub const ARCH: &'static str = "le32";
866 }
867
868 #[cfg(target_arch = "asmjs")]
869 mod arch {
870     pub const ARCH: &'static str = "asmjs";
871 }
872
873 #[cfg(target_arch = "wasm32")]
874 mod arch {
875     pub const ARCH: &'static str = "wasm32";
876 }
877
878 #[cfg(test)]
879 mod tests {
880     use super::*;
881
882     use iter::repeat;
883     use rand::{self, Rng};
884     use ffi::{OsString, OsStr};
885     use path::{Path, PathBuf};
886
887     fn make_rand_name() -> OsString {
888         let mut rng = rand::thread_rng();
889         let n = format!("TEST{}", rng.gen_ascii_chars().take(10)
890                                      .collect::<String>());
891         let n = OsString::from(n);
892         assert!(var_os(&n).is_none());
893         n
894     }
895
896     fn eq(a: Option<OsString>, b: Option<&str>) {
897         assert_eq!(a.as_ref().map(|s| &**s), b.map(OsStr::new).map(|s| &*s));
898     }
899
900     #[test]
901     fn test_set_var() {
902         let n = make_rand_name();
903         set_var(&n, "VALUE");
904         eq(var_os(&n), Some("VALUE"));
905     }
906
907     #[test]
908     fn test_remove_var() {
909         let n = make_rand_name();
910         set_var(&n, "VALUE");
911         remove_var(&n);
912         eq(var_os(&n), None);
913     }
914
915     #[test]
916     fn test_set_var_overwrite() {
917         let n = make_rand_name();
918         set_var(&n, "1");
919         set_var(&n, "2");
920         eq(var_os(&n), Some("2"));
921         set_var(&n, "");
922         eq(var_os(&n), Some(""));
923     }
924
925     #[test]
926     #[cfg_attr(target_os = "emscripten", ignore)]
927     fn test_var_big() {
928         let mut s = "".to_string();
929         let mut i = 0;
930         while i < 100 {
931             s.push_str("aaaaaaaaaa");
932             i += 1;
933         }
934         let n = make_rand_name();
935         set_var(&n, &s);
936         eq(var_os(&n), Some(&s));
937     }
938
939     #[test]
940     #[cfg_attr(target_os = "emscripten", ignore)]
941     fn test_self_exe_path() {
942         let path = current_exe();
943         assert!(path.is_ok());
944         let path = path.unwrap();
945
946         // Hard to test this function
947         assert!(path.is_absolute());
948     }
949
950     #[test]
951     #[cfg_attr(target_os = "emscripten", ignore)]
952     fn test_env_set_get_huge() {
953         let n = make_rand_name();
954         let s = repeat("x").take(10000).collect::<String>();
955         set_var(&n, &s);
956         eq(var_os(&n), Some(&s));
957         remove_var(&n);
958         eq(var_os(&n), None);
959     }
960
961     #[test]
962     fn test_env_set_var() {
963         let n = make_rand_name();
964
965         let mut e = vars_os();
966         set_var(&n, "VALUE");
967         assert!(!e.any(|(k, v)| {
968             &*k == &*n && &*v == "VALUE"
969         }));
970
971         assert!(vars_os().any(|(k, v)| {
972             &*k == &*n && &*v == "VALUE"
973         }));
974     }
975
976     #[test]
977     fn test() {
978         assert!((!Path::new("test-path").is_absolute()));
979
980         current_dir().unwrap();
981     }
982
983     #[test]
984     #[cfg(windows)]
985     fn split_paths_windows() {
986         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
987             split_paths(unparsed).collect::<Vec<_>>() ==
988                 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
989         }
990
991         assert!(check_parse("", &mut [""]));
992         assert!(check_parse(r#""""#, &mut [""]));
993         assert!(check_parse(";;", &mut ["", "", ""]));
994         assert!(check_parse(r"c:\", &mut [r"c:\"]));
995         assert!(check_parse(r"c:\;", &mut [r"c:\", ""]));
996         assert!(check_parse(r"c:\;c:\Program Files\",
997                             &mut [r"c:\", r"c:\Program Files\"]));
998         assert!(check_parse(r#"c:\;c:\"foo"\"#, &mut [r"c:\", r"c:\foo\"]));
999         assert!(check_parse(r#"c:\;c:\"foo;bar"\;c:\baz"#,
1000                             &mut [r"c:\", r"c:\foo;bar\", r"c:\baz"]));
1001     }
1002
1003     #[test]
1004     #[cfg(unix)]
1005     fn split_paths_unix() {
1006         fn check_parse(unparsed: &str, parsed: &[&str]) -> bool {
1007             split_paths(unparsed).collect::<Vec<_>>() ==
1008                 parsed.iter().map(|s| PathBuf::from(*s)).collect::<Vec<_>>()
1009         }
1010
1011         assert!(check_parse("", &mut [""]));
1012         assert!(check_parse("::", &mut ["", "", ""]));
1013         assert!(check_parse("/", &mut ["/"]));
1014         assert!(check_parse("/:", &mut ["/", ""]));
1015         assert!(check_parse("/:/usr/local", &mut ["/", "/usr/local"]));
1016     }
1017
1018     #[test]
1019     #[cfg(unix)]
1020     fn join_paths_unix() {
1021         fn test_eq(input: &[&str], output: &str) -> bool {
1022             &*join_paths(input.iter().cloned()).unwrap() ==
1023                 OsStr::new(output)
1024         }
1025
1026         assert!(test_eq(&[], ""));
1027         assert!(test_eq(&["/bin", "/usr/bin", "/usr/local/bin"],
1028                          "/bin:/usr/bin:/usr/local/bin"));
1029         assert!(test_eq(&["", "/bin", "", "", "/usr/bin", ""],
1030                          ":/bin:::/usr/bin:"));
1031         assert!(join_paths(["/te:st"].iter().cloned()).is_err());
1032     }
1033
1034     #[test]
1035     #[cfg(windows)]
1036     fn join_paths_windows() {
1037         fn test_eq(input: &[&str], output: &str) -> bool {
1038             &*join_paths(input.iter().cloned()).unwrap() ==
1039                 OsStr::new(output)
1040         }
1041
1042         assert!(test_eq(&[], ""));
1043         assert!(test_eq(&[r"c:\windows", r"c:\"],
1044                         r"c:\windows;c:\"));
1045         assert!(test_eq(&["", r"c:\windows", "", "", r"c:\", ""],
1046                         r";c:\windows;;;c:\;"));
1047         assert!(test_eq(&[r"c:\te;st", r"c:\"],
1048                         r#""c:\te;st";c:\"#));
1049         assert!(join_paths([r#"c:\te"st"#].iter().cloned()).is_err());
1050     }
1051     }