Skip to content

Commit 6dc0624

Browse files
committed
Improve docs and refactore std::os.
1 parent ea41101 commit 6dc0624

File tree

1 file changed

+140
-76
lines changed

1 file changed

+140
-76
lines changed

src/libstd/os.rs

Lines changed: 140 additions & 76 deletions
Original file line numberDiff line numberDiff line change
@@ -73,8 +73,10 @@ static BUF_BYTES : uint = 2048u;
7373
/// # Example
7474
///
7575
/// ```rust
76+
/// use std::os;
77+
///
7678
/// // We assume that we are in a valid directory like "/home".
77-
/// let current_working_directory = std::os::getcwd();
79+
/// let current_working_directory = os::getcwd();
7880
/// println!("The current directory is {}", current_working_directory.display());
7981
/// // /home
8082
/// ```
@@ -104,8 +106,10 @@ pub fn getcwd() -> Path {
104106
/// # Example
105107
///
106108
/// ```rust
109+
/// use std::os;
110+
///
107111
/// // We assume that we are in a valid directory like "C:\\Windows".
108-
/// let current_working_directory = std::os::getcwd();
112+
/// let current_working_directory = os::getcwd();
109113
/// println!("The current directory is {}", current_working_directory.display());
110114
/// // C:\\Windows
111115
/// ```
@@ -188,17 +192,19 @@ fn with_env_lock<T>(f: || -> T) -> T {
188192
}
189193
}
190194

