]> git.lizzy.rs Git - rust.git/blob - src/test/run-pass-fulldeps/switch-stdout.rs
Auto merge of #54919 - alexcrichton:update-cargo, r=Mark-Simulacrum
[rust.git] / src / test / run-pass-fulldeps / switch-stdout.rs
1 // Copyright 2012-2014 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 use std::env;
12 use std::fs::File;
13 use std::io::{Read, Write};
14 use std::path::PathBuf;
15
16 #[cfg(unix)]
17 fn switch_stdout_to(file: File) {
18     use std::os::unix::prelude::*;
19
20     extern {
21         fn dup2(old: i32, new: i32) -> i32;
22     }
23
24     unsafe {
25         assert_eq!(dup2(file.as_raw_fd(), 1), 1);
26     }
27 }
28
29 #[cfg(windows)]
30 fn switch_stdout_to(file: File) {
31     use std::os::windows::prelude::*;
32
33     extern "system" {
34         fn SetStdHandle(nStdHandle: u32, handle: *mut u8) -> i32;
35     }
36
37     const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
38
39     unsafe {
40         let rc = SetStdHandle(STD_OUTPUT_HANDLE,
41                               file.into_raw_handle() as *mut _);
42         assert!(rc != 0);
43     }
44 }
45
46 fn main() {
47     let path = PathBuf::from(env::var_os("RUST_TEST_TMPDIR").unwrap());
48     let path = path.join("switch-stdout-output");
49     let f = File::create(&path).unwrap();
50
51     println!("foo");
52     std::io::stdout().flush().unwrap();
53     switch_stdout_to(f);
54     println!("bar");
55     std::io::stdout().flush().unwrap();
56
57     let mut contents = String::new();
58     File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
59     assert_eq!(contents, "bar\n");
60 }