about summary refs log tree commit diff
path: root/src/libstd/rt/io/native/stdio.rs
blob: 5661725d77baa40f6d8247a2c015a3d9c800d500 (plain)
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
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use libc;
use option::Option;
use rt::io::{Reader, Writer};
use super::file;

/// Creates a new handle to the stdin of this process
pub fn stdin() -> StdIn { StdIn::new() }
/// Creates a new handle to the stdout of this process
pub fn stdout() -> StdOut { StdOut::new(libc::STDOUT_FILENO) }
/// Creates a new handle to the stderr of this process
pub fn stderr() -> StdOut { StdOut::new(libc::STDERR_FILENO) }

pub fn print(s: &str) {
    stdout().write(s.as_bytes())
}

pub fn println(s: &str) {
    let mut out = stdout();
    out.write(s.as_bytes());
    out.write(['\n' as u8]);
}

pub struct StdIn {
    priv fd: file::FileDesc
}

impl StdIn {
    /// Duplicates the stdin file descriptor, returning an io::Reader
    #[fixed_stack_segment] #[inline(never)]
    pub fn new() -> StdIn {
        let fd = unsafe { libc::dup(libc::STDIN_FILENO) };
        StdIn { fd: file::FileDesc::new(fd) }
    }
}

impl Reader for StdIn {
    fn read(&mut self, buf: &mut [u8]) -> Option<uint> { self.fd.read(buf) }
    fn eof(&mut self) -> bool { self.fd.eof() }
}

pub struct StdOut {
    priv fd: file::FileDesc
}

impl StdOut {
    /// Duplicates the specified file descriptor, returning an io::Writer
    #[fixed_stack_segment] #[inline(never)]
    pub fn new(fd: file::fd_t) -> StdOut {
        let fd = unsafe { libc::dup(fd) };
        StdOut { fd: file::FileDesc::new(fd) }
    }
}

impl Writer for StdOut {
    fn write(&mut self, buf: &[u8]) { self.fd.write(buf) }
    fn flush(&mut self) { self.fd.flush() }
}