191-
/// Returns a vector of (variable, value) pairs as a Vec<(String, String)>,
192-
/// for all the environment variables of the current process.
195+
/// Returns a vector of (variable, value) pairs, for all the environment
196+
/// variables of the current process.
193197
///
194198
/// Invalid UTF-8 bytes are replaced with \uFFFD. See `str::from_utf8_lossy()`
195199
/// for details.
196200
///
197201
/// # Example
198202
///
199203
/// ```rust
200-
/// // We will iterate through the references to the element returned by std::os::env();
201-
/// for &(ref key, ref value) in std::os::env().iter() {
204+
/// use std::os;
205+
///
206+
/// // We will iterate through the references to the element returned by os::env();
207+
/// for &(ref key, ref value) in os::env().iter() {
202208
/// println!("'{}': '{}'", key, value );
203209
/// }
204210
/// ```
@@ -306,8 +312,10 @@ pub fn env_as_bytes() -> Vec<(Vec<u8>,Vec<u8>)> {
306312
/// # Example
307313
///
308314
/// ```rust
315+
/// use std::os;
316+
///
309317
/// let key = "HOME";
310-
/// match std::os::getenv(key) {
318+
/// match os::getenv(key) {
311319
/// Some(val) => println!("{}: {}", key, val),
312320
/// None => println!("{} is not defined in the environment.", key)
313321
/// }
@@ -361,45 +369,49 @@ pub fn getenv_as_bytes(n: &str) -> Option<Vec<u8>> {
361369
getenv(n).map(|s| s.into_bytes())
362370
}
363371

364-
365-
#[cfg(unix)]
366372
/// Sets the environment variable `n` to the value `v` for the currently running
367-
/// process
373+
/// process.
368374
///
369-
/// # Failure
375+
/// # Example
370376
///
371-
/// Fails if `n` or `v` have any interior NULs.
377+
/// ```rust
378+
/// use std::os;
379+
///
380+
/// let key = "KEY";
381+
/// os::setenv(key, "VALUE");
382+
/// match os::getenv(key) {
383+
/// Some(ref val) => println!("{}: {}", key, val),
384+
/// None => println!("{} is not defined in the environment.", key)
385+
/// }
386+
/// ```
372387
pub fn setenv(n: &str, v: &str) {
373-
unsafe {
374-
with_env_lock(|| {
375-
n.with_c_str(|nbuf| {
376-
v.with_c_str(|vbuf| {
377-
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
388+
#[cfg(unix)]
389+
fn _setenv(n: &str, v: &str) {
390+
unsafe {
391+
with_env_lock(|| {
392+
n.with_c_str(|nbuf| {
393+
v.with_c_str(|vbuf| {
394+
libc::funcs::posix01::unistd::setenv(nbuf, vbuf, 1);
395+
})
378396
})
379397
})
380-
})
398+
}
381399
}
382-
}
383-
384400

385-
#[cfg(windows)]
386-
/// Sets the environment variable `n` to the value `v` for the currently running
387-
/// process
388-
pub fn setenv(n: &str, v: &str) {
389-
let n = n.to_utf16().append_one(0);
390-
let v = v.to_utf16().append_one(0);
391-
unsafe {
392-
with_env_lock(|| {
393-
libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
394-
})
401+
#[cfg(windows)]
402+
fn _setenv(n: &str, v: &str) {
403+
let n = n.to_utf16().append_one(0);
404+
let v = v.to_utf16().append_one(0);
405+
unsafe {
406+
with_env_lock(|| {
407+
libc::SetEnvironmentVariableW(n.as_ptr(), v.as_ptr());
408+
})
409+
}
395410
}
411+
_setenv(n, v)
396412
}
397413

398-
/// Remove a variable from the environment entirely
399-
///
400-
/// # Failure
401-
///
402-
/// Fails (on unix) if `n` has any interior NULs.
414+
/// Remove a variable from the environment entirely.
403415
pub fn unsetenv(n: &str) {
404416
#[cfg(unix)]
405417
fn _unsetenv(n: &str) {
@@ -411,6 +423,7 @@ pub fn unsetenv(n: &str) {
411423
})
412424
}
413425
}
426+
414427
#[cfg(windows)]
415428
fn _unsetenv(n: &str) {
416429
let n = n.to_utf16().append_one(0);
@@ -420,13 +433,28 @@ pub fn unsetenv(n: &str) {
420433
})
421434
}
422435
}
423-
424436
_unsetenv(n);
425437
}
426438

427439
#[cfg(unix)]
428440
/// Parse a string or vector according to the platform's conventions
429-
/// for the `PATH` environment variable. Drops empty paths.
441+
/// for the `PATH` environment variable and return a Vec<Path>.
442+
/// Drops empty paths.
443+
///
444+
/// # Example
445+
/// ```rust
446+
/// use std::os;
447+
///
448+
/// let key = "PATH";
449+
/// match os::getenv(key) {
450+
/// Some(paths) => {
451+
/// for path in os::split_paths(paths).iter() {
452+
/// println!("'{}'", path.display());
453+
/// }
454+
/// }
455+
/// None => println!("{} is not defined in the environnement.", key)
456+
/// }
457+
/// ```
430458
pub fn split_paths<T: BytesContainer>(unparsed: T) -> Vec<Path> {
431459
unparsed.container_as_bytes()
432460
.split(|b| *b == ':' as u8)
@@ -491,7 +519,7 @@ pub struct Pipe {
491519
pub out: c_int,
492520
}
493521

494-
/// Creates a new low-level OS in-memory pipe.
522+
/// Creates a new low-level OS in-memory pipe represented as a Pipe struct.
495523
#[cfg(unix)]
496524
pub fn pipe() -> Pipe {
497525
unsafe {
@@ -502,7 +530,7 @@ pub fn pipe() -> Pipe {
502530
}
503531
}
504532

505-
/// Creates a new low-level OS in-memory pipe.
533+
/// Creates a new low-level OS in-memory pipe represented as a Pipe struct.
506534
#[cfg(windows)]
507535
pub fn pipe() -> Pipe {
508536
unsafe {
@@ -522,13 +550,25 @@ pub fn pipe() -> Pipe {
522550
}
523551
}
524552

525-
/// Returns the proper dll filename for the given basename of a file.
553+
/// Returns the proper dll filename for the given basename of a file
554+
/// as a String.
526555
pub fn dll_filename(base: &str) -> String {
527556
format!("{}{}{}", consts::DLL_PREFIX, base, consts::DLL_SUFFIX)
528557
}
529558

530-
/// Optionally returns the filesystem path of the current executable which is
531-
/// running. If any failure occurs, None is returned.
559+
/// Optionally returns the filesystem path to the current executable which is
560+
/// running but with the executable name.
561+
///
562+
/// # Examples
563+
///
564+
/// ```rust
565+
/// use std::os;
566+
///
567+
/// match os::self_exe_name() {
568+
/// Some(exe_path) => println!("Path of this executable is: {}", exe_path.display()),
569+
/// None => println!("Unable to get the path of this executable!")
570+
/// };
571+
/// ```
532572
pub fn self_exe_name() -> Option<Path> {
533573

534574
#[cfg(target_os = "freebsd")]
@@ -598,47 +638,71 @@ pub fn self_exe_name() -> Option<Path> {
598638
}
599639

600640
/// Optionally returns the filesystem path to the current executable which is
601-
/// running. Like self_exe_name() but without the binary's name.
602-
/// If any failure occurs, None is returned.
641+
/// running.
642+
///
643+
/// Like self_exe_name() but without the binary's name.
644+
///
645+
/// # Example
646+
///
647+
/// ```rust
648+
/// use std::os;
649+
///
650+
/// match os::self_exe_path() {
651+
/// Some(exe_path) => println!("Executable's Path is: {}", exe_path.display()),
652+
/// None => println!("Impossible to fetch the path of this executable.")
653+
/// };
654+
/// ```
603655
pub fn self_exe_path() -> Option<Path> {
604656
self_exe_name().map(|mut p| { p.pop(); p })
605657
}
606658

607-
/**
608-
* Returns the path to the user's home directory, if known.
609-
*
610-
* On Unix, returns the value of the 'HOME' environment variable if it is set
611-
* and not equal to the empty string.
612-
*
613-
* On Windows, returns the value of the 'HOME' environment variable if it is
614-
* set and not equal to the empty string. Otherwise, returns the value of the
615-
* 'USERPROFILE' environment variable if it is set and not equal to the empty
616-
* string.
617-
*
618-
* Otherwise, homedir returns option::none.
619-
*/
659+
/// Optionally returns the path to the current user's home directory if known.
660+
///
661+
/// # Unix
662+
///
663+
/// Returns the value of the 'HOME' environment variable if it is set
664+
/// and not equal to the empty string.
665+
///
666+
/// # Windows
667+
///
668+
/// Returns the value of the 'HOME' environment variable if it is
669+
/// set and not equal to the empty string. Otherwise, returns the value of the
670+
/// 'USERPROFILE' environment variable if it is set and not equal to the empty
671+
/// string.
672+
///
673+
/// # Example
674+
///
675+
/// ```rust
676+
/// use std::os;
677+
///
678+
/// match os::homedir() {
679+
/// Some(ref p) => println!("{}", p.display()),
680+
/// None => println!("Impossible to get your home dir!")
681+
/// }
682+
/// ```
620683
pub fn homedir() -> Option<Path> {
621-
// FIXME (#7188): getenv needs a Vec<u8> variant
622-
return match getenv("HOME") {
623-
Some(ref p) if !p.is_empty() => Path::new_opt(p.as_slice()),
624-
_ => secondary()
625-
};
626-
684+
#[inline]
627685
#[cfg(unix)]
628-
fn secondary() -> Option<Path> {
629-
None
686+
fn _homedir() -> Option<Path> {
687+
aux_homedir("HOME")
630688
}
631689

690+
#[inline]
632691
#[cfg(windows)]
633-
fn secondary() -> Option<Path> {
634-
getenv("USERPROFILE").and_then(|p| {
635-
if !p.is_empty() {
636-
Path::new_opt(p)
637-
} else {
638-
None
639-
}
640-
})
692+
fn _homedir() -> Option<Path> {
693+
aux_homedir("HOME").or(aux_homedir("USERPROFILE"))
694+
}
695+
696+
#[inline]
697+
fn aux_homedir(home_name: &str) -> Option<Path> {
698+
match getenv_as_bytes(home_name) {
699+
Some(p) => {
700+
if p.is_empty() { None } else { Path::new_opt(p) }
701+
},
702+
_ => None
703+
}
641704
}
705+
_homedir()
642706
}
643707

644708
/**
@@ -1732,7 +1796,7 @@ mod tests {
17321796
assert!(os::homedir().is_none());
17331797

17341798
for s in oldhome.iter() {
1735-
setenv("HOME", s.as_slice())
1799+
setenv("HOME", s.as_slice());
17361800
}
17371801
}
17381802

@@ -1761,10 +1825,10 @@ mod tests {
17611825
assert!(os::homedir() == Some(Path::new("/home/MountainView")));
17621826

17631827
for s in oldhome.iter() {
1764-
setenv("HOME", s.as_slice())
1828+
setenv("HOME", s.as_slice());
17651829
}
17661830
for s in olduserprofile.iter() {
1767-
setenv("USERPROFILE", s.as_slice())
1831+
setenv("USERPROFILE", s.as_slice());
17681832
}
17691833
}
17701834

0 commit comments

Comments
 (0)