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