• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 use crate::io::blocking::Blocking;
2 use crate::io::{AsyncRead, ReadBuf};
3 
4 use std::io;
5 use std::pin::Pin;
6 use std::task::Context;
7 use std::task::Poll;
8 
9 cfg_io_std! {
10     /// A handle to the standard input stream of a process.
11     ///
12     /// The handle implements the [`AsyncRead`] trait, but beware that concurrent
13     /// reads of `Stdin` must be executed with care.
14     ///
15     /// This handle is best used for non-interactive uses, such as when a file
16     /// is piped into the application. For technical reasons, `stdin` is
17     /// implemented by using an ordinary blocking read on a separate thread, and
18     /// it is impossible to cancel that read. This can make shutdown of the
19     /// runtime hang until the user presses enter.
20     ///
21     /// For interactive uses, it is recommended to spawn a thread dedicated to
22     /// user input and use blocking IO directly in that thread.
23     ///
24     /// Created by the [`stdin`] function.
25     ///
26     /// [`stdin`]: fn@stdin
27     /// [`AsyncRead`]: trait@AsyncRead
28     #[derive(Debug)]
29     pub struct Stdin {
30         std: Blocking<std::io::Stdin>,
31     }
32 
33     /// Constructs a new handle to the standard input of the current process.
34     ///
35     /// This handle is best used for non-interactive uses, such as when a file
36     /// is piped into the application. For technical reasons, `stdin` is
37     /// implemented by using an ordinary blocking read on a separate thread, and
38     /// it is impossible to cancel that read. This can make shutdown of the
39     /// runtime hang until the user presses enter.
40     ///
41     /// For interactive uses, it is recommended to spawn a thread dedicated to
42     /// user input and use blocking IO directly in that thread.
43     pub fn stdin() -> Stdin {
44         let std = io::stdin();
45         Stdin {
46             std: Blocking::new(std),
47         }
48     }
49 }
50 
51 #[cfg(unix)]
52 impl std::os::unix::io::AsRawFd for Stdin {
as_raw_fd(&self) -> std::os::unix::io::RawFd53     fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
54         std::io::stdin().as_raw_fd()
55     }
56 }
57 
58 #[cfg(windows)]
59 impl std::os::windows::io::AsRawHandle for Stdin {
as_raw_handle(&self) -> std::os::windows::io::RawHandle60     fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
61         std::io::stdin().as_raw_handle()
62     }
63 }
64 
65 impl AsyncRead for Stdin {
poll_read( mut self: Pin<&mut Self>, cx: &mut Context<'_>, buf: &mut ReadBuf<'_>, ) -> Poll<io::Result<()>>66     fn poll_read(
67         mut self: Pin<&mut Self>,
68         cx: &mut Context<'_>,
69         buf: &mut ReadBuf<'_>,
70     ) -> Poll<io::Result<()>> {
71         Pin::new(&mut self.std).poll_read(cx, buf)
72     }
73 }
74