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