]> git.lizzy.rs Git - rust.git/blob - src/libstd/rt/io/pipe.rs
auto merge of #8848 : ILyoan/rust/mk_libuv, r=cmr
[rust.git] / src / libstd / rt / io / pipe.rs
1 // Copyright 2013 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 //! Synchronous, in-memory pipes.
12 //!
13 //! Currently these aren't particularly useful, there only exists bindings
14 //! enough so that pipes can be created to child processes.
15
16 use prelude::*;
17 use super::{Reader, Writer};
18 use rt::io::{io_error, read_error, EndOfFile};
19 use rt::local::Local;
20 use rt::rtio::{RtioPipeObject, RtioStream, IoFactoryObject, IoFactory};
21 use rt::uv::pipe;
22
23 pub struct PipeStream(~RtioPipeObject);
24
25 impl PipeStream {
26     /// Creates a new pipe initialized, but not bound to any particular
27     /// source/destination
28     pub fn new() -> Option<PipeStream> {
29         let pipe = unsafe {
30             let io: *mut IoFactoryObject = Local::unsafe_borrow();
31             (*io).pipe_init(false)
32         };
33         match pipe {
34             Ok(p) => Some(PipeStream(p)),
35             Err(ioerr) => {
36                 io_error::cond.raise(ioerr);
37                 None
38             }
39         }
40     }
41
42     /// Extracts the underlying libuv pipe to be bound to another source.
43     pub fn uv_pipe(&self) -> pipe::Pipe {
44         // Did someone say multiple layers of indirection?
45         (**self).uv_pipe()
46     }
47 }
48
49 impl Reader for PipeStream {
50     fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
51         match (***self).read(buf) {
52             Ok(read) => Some(read),
53             Err(ioerr) => {
54                 // EOF is indicated by returning None
55                 if ioerr.kind != EndOfFile {
56                     read_error::cond.raise(ioerr);
57                 }
58                 return None;
59             }
60         }
61     }
62
63     fn eof(&mut self) -> bool { fail!() }
64 }
65
66 impl Writer for PipeStream {
67     fn write(&mut self, buf: &[u8]) {
68         match (***self).write(buf) {
69             Ok(_) => (),
70             Err(ioerr) => {
71                 io_error::cond.raise(ioerr);
72             }
73         }
74     }
75
76     fn flush(&mut self) { fail!() }
77 }