1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
//! A utility library that adds asynchronous support to file-like objects on //! Unix-like platforms. //! //! See [`File`](struct.File.html) for an example of how a file can be made //! suitable for asynchronous I/O. See [`DelimCodec`](struct.DelimCodec.html) //! for a more comprehensive example of reading the lines of a file using //! `futures::Stream`. //! //! Due to limitations of `epoll`, the library [does not support regular //! files][bug2]. Only pipes/FIFO and sockets are supported. Standard I/O is //! okay as long as they are not redirected to regular files. Any attempt to //! use a regular file will cause a permissions error (`EPERM`) when the //! `PollEvented` object gets constructed. //! //! [bug2]: https://github.com/Rufflewind/tokio-file-unix/issues/2 extern crate bytes; extern crate libc; extern crate mio; extern crate tokio_core; extern crate tokio_io; use std::io; use std::os::unix::io::{AsRawFd, RawFd}; use bytes::{BufMut, BytesMut}; use tokio_core::reactor::{Handle, PollEvented}; /// Wrapper for `std::io::Std*Lock` that can be used with `File`. /// /// For an example, see [`File`](struct.File.html). /// /// ```ignore /// impl AsRawFd + Read + Write for File<StdinLock> /// impl AsRawFd + Read + Write for File<StdoutLock> /// impl AsRawFd + Read + Write for File<StderrLock> /// ``` pub struct StdFile<F>(pub F); impl<'a> AsRawFd for StdFile<io::StdinLock<'a>> { fn as_raw_fd(&self) -> RawFd { libc::STDIN_FILENO } } impl<'a> AsRawFd for StdFile<io::StdoutLock<'a>> { fn as_raw_fd(&self) -> RawFd { libc::STDOUT_FILENO } } impl<'a> AsRawFd for StdFile<io::StderrLock<'a>> { fn as_raw_fd(&self) -> RawFd { libc::STDERR_FILENO } } impl<'a> io::Read for StdFile<io::StdinLock<'a>> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl<'a> io::Write for StdFile<io::StdoutLock<'a>> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } impl<'a> io::Write for StdFile<io::StderrLock<'a>> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } /// Used to wrap file-like objects so they can be used with /// `tokio_core::reactor::PollEvented`. /// /// Normally, you should use `File::new_nb` rather than the `File` constructor /// directly, unless the underlying file descriptor has already been set to /// nonblocking mode. Using a file that is not in nonblocking mode for /// asynchronous I/O will lead to subtle bugs. /// /// ```ignore /// impl Evented for File<std::fs::File>; /// impl Evented for File<StdFile<StdinLock>>; /// impl Evented for File<impl AsRawFd>; /// ``` /// /// ## Example: wrapping standard input /// /// ``` /// # use tokio_file_unix::*; /// # fn test() -> std::io::Result<()> { /// let stdin = std::io::stdin(); /// let file = File::new_nb(StdFile(stdin.lock()))?; /// # Ok(()) /// # } /// ``` #[derive(Debug)] pub struct File<F>(pub F); impl<F: AsRawFd> File<F> { /// Wraps a file-like object so it can be used with /// `tokio_core::reactor::PollEvented`, and also *enables nonblocking /// mode* on the underlying file descriptor. /// /// ```ignore /// fn new_nb(std::fs::File) -> Result<impl Evented + Read + Write>; /// fn new_nb(StdFile<StdinLock>) -> Result<impl Evented + Read + Write>; /// fn new_nb(impl AsRawFd) -> Result<impl Evented>; /// ``` pub fn new_nb(file: F) -> io::Result<Self> { let mut file = File(file); file.set_nonblocking(true)?; Ok(file) } /// Sets the nonblocking mode of the underlying file descriptor to either /// on (`true`) or off (`false`). If `File::new_nb` was previously used /// to construct the `File`, then nonblocking mode has already been turned /// on. /// /// Implementation detail: uses `fcntl` to set `O_NONBLOCK`. pub fn set_nonblocking(&mut self, nonblocking: bool) -> io::Result<()> { unsafe { let fd = self.as_raw_fd(); // shamelessly copied from libstd/sys/unix/fd.rs let previous = libc::fcntl(fd, libc::F_GETFL); if previous < 0 { return Err(io::Error::last_os_error()); } let new = if nonblocking { previous | libc::O_NONBLOCK } else { previous & !libc::O_NONBLOCK }; if libc::fcntl(fd, libc::F_SETFL, new) < 0 { return Err(io::Error::last_os_error()); } Ok(()) } } /// Converts into a pollable object that supports `std::io::AsyncRead` and /// `std::io::AsyncWrite`, making it suitable for `tokio_io::io::*`. /// /// If the underlying file descriptor refers to a regular file, this may /// fail with “Operation not permitted” (`EPERM`). /// /// ```ignore /// fn into_io(File<std::fs::File>, &Handle) -> Result<impl AsyncRead + AsyncWrite>; /// fn into_io(File<StdFile<StdinLock>>, &Handle) -> Result<impl AsyncRead + AsyncWrite>; /// fn into_io(File<impl AsRawFd + Read>, &Handle) -> Result<impl AsyncRead>; /// fn into_io(File<impl AsRawFd + Write>, &Handle) -> Result<impl AsyncWrite>; /// fn into_io(File<impl AsRawFd + Read + Write>, &Handle) -> Result<impl AsyncRead + AsyncWrite>; /// ``` pub fn into_io(self, handle: &Handle) -> io::Result<PollEvented<Self>> { Ok(PollEvented::new(self, handle)?) } } impl<F: AsRawFd + io::Read> File<F> { /// Converts into a pollable object that supports `std::io::Read` and /// `std::io::ReadBuf`, making it suitable for `tokio_io::io::read_*`. /// /// If the underlying file descriptor refers to a regular file, this may /// fail with “Operation not permitted” (`EPERM`). /// /// ```ignore /// fn into_reader(File<std::fs::File>, &Handle) -> Result<impl ReadBuf>; /// fn into_reader(File<StdFile<StdinLock>>, &Handle) -> Result<impl ReadBuf>; /// fn into_reader(File<impl AsRawFd + Read>, &Handle) -> Result<impl ReadBuf>; /// ``` pub fn into_reader(self, handle: &Handle) -> io::Result<io::BufReader<PollEvented<Self>>> { Ok(io::BufReader::new(self.into_io(handle)?)) } } impl<F: AsRawFd> AsRawFd for File<F> { fn as_raw_fd(&self) -> RawFd { self.0.as_raw_fd() } } impl<F: AsRawFd> mio::Evented for File<F> { fn register(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.as_raw_fd()) .register(poll, token, interest, opts) } fn reregister(&self, poll: &mio::Poll, token: mio::Token, interest: mio::Ready, opts: mio::PollOpt) -> io::Result<()> { mio::unix::EventedFd(&self.as_raw_fd()) .reregister(poll, token, interest, opts) } fn deregister(&self, poll: &mio::Poll) -> io::Result<()> { mio::unix::EventedFd(&self.as_raw_fd()) .deregister(poll) } } impl<F: io::Read> io::Read for File<F> { fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> { self.0.read(buf) } } impl<F: io::Write> io::Write for File<F> { fn write(&mut self, buf: &[u8]) -> io::Result<usize> { self.0.write(buf) } fn flush(&mut self) -> io::Result<()> { self.0.flush() } } /// A `Codec` that splits the stream into frames divided by a given delimiter /// byte. All frames except possibly the last one contain the delimiter byte /// as the last element. /// /// ```ignore /// impl Codec for DelimCodec<u8>; /// impl Codec for DelimCodec<Newline>; /// impl Codec for DelimCodec<impl Into<u8> + Clone>; /// ``` /// /// ## Example: read stdin line by line /// /// ``` /// extern crate futures; /// extern crate tokio_core; /// extern crate tokio_io; /// # extern crate tokio_file_unix; /// /// use futures::Stream; /// use tokio_io::{AsyncRead, AsyncWrite}; /// use tokio_io::codec::FramedRead; /// # use tokio_file_unix::*; /// # /// # fn main() { /// # fn test() -> std::io::Result<()> { /// /// // initialize the event loop /// let mut core = tokio_core::reactor::Core::new()?; /// let handle = core.handle(); /// /// // get the standard input as a file /// let stdin = std::io::stdin(); /// let io = File::new_nb(StdFile(stdin.lock()))?.into_io(&handle)?; /// /// // turn it into a stream of lines, decoded as UTF-8 /// let line_stream = FramedRead::new(io, DelimCodec(Newline)).and_then(|line| { /// String::from_utf8(line).map_err(|_| { /// std::io::Error::from(std::io::ErrorKind::InvalidData) /// }) /// }); /// /// // specify how each line is to be processed /// let future = line_stream.for_each(|line| { /// println!("Got: {}", line); /// Ok(()) /// }); /// /// // start the event loop /// core.run(future)?; /// /// # Ok(()) /// # } /// # } /// ``` #[derive(Debug, Clone, Copy)] pub struct DelimCodec<D>(pub D); impl<D: Into<u8> + Clone> tokio_io::codec::Decoder for DelimCodec<D> { type Item = Vec<u8>; type Error = io::Error; fn decode(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { Ok(buf.as_ref().iter().position(|b| *b == self.0.clone().into()) .map(|n| buf.split_to(n + 1).as_ref().to_vec())) } fn decode_eof(&mut self, buf: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> { let buf = buf.split_off(0); if buf.is_empty() { Ok(None) } else { Ok(Some(buf.as_ref().to_vec())) } } } impl<D: Into<u8> + Clone> tokio_io::codec::Encoder for DelimCodec<D> { type Item = Vec<u8>; type Error = io::Error; fn encode(&mut self, msg: Self::Item, buf: &mut BytesMut) -> Result<(), Self::Error> { buf.extend(msg); buf.put_u8(self.0.clone().into()); Ok(()) } } /// Represents a newline that can be used with `DelimCodec`. /// /// For an example, see [`File`](struct.File.html). /// /// ```ignore /// impl Into<u8> for Newline; /// ``` #[derive(Debug, Clone, Copy)] pub struct Newline; impl From<Newline> for u8 { fn from(_: Newline) -> Self { b'\n' } }