1 // Copyright 2012 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.
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.
13 The `io` module contains basic input and output routines.
17 ## `Reader` and `Writer` traits
19 These traits define the minimal set of methods that anything that can do
20 input and output should implement.
22 ## `ReaderUtil` and `WriterUtil` traits
24 Richer methods that allow you to do more. `Reader` only lets you read a certain
25 number of bytes into a buffer, while `ReaderUtil` allows you to read a whole
28 Generally, these richer methods are probably the ones you want to actually
29 use in day-to-day Rust.
31 Furthermore, because there is an implementation of `ReaderUtil` for
32 `<T: Reader>`, when your input or output code implements `Reader`, you get
33 all of these methods for free.
35 ## `print` and `println`
37 These very useful functions are defined here. You generally don't need to
38 import them, though, as the prelude already does.
40 ## `stdin`, `stdout`, and `stderr`
42 These functions return references to the classic three file descriptors. They
43 implement `Reader` and `Writer`, where appropriate.
47 #[allow(missing_doc)];
52 use container::Container;
54 use iterator::Iterator;
55 use libc::consts::os::posix88::*;
56 use libc::{c_int, c_long, c_void, size_t, ssize_t};
60 use option::{Some, None};
64 use result::{Result, Ok, Err};
65 use str::{StrSlice, OwnedStr};
69 use vec::{MutableVector, ImmutableVector, OwnedVector, OwnedCopyableVector, CopyableVector};
72 #[allow(non_camel_case_types)] // not sure what to do about this
73 pub type fd_t = c_int;
79 #[link_name = "rustrt"]
81 pub fn rust_get_stdin() -> *libc::FILE;
82 pub fn rust_get_stdout() -> *libc::FILE;
83 pub fn rust_get_stderr() -> *libc::FILE;
89 // FIXME (#2004): This is all buffered. We might need an unbuffered variant
92 * The SeekStyle enum describes the relationship between the position
93 * we'd like to seek to from our current position. It's used as an argument
94 * to the `seek` method defined on the `Reader` trait.
96 * There are three seek styles:
98 * 1. `SeekSet` means that the new position should become our position.
99 * 2. `SeekCur` means that we should seek from the current position.
100 * 3. `SeekEnd` means that we should seek from the end.
106 pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, }
110 * The core Reader trait. All readers must implement this trait.
117 // FIXME (#2004): Seekable really should be orthogonal.
119 // FIXME (#2982): This should probably return an error.
121 * Reads bytes and puts them into `bytes`, advancing the cursor. Returns the
122 * number of bytes read.
124 * The number of bytes to be read is `len` or the end of the file,
125 * whichever comes first.
127 * The buffer must be at least `len` bytes long.
129 * `read` is conceptually similar to C's `fread` function.
135 fn read(&self, bytes: &mut [u8], len: uint) -> uint;
138 * Reads a single byte, advancing the cursor.
140 * In the case of an EOF or an error, returns a negative value.
142 * `read_byte` is conceptually similar to C's `getc` function.
148 fn read_byte(&self) -> int;
151 * Returns a boolean value: are we currently at EOF?
153 * Note that stream position may be already at the end-of-file point,
154 * but `eof` returns false until an attempt to read at that position.
156 * `eof` is conceptually similar to C's `feof` function.
162 fn eof(&self) -> bool;
165 * Seek to a given `position` in the stream.
167 * Takes an optional SeekStyle, which affects how we seek from the
168 * position. See `SeekStyle` docs for more details.
170 * `seek` is conceptually similar to C's `fseek` function.
176 fn seek(&self, position: int, style: SeekStyle);
179 * Returns the current position within the stream.
181 * `tell` is conceptually similar to C's `ftell` function.
187 fn tell(&self) -> uint;
190 impl Reader for @Reader {
191 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
192 self.read(bytes, len)
194 fn read_byte(&self) -> int {
197 fn eof(&self) -> bool {
200 fn seek(&self, position: int, style: SeekStyle) {
201 self.seek(position, style)
203 fn tell(&self) -> uint {
209 * The `ReaderUtil` trait is a home for many of the utility functions
210 * a particular Reader should implement.
212 * The default `Reader` trait is focused entirely on bytes. `ReaderUtil` is based
213 * on higher-level concepts like 'chars' and 'lines.'
219 pub trait ReaderUtil {
222 * Reads `len` number of bytes, and gives you a new vector back.
228 fn read_bytes(&self, len: uint) -> ~[u8];
231 * Reads up until a specific byte is seen or EOF.
233 * The `include` parameter specifies if the character should be included
234 * in the returned string.
240 fn read_until(&self, c: u8, include: bool) -> ~str;
243 * Reads up until the first '\n' or EOF.
245 * The '\n' is not included in the result.
251 fn read_line(&self) -> ~str;
256 * Assumes that those chars are UTF-8 encoded.
258 * The '\n' is not included in the result.
264 fn read_chars(&self, n: uint) -> ~[char];
267 * Reads a single UTF-8 encoded char.
273 fn read_char(&self) -> char;
276 * Reads up until the first null byte or EOF.
278 * The null byte is not returned.
284 fn read_c_str(&self) -> ~str;
287 * Reads all remaining data in the stream.
293 fn read_whole_stream(&self) -> ~[u8];
296 * Iterate over every byte until EOF or the iterator breaks.
302 fn each_byte(&self, it: &fn(int) -> bool) -> bool;
305 * Iterate over every char until EOF or the iterator breaks.
311 fn each_char(&self, it: &fn(char) -> bool) -> bool;
314 * Iterate over every line until EOF or the iterator breaks.
320 fn each_line(&self, it: &fn(&str) -> bool) -> bool;
323 * Reads all of the lines in the stream.
325 * Returns a vector of those lines.
331 fn read_lines(&self) -> ~[~str];
334 * Reads `n` little-endian unsigned integer bytes.
336 * `n` must be between 1 and 8, inclusive.
342 fn read_le_uint_n(&self, nbytes: uint) -> u64;
345 * Reads `n` little-endian signed integer bytes.
347 * `n` must be between 1 and 8, inclusive.
353 fn read_le_int_n(&self, nbytes: uint) -> i64;
356 * Reads `n` big-endian unsigned integer bytes.
358 * `n` must be between 1 and 8, inclusive.
364 fn read_be_uint_n(&self, nbytes: uint) -> u64;
367 * Reads `n` big-endian signed integer bytes.
369 * `n` must be between 1 and 8, inclusive.
375 fn read_be_int_n(&self, nbytes: uint) -> i64;
378 * Reads a little-endian unsigned integer.
380 * The number of bytes returned is system-dependant.
386 fn read_le_uint(&self) -> uint;
389 * Reads a little-endian integer.
391 * The number of bytes returned is system-dependant.
397 fn read_le_int(&self) -> int;
400 * Reads a big-endian unsigned integer.
402 * The number of bytes returned is system-dependant.
408 fn read_be_uint(&self) -> uint;
411 * Reads a big-endian integer.
413 * The number of bytes returned is system-dependant.
419 fn read_be_int(&self) -> int;
422 * Reads a big-endian `u64`.
424 * `u64`s are 8 bytes long.
430 fn read_be_u64(&self) -> u64;
433 * Reads a big-endian `u32`.
435 * `u32`s are 4 bytes long.
441 fn read_be_u32(&self) -> u32;
444 * Reads a big-endian `u16`.
446 * `u16`s are 2 bytes long.
452 fn read_be_u16(&self) -> u16;
455 * Reads a big-endian `i64`.
457 * `i64`s are 8 bytes long.
463 fn read_be_i64(&self) -> i64;
466 * Reads a big-endian `i32`.
468 * `i32`s are 4 bytes long.
474 fn read_be_i32(&self) -> i32;
477 * Reads a big-endian `i16`.
479 * `i16`s are 2 bytes long.
485 fn read_be_i16(&self) -> i16;
488 * Reads a big-endian `f64`.
490 * `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
496 fn read_be_f64(&self) -> f64;
499 * Reads a big-endian `f32`.
501 * `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
507 fn read_be_f32(&self) -> f32;
510 * Reads a little-endian `u64`.
512 * `u64`s are 8 bytes long.
518 fn read_le_u64(&self) -> u64;
521 * Reads a little-endian `u32`.
523 * `u32`s are 4 bytes long.
529 fn read_le_u32(&self) -> u32;
532 * Reads a little-endian `u16`.
534 * `u16`s are 2 bytes long.
540 fn read_le_u16(&self) -> u16;
543 * Reads a little-endian `i64`.
545 * `i64`s are 8 bytes long.
551 fn read_le_i64(&self) -> i64;
554 * Reads a little-endian `i32`.
556 * `i32`s are 4 bytes long.
562 fn read_le_i32(&self) -> i32;
565 * Reads a little-endian `i16`.
567 * `i16`s are 2 bytes long.
573 fn read_le_i16(&self) -> i16;
576 * Reads a little-endian `f64`.
578 * `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
584 fn read_le_f64(&self) -> f64;
587 * Reads a little-endian `f32`.
589 * `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
595 fn read_le_f32(&self) -> f32;
606 fn read_u8(&self) -> u8;
617 fn read_i8(&self) -> i8;
620 impl<T:Reader> ReaderUtil for T {
622 fn read_bytes(&self,len: uint) -> ~[u8] {
623 let mut bytes = vec::with_capacity(len);
624 unsafe { vec::raw::set_len(&mut bytes, len); }
626 let count = self.read(bytes, len);
628 unsafe { vec::raw::set_len(&mut bytes, count); }
632 fn read_until(&self, c: u8, include: bool) -> ~str {
635 let ch = self.read_byte();
636 if ch == -1 || ch == c as int {
637 if include && ch == c as int {
638 bytes.push(ch as u8);
642 bytes.push(ch as u8);
644 str::from_bytes(bytes)
647 fn read_line(&self) -> ~str {
648 self.read_until('\n' as u8, false)
651 fn read_chars(&self, n: uint) -> ~[char] {
652 // returns the (consumed offset, n_req), appends characters to &chars
653 fn chars_from_bytes<T:Reader>(bytes: &~[u8], chars: &mut ~[char])
656 let bytes_len = bytes.len();
657 while i < bytes_len {
659 let w = str::utf8_char_width(b0);
664 chars.push(b0 as char);
667 // can't satisfy this char with the existing data
669 return (i - 1, end - bytes_len);
673 let next = bytes[i] as int;
675 assert!((next > -1));
676 assert_eq!(next & 192, 128);
678 val += (next & 63) as uint;
680 // See str::StrSlice::char_at
681 val += ((b0 << ((w + 1) as u8)) as uint)
682 << (w - 1) * 6 - w - 1u;
683 chars.push(val as char);
689 // might need more bytes, but reading n will never over-read
692 let data = self.read_bytes(nbread);
694 // eof - FIXME (#2004): should we do something if
695 // we're split in a unicode char?
698 bytes.push_all(data);
699 let (offset, nbreq) = chars_from_bytes::<T>(&bytes, &mut chars);
700 let ncreq = n - chars.len();
701 // again we either know we need a certain number of bytes
702 // to complete a character, or we make sure we don't
703 // over-read by reading 1-byte per char needed
704 nbread = if ncreq > nbreq { ncreq } else { nbreq };
706 bytes = bytes.slice(offset, bytes.len()).to_owned();
712 fn read_char(&self) -> char {
713 let c = self.read_chars(1);
715 return -1 as char; // FIXME will this stay valid? // #2004
717 assert_eq!(c.len(), 1);
721 fn read_c_str(&self) -> ~str {
722 self.read_until(0u8, false)
725 fn read_whole_stream(&self) -> ~[u8] {
726 let mut bytes: ~[u8] = ~[];
727 while !self.eof() { bytes.push_all(self.read_bytes(2048u)); }
731 fn each_byte(&self, it: &fn(int) -> bool) -> bool {
733 match self.read_byte() {
735 ch => if !it(ch) { return false; }
741 fn each_char(&self, it: &fn(char) -> bool) -> bool {
743 match self.read_char() {
744 eof if eof == (-1 as char) => break,
745 ch => if !it(ch) { return false; }
751 fn each_line(&self, it: &fn(s: &str) -> bool) -> bool {
753 // include the \n, so that we can distinguish an entirely empty
754 // line read after "...\n", and the trailing empty line in
756 let mut line = self.read_until('\n' as u8, true);
758 // blank line at the end of the reader is ignored
759 if self.eof() && line.is_empty() { break; }
761 // trim the \n, so that each_line is consistent with read_line
763 if line[n-1] == '\n' as u8 {
764 unsafe { str::raw::set_len(&mut line, n-1); }
767 if !it(line) { return false; }
772 fn read_lines(&self) -> ~[~str] {
773 do vec::build |push| {
774 do self.each_line |line| {
775 push(line.to_owned());
781 // FIXME int reading methods need to deal with eof - issue #2004
783 fn read_le_uint_n(&self, nbytes: uint) -> u64 {
784 assert!(nbytes > 0 && nbytes <= 8);
790 val += (self.read_u8() as u64) << pos;
797 fn read_le_int_n(&self, nbytes: uint) -> i64 {
798 extend_sign(self.read_le_uint_n(nbytes), nbytes)
801 fn read_be_uint_n(&self, nbytes: uint) -> u64 {
802 assert!(nbytes > 0 && nbytes <= 8);
808 val += (self.read_u8() as u64) << i * 8;
813 fn read_be_int_n(&self, nbytes: uint) -> i64 {
814 extend_sign(self.read_be_uint_n(nbytes), nbytes)
817 fn read_le_uint(&self) -> uint {
818 self.read_le_uint_n(uint::bytes) as uint
821 fn read_le_int(&self) -> int {
822 self.read_le_int_n(int::bytes) as int
825 fn read_be_uint(&self) -> uint {
826 self.read_be_uint_n(uint::bytes) as uint
829 fn read_be_int(&self) -> int {
830 self.read_be_int_n(int::bytes) as int
833 fn read_be_u64(&self) -> u64 {
834 self.read_be_uint_n(8) as u64
837 fn read_be_u32(&self) -> u32 {
838 self.read_be_uint_n(4) as u32
841 fn read_be_u16(&self) -> u16 {
842 self.read_be_uint_n(2) as u16
845 fn read_be_i64(&self) -> i64 {
846 self.read_be_int_n(8) as i64
849 fn read_be_i32(&self) -> i32 {
850 self.read_be_int_n(4) as i32
853 fn read_be_i16(&self) -> i16 {
854 self.read_be_int_n(2) as i16
857 fn read_be_f64(&self) -> f64 {
859 cast::transmute::<u64, f64>(self.read_be_u64())
863 fn read_be_f32(&self) -> f32 {
865 cast::transmute::<u32, f32>(self.read_be_u32())
869 fn read_le_u64(&self) -> u64 {
870 self.read_le_uint_n(8) as u64
873 fn read_le_u32(&self) -> u32 {
874 self.read_le_uint_n(4) as u32
877 fn read_le_u16(&self) -> u16 {
878 self.read_le_uint_n(2) as u16
881 fn read_le_i64(&self) -> i64 {
882 self.read_le_int_n(8) as i64
885 fn read_le_i32(&self) -> i32 {
886 self.read_le_int_n(4) as i32
889 fn read_le_i16(&self) -> i16 {
890 self.read_le_int_n(2) as i16
893 fn read_le_f64(&self) -> f64 {
895 cast::transmute::<u64, f64>(self.read_le_u64())
899 fn read_le_f32(&self) -> f32 {
901 cast::transmute::<u32, f32>(self.read_le_u32())
905 fn read_u8(&self) -> u8 {
906 self.read_byte() as u8
909 fn read_i8(&self) -> i8 {
910 self.read_byte() as i8
914 fn extend_sign(val: u64, nbytes: uint) -> i64 {
915 let shift = (8 - nbytes) * 8;
916 (val << shift) as i64 >> shift
919 // Reader implementations
921 fn convert_whence(whence: SeekStyle) -> i32 {
922 return match whence {
929 impl Reader for *libc::FILE {
930 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
932 do bytes.as_mut_buf |buf_p, buf_len| {
933 assert!(buf_len >= len);
935 let count = libc::fread(buf_p as *mut c_void, 1u as size_t,
936 len as size_t, *self) as uint;
938 match libc::ferror(*self) {
941 error!("error reading buffer");
942 error!("%s", os::last_os_error());
952 fn read_byte(&self) -> int {
954 libc::fgetc(*self) as int
957 fn eof(&self) -> bool {
959 return libc::feof(*self) != 0 as c_int;
962 fn seek(&self, offset: int, whence: SeekStyle) {
964 assert!(libc::fseek(*self,
966 convert_whence(whence)) == 0 as c_int);
969 fn tell(&self) -> uint {
971 return libc::ftell(*self) as uint;
976 struct Wrapper<T, C> {
981 // A forwarding impl of reader that also holds on to a resource for the
982 // duration of its lifetime.
983 // FIXME there really should be a better way to do this // #2004
984 impl<R:Reader,C> Reader for Wrapper<R, C> {
985 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
986 self.base.read(bytes, len)
988 fn read_byte(&self) -> int { self.base.read_byte() }
989 fn eof(&self) -> bool { self.base.eof() }
990 fn seek(&self, off: int, whence: SeekStyle) {
991 self.base.seek(off, whence)
993 fn tell(&self) -> uint { self.base.tell() }
1001 pub fn new(f: *libc::FILE) -> FILERes {
1006 impl Drop for FILERes {
1009 libc::fclose(self.f);
1014 pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> @Reader {
1016 @Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader
1022 // FIXME (#2004): this should either be an trait-less impl, a set of
1023 // top-level functions that take a reader, or a set of default methods on
1024 // reader (which can then be called reader)
1027 * Gives a `Reader` that allows you to read values from standard input.
1032 * let stdin = std::io::stdin();
1033 * let line = stdin.read_line();
1034 * std::io::print(line);
1037 pub fn stdin() -> @Reader {
1039 @rustrt::rust_get_stdin() as @Reader
1043 pub fn file_reader(path: &Path) -> Result<@Reader, ~str> {
1044 let f = do path.with_c_str |pathbuf| {
1045 do "rb".with_c_str |modebuf| {
1046 unsafe { libc::fopen(pathbuf, modebuf as *libc::c_char) }
1050 if f as uint == 0u {
1051 Err(~"error opening " + path.to_str())
1053 Ok(FILE_reader(f, true))
1059 pub struct BytesReader {
1060 // FIXME(#5723) see other FIXME below
1061 // FIXME(#7268) this should also be parameterized over <'self>
1062 bytes: &'static [u8],
1066 impl Reader for BytesReader {
1067 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
1068 let count = num::min(len, self.bytes.len() - *self.pos);
1070 let view = self.bytes.slice(*self.pos, self.bytes.len());
1071 vec::bytes::copy_memory(bytes, view, count);
1078 fn read_byte(&self) -> int {
1079 if *self.pos == self.bytes.len() {
1083 let b = self.bytes[*self.pos];
1088 fn eof(&self) -> bool {
1089 *self.pos == self.bytes.len()
1092 fn seek(&self, offset: int, whence: SeekStyle) {
1093 let pos = *self.pos;
1094 *self.pos = seek_in_buf(offset, pos, self.bytes.len(), whence);
1097 fn tell(&self) -> uint {
1102 pub fn with_bytes_reader<T>(bytes: &[u8], f: &fn(@Reader) -> T) -> T {
1103 // XXX XXX XXX this is glaringly unsound
1104 // FIXME(#5723) Use a &Reader for the callback's argument. Should be:
1105 // fn with_bytes_reader<'r, T>(bytes: &'r [u8], f: &fn(&'r Reader) -> T) -> T
1106 let bytes: &'static [u8] = unsafe { cast::transmute(bytes) };
1113 pub fn with_str_reader<T>(s: &str, f: &fn(@Reader) -> T) -> T {
1114 // FIXME(#5723): As above.
1115 with_bytes_reader(s.as_bytes(), f)
1119 pub enum FileFlag { Append, Create, Truncate, NoFlag, }
1121 // What type of writer are we?
1123 pub enum WriterType { Screen, File }
1125 // FIXME (#2004): Seekable really should be orthogonal.
1126 // FIXME (#2004): eventually u64
1127 /// The raw underlying writer trait. All writers must implement this.
1130 /// Write all of the given bytes.
1131 fn write(&self, v: &[u8]);
1133 /// Move the current position within the stream. The second parameter
1134 /// determines the position that the first parameter is relative to.
1135 fn seek(&self, int, SeekStyle);
1137 /// Return the current position within the stream.
1138 fn tell(&self) -> uint;
1140 /// Flush the output buffer for this stream (if there is one).
1141 fn flush(&self) -> int;
1143 /// Determine if this Writer is writing to a file or not.
1144 fn get_type(&self) -> WriterType;
1147 impl Writer for @Writer {
1148 fn write(&self, v: &[u8]) { self.write(v) }
1149 fn seek(&self, a: int, b: SeekStyle) { self.seek(a, b) }
1150 fn tell(&self) -> uint { self.tell() }
1151 fn flush(&self) -> int { self.flush() }
1152 fn get_type(&self) -> WriterType { self.get_type() }
1155 impl<W:Writer,C> Writer for Wrapper<W, C> {
1156 fn write(&self, bs: &[u8]) { self.base.write(bs); }
1157 fn seek(&self, off: int, style: SeekStyle) { self.base.seek(off, style); }
1158 fn tell(&self) -> uint { self.base.tell() }
1159 fn flush(&self) -> int { self.base.flush() }
1160 fn get_type(&self) -> WriterType { File }
1163 impl Writer for *libc::FILE {
1164 fn write(&self, v: &[u8]) {
1166 do v.as_imm_buf |vbuf, len| {
1167 let nout = libc::fwrite(vbuf as *c_void,
1171 if nout != len as size_t {
1172 error!("error writing buffer");
1173 error!("%s", os::last_os_error());
1179 fn seek(&self, offset: int, whence: SeekStyle) {
1181 assert!(libc::fseek(*self,
1183 convert_whence(whence)) == 0 as c_int);
1186 fn tell(&self) -> uint {
1188 libc::ftell(*self) as uint
1191 fn flush(&self) -> int {
1193 libc::fflush(*self) as int
1196 fn get_type(&self) -> WriterType {
1198 let fd = libc::fileno(*self);
1199 if libc::isatty(fd) == 0 { File }
1205 pub fn FILE_writer(f: *libc::FILE, cleanup: bool) -> @Writer {
1207 @Wrapper { base: f, cleanup: FILERes::new(f) } as @Writer
1213 impl Writer for fd_t {
1214 fn write(&self, v: &[u8]) {
1217 do v.as_imm_buf |vbuf, len| {
1219 let vb = ptr::offset(vbuf, count as int) as *c_void;
1220 let nout = libc::write(*self, vb, len as size_t);
1221 if nout < 0 as ssize_t {
1222 error!("error writing buffer");
1223 error!("%s", os::last_os_error());
1226 count += nout as uint;
1231 fn seek(&self, _offset: int, _whence: SeekStyle) {
1232 error!("need 64-bit foreign calls for seek, sorry");
1235 fn tell(&self) -> uint {
1236 error!("need 64-bit foreign calls for tell, sorry");
1239 fn flush(&self) -> int { 0 }
1240 fn get_type(&self) -> WriterType {
1242 if libc::isatty(*self) == 0 { File } else { Screen }
1252 pub fn new(fd: fd_t) -> FdRes {
1257 impl Drop for FdRes {
1260 libc::close(self.fd);
1265 pub fn fd_writer(fd: fd_t, cleanup: bool) -> @Writer {
1267 @Wrapper { base: fd, cleanup: FdRes::new(fd) } as @Writer
1274 pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1275 -> Result<@Writer, ~str> {
1278 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1282 fn wb() -> c_int { O_WRONLY as c_int }
1284 let mut fflags: c_int = wb();
1285 for f in flags.iter() {
1287 Append => fflags |= O_APPEND as c_int,
1288 Create => fflags |= O_CREAT as c_int,
1289 Truncate => fflags |= O_TRUNC as c_int,
1294 do path.with_c_str |pathbuf| {
1295 libc::open(pathbuf, fflags, (S_IRUSR | S_IWUSR) as c_int)
1298 if fd < (0 as c_int) {
1299 Err(fmt!("error opening %s: %s", path.to_str(), os::last_os_error()))
1301 Ok(fd_writer(fd, true))
1305 pub fn u64_to_le_bytes<T>(n: u64, size: uint,
1306 f: &fn(v: &[u8]) -> T) -> T {
1307 assert!(size <= 8u);
1309 1u => f(&[n as u8]),
1326 let mut bytes: ~[u8] = ~[];
1330 bytes.push((n & 255_u64) as u8);
1339 pub fn u64_to_be_bytes<T>(n: u64, size: uint,
1340 f: &fn(v: &[u8]) -> T) -> T {
1341 assert!(size <= 8u);
1343 1u => f(&[n as u8]),
1344 2u => f(&[(n >> 8) as u8,
1346 4u => f(&[(n >> 24) as u8,
1350 8u => f(&[(n >> 56) as u8,
1359 let mut bytes: ~[u8] = ~[];
1362 let shift = ((i - 1u) * 8u) as u64;
1363 bytes.push((n >> shift) as u8);
1371 pub fn u64_from_be_bytes(data: &[u8],
1376 assert!((sz <= 8u));
1377 let mut val = 0_u64;
1378 let mut pos = start;
1381 val += (data[pos] as u64) << ((sz * 8u) as u64);
1387 // FIXME: #3048 combine trait+impl (or just move these to
1388 // default methods on writer)
1389 /// Generic utility functions defined on writers.
1390 pub trait WriterUtil {
1392 /// Write a single utf-8 encoded char.
1393 fn write_char(&self, ch: char);
1395 /// Write every char in the given str, encoded as utf-8.
1396 fn write_str(&self, s: &str);
1398 /// Write the given str, as utf-8, followed by '\n'.
1399 fn write_line(&self, s: &str);
1401 /// Write the result of passing n through `int::to_str_bytes`.
1402 fn write_int(&self, n: int);
1404 /// Write the result of passing n through `uint::to_str_bytes`.
1405 fn write_uint(&self, n: uint);
1407 /// Write a little-endian uint (number of bytes depends on system).
1408 fn write_le_uint(&self, n: uint);
1410 /// Write a little-endian int (number of bytes depends on system).
1411 fn write_le_int(&self, n: int);
1413 /// Write a big-endian uint (number of bytes depends on system).
1414 fn write_be_uint(&self, n: uint);
1416 /// Write a big-endian int (number of bytes depends on system).
1417 fn write_be_int(&self, n: int);
1419 /// Write a big-endian u64 (8 bytes).
1420 fn write_be_u64(&self, n: u64);
1422 /// Write a big-endian u32 (4 bytes).
1423 fn write_be_u32(&self, n: u32);
1425 /// Write a big-endian u16 (2 bytes).
1426 fn write_be_u16(&self, n: u16);
1428 /// Write a big-endian i64 (8 bytes).
1429 fn write_be_i64(&self, n: i64);
1431 /// Write a big-endian i32 (4 bytes).
1432 fn write_be_i32(&self, n: i32);
1434 /// Write a big-endian i16 (2 bytes).
1435 fn write_be_i16(&self, n: i16);
1437 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1438 fn write_be_f64(&self, f: f64);
1440 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1441 fn write_be_f32(&self, f: f32);
1443 /// Write a little-endian u64 (8 bytes).
1444 fn write_le_u64(&self, n: u64);
1446 /// Write a little-endian u32 (4 bytes).
1447 fn write_le_u32(&self, n: u32);
1449 /// Write a little-endian u16 (2 bytes).
1450 fn write_le_u16(&self, n: u16);
1452 /// Write a little-endian i64 (8 bytes).
1453 fn write_le_i64(&self, n: i64);
1455 /// Write a little-endian i32 (4 bytes).
1456 fn write_le_i32(&self, n: i32);
1458 /// Write a little-endian i16 (2 bytes).
1459 fn write_le_i16(&self, n: i16);
1461 /// Write a little-endian IEEE754 double-precision floating-point
1463 fn write_le_f64(&self, f: f64);
1465 /// Write a little-endian IEEE754 single-precision floating-point
1467 fn write_le_f32(&self, f: f32);
1469 /// Write a u8 (1 byte).
1470 fn write_u8(&self, n: u8);
1472 /// Write a i8 (1 byte).
1473 fn write_i8(&self, n: i8);
1476 impl<T:Writer> WriterUtil for T {
1477 fn write_char(&self, ch: char) {
1478 if (ch as uint) < 128u {
1479 self.write(&[ch as u8]);
1481 self.write_str(str::from_char(ch));
1484 fn write_str(&self, s: &str) { self.write(s.as_bytes()) }
1485 fn write_line(&self, s: &str) {
1487 self.write_str(&"\n");
1489 fn write_int(&self, n: int) {
1490 int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1492 fn write_uint(&self, n: uint) {
1493 uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1495 fn write_le_uint(&self, n: uint) {
1496 u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v))
1498 fn write_le_int(&self, n: int) {
1499 u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v))
1501 fn write_be_uint(&self, n: uint) {
1502 u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v))
1504 fn write_be_int(&self, n: int) {
1505 u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v))
1507 fn write_be_u64(&self, n: u64) {
1508 u64_to_be_bytes(n, 8u, |v| self.write(v))
1510 fn write_be_u32(&self, n: u32) {
1511 u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1513 fn write_be_u16(&self, n: u16) {
1514 u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1516 fn write_be_i64(&self, n: i64) {
1517 u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1519 fn write_be_i32(&self, n: i32) {
1520 u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1522 fn write_be_i16(&self, n: i16) {
1523 u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1525 fn write_be_f64(&self, f:f64) {
1527 self.write_be_u64(cast::transmute(f))
1530 fn write_be_f32(&self, f:f32) {
1532 self.write_be_u32(cast::transmute(f))
1535 fn write_le_u64(&self, n: u64) {
1536 u64_to_le_bytes(n, 8u, |v| self.write(v))
1538 fn write_le_u32(&self, n: u32) {
1539 u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1541 fn write_le_u16(&self, n: u16) {
1542 u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1544 fn write_le_i64(&self, n: i64) {
1545 u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1547 fn write_le_i32(&self, n: i32) {
1548 u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1550 fn write_le_i16(&self, n: i16) {
1551 u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1553 fn write_le_f64(&self, f:f64) {
1555 self.write_le_u64(cast::transmute(f))
1558 fn write_le_f32(&self, f:f32) {
1560 self.write_le_u32(cast::transmute(f))
1564 fn write_u8(&self, n: u8) { self.write([n]) }
1565 fn write_i8(&self, n: i8) { self.write([n as u8]) }
1569 pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> {
1570 mk_file_writer(path, flags).chain(|w| Ok(w))
1574 // FIXME: fileflags // #2004
1575 pub fn buffered_file_writer(path: &Path) -> Result<@Writer, ~str> {
1577 let f = do path.with_c_str |pathbuf| {
1578 do "w".with_c_str |modebuf| {
1579 libc::fopen(pathbuf, modebuf)
1582 return if f as uint == 0u {
1583 Err(~"error opening " + path.to_str())
1585 Ok(FILE_writer(f, true))
1590 // FIXME (#2004) it would be great if this could be a const
1591 // FIXME (#2004) why are these different from the way stdin() is
1596 * Gives a `Writer` which allows you to write to the standard output.
1601 * let stdout = std::io::stdout();
1602 * stdout.write_str("hello\n");
1605 pub fn stdout() -> @Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) }
1608 * Gives a `Writer` which allows you to write to standard error.
1613 * let stderr = std::io::stderr();
1614 * stderr.write_str("hello\n");
1617 pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) }
1620 * Prints a string to standard output.
1622 * This string will not have an implicit newline at the end. If you want
1623 * an implicit newline, please see `println`.
1628 * // print is imported into the prelude, and so is always available.
1632 pub fn print(s: &str) {
1633 stdout().write_str(s);
1637 * Prints a string to standard output, followed by a newline.
1639 * If you do not want an implicit newline, please see `print`.
1644 * // println is imported into the prelude, and so is always available.
1648 pub fn println(s: &str) {
1649 stdout().write_line(s);
1652 pub struct BytesWriter {
1658 pub fn new() -> BytesWriter {
1666 impl Writer for BytesWriter {
1667 fn write(&self, v: &[u8]) {
1668 let v_len = v.len();
1670 let bytes = &mut *self.bytes;
1671 let count = num::max(bytes.len(), *self.pos + v_len);
1672 bytes.reserve(count);
1675 vec::raw::set_len(bytes, count);
1677 let view = bytes.mut_slice(*self.pos, count);
1678 vec::bytes::copy_memory(view, v, v_len);
1684 fn seek(&self, offset: int, whence: SeekStyle) {
1685 let pos = *self.pos;
1686 let len = self.bytes.len();
1687 *self.pos = seek_in_buf(offset, pos, len, whence);
1690 fn tell(&self) -> uint {
1694 fn flush(&self) -> int {
1698 fn get_type(&self) -> WriterType {
1703 pub fn with_bytes_writer(f: &fn(@Writer)) -> ~[u8] {
1704 let wr = @BytesWriter::new();
1706 let @BytesWriter { bytes, _ } = wr;
1710 pub fn with_str_writer(f: &fn(@Writer)) -> ~str {
1711 str::from_bytes(with_bytes_writer(f))
1714 // Utility functions
1715 pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) ->
1717 let mut bpos = pos as int;
1718 let blen = len as int;
1720 SeekSet => bpos = offset,
1721 SeekCur => bpos += offset,
1722 SeekEnd => bpos = blen + offset
1724 if bpos < 0 { bpos = 0; } else if bpos > blen { bpos = blen; }
1725 return bpos as uint;
1728 pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
1729 do read_whole_file(file).chain |bytes| {
1730 if str::is_utf8(bytes) {
1731 Ok(str::from_bytes(bytes))
1733 Err(file.to_str() + " is not UTF-8")
1738 // FIXME (#2004): implement this in a low-level way. Going through the
1739 // abstractions is pointless.
1740 pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> {
1741 do file_reader(file).chain |rdr| {
1742 Ok(rdr.read_whole_stream())
1749 use io::{FILERes, FdRes, fd_t};
1752 use option::{None, Option, Some};
1756 // whatever fsync does on that platform
1759 // fdatasync on linux, similiar or more on other platforms
1764 // You must additionally sync the parent directory as well!
1769 // Artifacts that need to fsync on destruction
1775 pub fn new(arg: Arg<t>) -> Res<t> {
1780 #[unsafe_destructor]
1781 impl<T> Drop for Res<T> {
1783 match self.arg.opt_level {
1786 // fail hard if not succesful
1787 assert!(((self.arg.fsync_fn)(&self.arg.val, level) != -1));
1795 opt_level: Option<Level>,
1796 fsync_fn: @fn(f: &t, Level) -> int,
1799 // fsync file after executing blk
1800 // FIXME (#2004) find better way to create resources within lifetime of
1802 pub fn FILE_res_sync(file: &FILERes, opt_level: Option<Level>,
1803 blk: &fn(v: Res<*libc::FILE>)) {
1805 val: file.f, opt_level: opt_level,
1806 fsync_fn: |file, l| {
1808 os::fsync_fd(libc::fileno(*file), l) as int
1814 // fsync fd after executing blk
1815 pub fn fd_res_sync(fd: &FdRes, opt_level: Option<Level>,
1816 blk: &fn(v: Res<fd_t>)) {
1818 val: fd.fd, opt_level: opt_level,
1819 fsync_fn: |fd, l| os::fsync_fd(*fd, l) as int
1823 // Type of objects that may want to fsync
1824 pub trait FSyncable { fn fsync(&self, l: Level) -> int; }
1826 // Call o.fsync after executing blk
1827 pub fn obj_sync(o: @FSyncable, opt_level: Option<Level>,
1828 blk: &fn(v: Res<@FSyncable>)) {
1830 val: o, opt_level: opt_level,
1831 fsync_fn: |o, l| (*o).fsync(l)
1840 use io::{BytesWriter, SeekCur, SeekEnd, SeekSet};
1843 use result::{Ok, Err};
1849 let tmpfile = &Path("tmp/lib-io-test-simple.tmp");
1852 ~"A hoopy frood who really knows where his towel is.";
1853 debug!(frood.clone());
1855 let out = io::file_writer(tmpfile, [io::Create, io::Truncate]).unwrap();
1856 out.write_str(frood);
1858 let inp = io::file_reader(tmpfile).unwrap();
1859 let frood2: ~str = inp.read_c_str();
1860 debug!(frood2.clone());
1861 assert_eq!(frood, frood2);
1865 fn test_each_byte_each_char_file() {
1866 // Issue #5056 -- shouldn't include trailing EOF.
1867 let path = Path("tmp/lib-io-test-each-byte-each-char-file.tmp");
1870 // create empty, enough to reproduce a problem
1871 io::file_writer(&path, [io::Create]).unwrap();
1875 let file = io::file_reader(&path).unwrap();
1876 do file.each_byte() |_| {
1877 fail!("must be empty")
1882 let file = io::file_reader(&path).unwrap();
1883 do file.each_char() |_| {
1884 fail!("must be empty")
1890 fn test_readchars_empty() {
1891 do io::with_str_reader("") |inp| {
1892 let res : ~[char] = inp.read_chars(128);
1893 assert_eq!(res.len(), 0);
1898 fn test_read_line_utf8() {
1899 do io::with_str_reader("生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| {
1900 let line = inp.read_line();
1901 assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤");
1906 fn test_read_lines() {
1907 do io::with_str_reader("a\nb\nc\n") |inp| {
1908 assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1911 do io::with_str_reader("a\nb\nc") |inp| {
1912 assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1915 do io::with_str_reader("") |inp| {
1916 assert!(inp.read_lines().is_empty());
1921 fn test_readchars_wide() {
1922 let wide_test = ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤";
1923 let ivals : ~[int] = ~[
1924 29983, 38152, 30340, 27748,
1925 21273, 20999, 32905, 27748,
1926 104, 101, 108, 108, 111,
1927 29983, 38152, 30340, 27748,
1928 21273, 20999, 32905, 27748];
1929 fn check_read_ln(len : uint, s: &str, ivals: &[int]) {
1930 do io::with_str_reader(s) |inp| {
1931 let res : ~[char] = inp.read_chars(len);
1932 if len <= ivals.len() {
1933 assert_eq!(res.len(), len);
1935 for (iv, c) in ivals.iter().zip(res.iter()) {
1936 assert!(*iv == *c as int)
1942 check_read_ln(i, wide_test, ivals);
1945 // check a long read for good measure
1946 check_read_ln(128, wide_test, ivals);
1950 fn test_readchar() {
1951 do io::with_str_reader("生") |inp| {
1952 let res : char = inp.read_char();
1953 assert_eq!(res as int, 29983);
1958 fn test_readchar_empty() {
1959 do io::with_str_reader("") |inp| {
1960 let res : char = inp.read_char();
1961 assert_eq!(res as int, -1);
1966 fn file_reader_not_exist() {
1967 match io::file_reader(&Path("not a file")) {
1969 assert_eq!(e, ~"error opening not a file");
1977 #[ignore(cfg(windows))]
1978 fn test_read_buffer_too_small() {
1979 let path = &Path("tmp/lib-io-test-read-buffer-too-small.tmp");
1980 // ensure the file exists
1981 io::file_writer(path, [io::Create]).unwrap();
1983 let file = io::file_reader(path).unwrap();
1984 let mut buf = vec::from_elem(5, 0u8);
1985 file.read(buf, 6); // this should fail because buf is too small
1989 fn test_read_buffer_big_enough() {
1990 let path = &Path("tmp/lib-io-test-read-buffer-big-enough.tmp");
1991 // ensure the file exists
1992 io::file_writer(path, [io::Create]).unwrap();
1994 let file = io::file_reader(path).unwrap();
1995 let mut buf = vec::from_elem(5, 0u8);
1996 file.read(buf, 4); // this should succeed because buf is big enough
2000 fn test_write_empty() {
2001 let file = io::file_writer(&Path("tmp/lib-io-test-write-empty.tmp"),
2002 [io::Create]).unwrap();
2007 fn file_writer_bad_name() {
2008 match io::file_writer(&Path("?/?"), []) {
2010 assert!(e.starts_with("error opening"));
2017 fn buffered_file_writer_bad_name() {
2018 match io::buffered_file_writer(&Path("?/?")) {
2020 assert!(e.starts_with("error opening"));
2027 fn bytes_buffer_overwrite() {
2028 let wr = BytesWriter::new();
2029 wr.write([0u8, 1u8, 2u8, 3u8]);
2030 assert!(*wr.bytes == ~[0u8, 1u8, 2u8, 3u8]);
2031 wr.seek(-2, SeekCur);
2032 wr.write([4u8, 5u8, 6u8, 7u8]);
2033 assert!(*wr.bytes == ~[0u8, 1u8, 4u8, 5u8, 6u8, 7u8]);
2034 wr.seek(-2, SeekEnd);
2036 wr.seek(1, SeekSet);
2038 assert!(*wr.bytes == ~[0u8, 9u8, 4u8, 5u8, 8u8, 7u8]);
2042 fn test_read_write_le() {
2043 let path = Path("tmp/lib-io-test-read-write-le.tmp");
2044 let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2046 // write the ints to the file
2048 let file = io::file_writer(&path, [io::Create]).unwrap();
2049 for i in uints.iter() {
2050 file.write_le_u64(*i);
2054 // then read them back and check that they are the same
2056 let file = io::file_reader(&path).unwrap();
2057 for i in uints.iter() {
2058 assert_eq!(file.read_le_u64(), *i);
2064 fn test_read_write_be() {
2065 let path = Path("tmp/lib-io-test-read-write-be.tmp");
2066 let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2068 // write the ints to the file
2070 let file = io::file_writer(&path, [io::Create]).unwrap();
2071 for i in uints.iter() {
2072 file.write_be_u64(*i);
2076 // then read them back and check that they are the same
2078 let file = io::file_reader(&path).unwrap();
2079 for i in uints.iter() {
2080 assert_eq!(file.read_be_u64(), *i);
2086 fn test_read_be_int_n() {
2087 let path = Path("tmp/lib-io-test-read-be-int-n.tmp");
2088 let ints = [i32::min_value, -123456, -42, -5, 0, 1, i32::max_value];
2090 // write the ints to the file
2092 let file = io::file_writer(&path, [io::Create]).unwrap();
2093 for i in ints.iter() {
2094 file.write_be_i32(*i);
2098 // then read them back and check that they are the same
2100 let file = io::file_reader(&path).unwrap();
2101 for i in ints.iter() {
2102 // this tests that the sign extension is working
2103 // (comparing the values as i32 would not test this)
2104 assert_eq!(file.read_be_int_n(4), *i as i64);
2110 fn test_read_f32() {
2111 let path = Path("tmp/lib-io-test-read-f32.tmp");
2112 //big-endian floating-point 8.1250
2113 let buf = ~[0x41, 0x02, 0x00, 0x00];
2116 let file = io::file_writer(&path, [io::Create]).unwrap();
2121 let file = io::file_reader(&path).unwrap();
2122 let f = file.read_be_f32();
2123 assert_eq!(f, 8.1250);
2128 fn test_read_write_f32() {
2129 let path = Path("tmp/lib-io-test-read-write-f32.tmp");
2133 let file = io::file_writer(&path, [io::Create]).unwrap();
2134 file.write_be_f32(f);
2135 file.write_le_f32(f);
2139 let file = io::file_reader(&path).unwrap();
2140 assert_eq!(file.read_be_f32(), 8.1250);
2141 assert_eq!(file.read_le_f32(), 8.1250);