]> git.lizzy.rs Git - rust.git/blob - tests/ui-fulldeps/switch-stdout.rs
Rollup merge of #106701 - ibraheemdev:sync-sender-spin, r=Amanieu
[rust.git] / tests / ui-fulldeps / switch-stdout.rs
1 // run-pass
2
3 use std::env;
4 use std::fs::File;
5 use std::io::{Read, Write};
6 use std::path::PathBuf;
7
8 #[cfg(unix)]
9 fn switch_stdout_to(file: File) {
10     use std::os::unix::prelude::*;
11
12     extern "C" {
13         fn dup2(old: i32, new: i32) -> i32;
14     }
15
16     unsafe {
17         assert_eq!(dup2(file.as_raw_fd(), 1), 1);
18     }
19 }
20
21 #[cfg(windows)]
22 fn switch_stdout_to(file: File) {
23     use std::os::windows::prelude::*;
24
25     extern "system" {
26         fn SetStdHandle(nStdHandle: u32, handle: *mut u8) -> i32;
27     }
28
29     const STD_OUTPUT_HANDLE: u32 = (-11i32) as u32;
30
31     unsafe {
32         let rc = SetStdHandle(STD_OUTPUT_HANDLE, file.into_raw_handle() as *mut _);
33         assert!(rc != 0);
34     }
35 }
36
37 fn main() {
38     let path = PathBuf::from(env::var_os("RUST_TEST_TMPDIR").unwrap());
39     let path = path.join("switch-stdout-output");
40     let f = File::create(&path).unwrap();
41
42     println!("foo");
43     std::io::stdout().flush().unwrap();
44     switch_stdout_to(f);
45     println!("bar");
46     std::io::stdout().flush().unwrap();
47
48     let mut contents = String::new();
49     File::open(&path).unwrap().read_to_string(&mut contents).unwrap();
50     assert_eq!(contents, "bar\n");
51 }