Implement io::native::stdio

This commit is contained in:
Alex Crichton 2013-10-06 13:21:42 -07:00
parent b509f7905a
commit edf4c16997

View file

@ -0,0 +1,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() }
}