(index<- ) ./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::{RtioPipe, RtioPipeObject, IoFactoryObject, IoFactory};
21 use rt::rtio::RtioUnboundPipeObject;
22
23 pub struct PipeStream {
24 priv obj: RtioPipeObject
25 }
26
27 // This should not be a newtype, but rt::uv::process::set_stdio needs to reach
28 // into the internals of this :(
29 pub struct UnboundPipeStream(~RtioUnboundPipeObject);
30
31 impl PipeStream {
32 /// Creates a new pipe initialized, but not bound to any particular
33 /// source/destination
34 pub fn new() -> Option<UnboundPipeStream> {
35 let pipe = unsafe {
36 let io: *mut IoFactoryObject = Local::unsafe_borrow();
37 (*io).pipe_init(false)
38 };
39 match pipe {
40 Ok(p) => Some(UnboundPipeStream(p)),
41 Err(ioerr) => {
42 io_error::cond.raise(ioerr);
43 None
44 }
45 }
46 }
47
48 pub fn bind(inner: RtioPipeObject) -> PipeStream {
49 PipeStream { obj: inner }
50 }
51 }
52
53 impl Reader for PipeStream {
54 fn read(&mut self, buf: &mut [u8]) -> Option<uint> {
55 match self.obj.read(buf) {
56 Ok(read) => Some(read),
57 Err(ioerr) => {
58 // EOF is indicated by returning None
59 if ioerr.kind != EndOfFile {
60 read_error::cond.raise(ioerr);
61 }
62 return None;
63 }
64 }
65 }
66
67 fn eof(&mut self) -> bool { fail2!() }
68 }
69
70 impl Writer for PipeStream {
71 fn write(&mut self, buf: &[u8]) {
72 match self.obj.write(buf) {
73 Ok(_) => (),
74 Err(ioerr) => {
75 io_error::cond.raise(ioerr);
76 }
77 }
78 }
79
80 fn flush(&mut self) { fail2!() }
81 }