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 {
931 #[fixed_stack_segment]; #[inline(never)];
934 do bytes.as_mut_buf |buf_p, buf_len| {
935 assert!(buf_len >= len);
937 let count = libc::fread(buf_p as *mut c_void, 1u as size_t,
938 len as size_t, *self) as uint;
940 match libc::ferror(*self) {
943 error!("error reading buffer");
944 error!("%s", os::last_os_error());
954 fn read_byte(&self) -> int {
955 #[fixed_stack_segment]; #[inline(never)];
958 libc::fgetc(*self) as int
961 fn eof(&self) -> bool {
962 #[fixed_stack_segment]; #[inline(never)];
965 return libc::feof(*self) != 0 as c_int;
968 fn seek(&self, offset: int, whence: SeekStyle) {
969 #[fixed_stack_segment]; #[inline(never)];
972 assert!(libc::fseek(*self,
974 convert_whence(whence)) == 0 as c_int);
977 fn tell(&self) -> uint {
978 #[fixed_stack_segment]; #[inline(never)];
981 return libc::ftell(*self) as uint;
986 struct Wrapper<T, C> {
991 // A forwarding impl of reader that also holds on to a resource for the
992 // duration of its lifetime.
993 // FIXME there really should be a better way to do this // #2004
994 impl<R:Reader,C> Reader for Wrapper<R, C> {
995 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
996 self.base.read(bytes, len)
998 fn read_byte(&self) -> int { self.base.read_byte() }
999 fn eof(&self) -> bool { self.base.eof() }
1000 fn seek(&self, off: int, whence: SeekStyle) {
1001 self.base.seek(off, whence)
1003 fn tell(&self) -> uint { self.base.tell() }
1006 pub struct FILERes {
1011 pub fn new(f: *libc::FILE) -> FILERes {
1016 impl Drop for FILERes {
1018 #[fixed_stack_segment]; #[inline(never)];
1021 libc::fclose(self.f);
1026 pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> @Reader {
1028 @Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader
1034 // FIXME (#2004): this should either be an trait-less impl, a set of
1035 // top-level functions that take a reader, or a set of default methods on
1036 // reader (which can then be called reader)
1039 * Gives a `Reader` that allows you to read values from standard input.
1044 * let stdin = std::io::stdin();
1045 * let line = stdin.read_line();
1046 * std::io::print(line);
1049 pub fn stdin() -> @Reader {
1050 #[fixed_stack_segment]; #[inline(never)];
1053 @rustrt::rust_get_stdin() as @Reader
1057 pub fn file_reader(path: &Path) -> Result<@Reader, ~str> {
1058 #[fixed_stack_segment]; #[inline(never)];
1060 let f = do path.with_c_str |pathbuf| {
1061 do "rb".with_c_str |modebuf| {
1062 unsafe { libc::fopen(pathbuf, modebuf as *libc::c_char) }
1066 if f as uint == 0u {
1067 Err(~"error opening " + path.to_str())
1069 Ok(FILE_reader(f, true))
1075 pub struct BytesReader {
1076 // FIXME(#5723) see other FIXME below
1077 // FIXME(#7268) this should also be parameterized over <'self>
1078 bytes: &'static [u8],
1082 impl Reader for BytesReader {
1083 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
1084 let count = num::min(len, self.bytes.len() - *self.pos);
1086 let view = self.bytes.slice(*self.pos, self.bytes.len());
1087 vec::bytes::copy_memory(bytes, view, count);
1094 fn read_byte(&self) -> int {
1095 if *self.pos == self.bytes.len() {
1099 let b = self.bytes[*self.pos];
1104 fn eof(&self) -> bool {
1105 *self.pos == self.bytes.len()
1108 fn seek(&self, offset: int, whence: SeekStyle) {
1109 let pos = *self.pos;
1110 *self.pos = seek_in_buf(offset, pos, self.bytes.len(), whence);
1113 fn tell(&self) -> uint {
1118 pub fn with_bytes_reader<T>(bytes: &[u8], f: &fn(@Reader) -> T) -> T {
1119 // XXX XXX XXX this is glaringly unsound
1120 // FIXME(#5723) Use a &Reader for the callback's argument. Should be:
1121 // fn with_bytes_reader<'r, T>(bytes: &'r [u8], f: &fn(&'r Reader) -> T) -> T
1122 let bytes: &'static [u8] = unsafe { cast::transmute(bytes) };
1129 pub fn with_str_reader<T>(s: &str, f: &fn(@Reader) -> T) -> T {
1130 // FIXME(#5723): As above.
1131 with_bytes_reader(s.as_bytes(), f)
1135 pub enum FileFlag { Append, Create, Truncate, NoFlag, }
1137 // What type of writer are we?
1139 pub enum WriterType { Screen, File }
1141 // FIXME (#2004): Seekable really should be orthogonal.
1142 // FIXME (#2004): eventually u64
1143 /// The raw underlying writer trait. All writers must implement this.
1146 /// Write all of the given bytes.
1147 fn write(&self, v: &[u8]);
1149 /// Move the current position within the stream. The second parameter
1150 /// determines the position that the first parameter is relative to.
1151 fn seek(&self, int, SeekStyle);
1153 /// Return the current position within the stream.
1154 fn tell(&self) -> uint;
1156 /// Flush the output buffer for this stream (if there is one).
1157 fn flush(&self) -> int;
1159 /// Determine if this Writer is writing to a file or not.
1160 fn get_type(&self) -> WriterType;
1163 impl Writer for @Writer {
1164 fn write(&self, v: &[u8]) { self.write(v) }
1165 fn seek(&self, a: int, b: SeekStyle) { self.seek(a, b) }
1166 fn tell(&self) -> uint { self.tell() }
1167 fn flush(&self) -> int { self.flush() }
1168 fn get_type(&self) -> WriterType { self.get_type() }
1171 impl<W:Writer,C> Writer for Wrapper<W, C> {
1172 fn write(&self, bs: &[u8]) { self.base.write(bs); }
1173 fn seek(&self, off: int, style: SeekStyle) { self.base.seek(off, style); }
1174 fn tell(&self) -> uint { self.base.tell() }
1175 fn flush(&self) -> int { self.base.flush() }
1176 fn get_type(&self) -> WriterType { File }
1179 impl Writer for *libc::FILE {
1180 fn write(&self, v: &[u8]) {
1181 #[fixed_stack_segment]; #[inline(never)];
1184 do v.as_imm_buf |vbuf, len| {
1185 let nout = libc::fwrite(vbuf as *c_void,
1189 if nout != len as size_t {
1190 error!("error writing buffer");
1191 error!("%s", os::last_os_error());
1197 fn seek(&self, offset: int, whence: SeekStyle) {
1198 #[fixed_stack_segment]; #[inline(never)];
1201 assert!(libc::fseek(*self,
1203 convert_whence(whence)) == 0 as c_int);
1206 fn tell(&self) -> uint {
1207 #[fixed_stack_segment]; #[inline(never)];
1210 libc::ftell(*self) as uint
1213 fn flush(&self) -> int {
1214 #[fixed_stack_segment]; #[inline(never)];
1217 libc::fflush(*self) as int
1220 fn get_type(&self) -> WriterType {
1221 #[fixed_stack_segment]; #[inline(never)];
1224 let fd = libc::fileno(*self);
1225 if libc::isatty(fd) == 0 { File }
1231 pub fn FILE_writer(f: *libc::FILE, cleanup: bool) -> @Writer {
1233 @Wrapper { base: f, cleanup: FILERes::new(f) } as @Writer
1239 impl Writer for fd_t {
1240 fn write(&self, v: &[u8]) {
1241 #[fixed_stack_segment]; #[inline(never)];
1245 do v.as_imm_buf |vbuf, len| {
1247 let vb = ptr::offset(vbuf, count as int) as *c_void;
1248 let nout = libc::write(*self, vb, len as size_t);
1249 if nout < 0 as ssize_t {
1250 error!("error writing buffer");
1251 error!("%s", os::last_os_error());
1254 count += nout as uint;
1259 fn seek(&self, _offset: int, _whence: SeekStyle) {
1260 error!("need 64-bit foreign calls for seek, sorry");
1263 fn tell(&self) -> uint {
1264 error!("need 64-bit foreign calls for tell, sorry");
1267 fn flush(&self) -> int { 0 }
1268 fn get_type(&self) -> WriterType {
1269 #[fixed_stack_segment]; #[inline(never)];
1272 if libc::isatty(*self) == 0 { File } else { Screen }
1282 pub fn new(fd: fd_t) -> FdRes {
1287 impl Drop for FdRes {
1289 #[fixed_stack_segment]; #[inline(never)];
1292 libc::close(self.fd);
1297 pub fn fd_writer(fd: fd_t, cleanup: bool) -> @Writer {
1299 @Wrapper { base: fd, cleanup: FdRes::new(fd) } as @Writer
1306 pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1307 -> Result<@Writer, ~str> {
1308 #[fixed_stack_segment]; #[inline(never)];
1312 (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1316 fn wb() -> c_int { O_WRONLY as c_int }
1318 let mut fflags: c_int = wb();
1319 for f in flags.iter() {
1321 Append => fflags |= O_APPEND as c_int,
1322 Create => fflags |= O_CREAT as c_int,
1323 Truncate => fflags |= O_TRUNC as c_int,
1328 do path.with_c_str |pathbuf| {
1329 libc::open(pathbuf, fflags, (S_IRUSR | S_IWUSR) as c_int)
1332 if fd < (0 as c_int) {
1333 Err(fmt!("error opening %s: %s", path.to_str(), os::last_os_error()))
1335 Ok(fd_writer(fd, true))
1339 pub fn u64_to_le_bytes<T>(n: u64, size: uint,
1340 f: &fn(v: &[u8]) -> T) -> T {
1341 assert!(size <= 8u);
1343 1u => f(&[n as u8]),
1360 let mut bytes: ~[u8] = ~[];
1364 bytes.push((n & 255_u64) as u8);
1373 pub fn u64_to_be_bytes<T>(n: u64, size: uint,
1374 f: &fn(v: &[u8]) -> T) -> T {
1375 assert!(size <= 8u);
1377 1u => f(&[n as u8]),
1378 2u => f(&[(n >> 8) as u8,
1380 4u => f(&[(n >> 24) as u8,
1384 8u => f(&[(n >> 56) as u8,
1393 let mut bytes: ~[u8] = ~[];
1396 let shift = ((i - 1u) * 8u) as u64;
1397 bytes.push((n >> shift) as u8);
1405 pub fn u64_from_be_bytes(data: &[u8],
1410 assert!((sz <= 8u));
1411 let mut val = 0_u64;
1412 let mut pos = start;
1415 val += (data[pos] as u64) << ((sz * 8u) as u64);
1421 // FIXME: #3048 combine trait+impl (or just move these to
1422 // default methods on writer)
1423 /// Generic utility functions defined on writers.
1424 pub trait WriterUtil {
1426 /// Write a single utf-8 encoded char.
1427 fn write_char(&self, ch: char);
1429 /// Write every char in the given str, encoded as utf-8.
1430 fn write_str(&self, s: &str);
1432 /// Write the given str, as utf-8, followed by '\n'.
1433 fn write_line(&self, s: &str);
1435 /// Write the result of passing n through `int::to_str_bytes`.
1436 fn write_int(&self, n: int);
1438 /// Write the result of passing n through `uint::to_str_bytes`.
1439 fn write_uint(&self, n: uint);
1441 /// Write a little-endian uint (number of bytes depends on system).
1442 fn write_le_uint(&self, n: uint);
1444 /// Write a little-endian int (number of bytes depends on system).
1445 fn write_le_int(&self, n: int);
1447 /// Write a big-endian uint (number of bytes depends on system).
1448 fn write_be_uint(&self, n: uint);
1450 /// Write a big-endian int (number of bytes depends on system).
1451 fn write_be_int(&self, n: int);
1453 /// Write a big-endian u64 (8 bytes).
1454 fn write_be_u64(&self, n: u64);
1456 /// Write a big-endian u32 (4 bytes).
1457 fn write_be_u32(&self, n: u32);
1459 /// Write a big-endian u16 (2 bytes).
1460 fn write_be_u16(&self, n: u16);
1462 /// Write a big-endian i64 (8 bytes).
1463 fn write_be_i64(&self, n: i64);
1465 /// Write a big-endian i32 (4 bytes).
1466 fn write_be_i32(&self, n: i32);
1468 /// Write a big-endian i16 (2 bytes).
1469 fn write_be_i16(&self, n: i16);
1471 /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1472 fn write_be_f64(&self, f: f64);
1474 /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1475 fn write_be_f32(&self, f: f32);
1477 /// Write a little-endian u64 (8 bytes).
1478 fn write_le_u64(&self, n: u64);
1480 /// Write a little-endian u32 (4 bytes).
1481 fn write_le_u32(&self, n: u32);
1483 /// Write a little-endian u16 (2 bytes).
1484 fn write_le_u16(&self, n: u16);
1486 /// Write a little-endian i64 (8 bytes).
1487 fn write_le_i64(&self, n: i64);
1489 /// Write a little-endian i32 (4 bytes).
1490 fn write_le_i32(&self, n: i32);
1492 /// Write a little-endian i16 (2 bytes).
1493 fn write_le_i16(&self, n: i16);
1495 /// Write a little-endian IEEE754 double-precision floating-point
1497 fn write_le_f64(&self, f: f64);
1499 /// Write a little-endian IEEE754 single-precision floating-point
1501 fn write_le_f32(&self, f: f32);
1503 /// Write a u8 (1 byte).
1504 fn write_u8(&self, n: u8);
1506 /// Write a i8 (1 byte).
1507 fn write_i8(&self, n: i8);
1510 impl<T:Writer> WriterUtil for T {
1511 fn write_char(&self, ch: char) {
1512 if (ch as uint) < 128u {
1513 self.write(&[ch as u8]);
1515 self.write_str(str::from_char(ch));
1518 fn write_str(&self, s: &str) { self.write(s.as_bytes()) }
1519 fn write_line(&self, s: &str) {
1521 self.write_str(&"\n");
1523 fn write_int(&self, n: int) {
1524 int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1526 fn write_uint(&self, n: uint) {
1527 uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1529 fn write_le_uint(&self, n: uint) {
1530 u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v))
1532 fn write_le_int(&self, n: int) {
1533 u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v))
1535 fn write_be_uint(&self, n: uint) {
1536 u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v))
1538 fn write_be_int(&self, n: int) {
1539 u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v))
1541 fn write_be_u64(&self, n: u64) {
1542 u64_to_be_bytes(n, 8u, |v| self.write(v))
1544 fn write_be_u32(&self, n: u32) {
1545 u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1547 fn write_be_u16(&self, n: u16) {
1548 u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1550 fn write_be_i64(&self, n: i64) {
1551 u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1553 fn write_be_i32(&self, n: i32) {
1554 u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1556 fn write_be_i16(&self, n: i16) {
1557 u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1559 fn write_be_f64(&self, f:f64) {
1561 self.write_be_u64(cast::transmute(f))
1564 fn write_be_f32(&self, f:f32) {
1566 self.write_be_u32(cast::transmute(f))
1569 fn write_le_u64(&self, n: u64) {
1570 u64_to_le_bytes(n, 8u, |v| self.write(v))
1572 fn write_le_u32(&self, n: u32) {
1573 u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1575 fn write_le_u16(&self, n: u16) {
1576 u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1578 fn write_le_i64(&self, n: i64) {
1579 u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1581 fn write_le_i32(&self, n: i32) {
1582 u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1584 fn write_le_i16(&self, n: i16) {
1585 u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1587 fn write_le_f64(&self, f:f64) {
1589 self.write_le_u64(cast::transmute(f))
1592 fn write_le_f32(&self, f:f32) {
1594 self.write_le_u32(cast::transmute(f))
1598 fn write_u8(&self, n: u8) { self.write([n]) }
1599 fn write_i8(&self, n: i8) { self.write([n as u8]) }
1603 pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> {
1604 mk_file_writer(path, flags).chain(|w| Ok(w))
1608 // FIXME: fileflags // #2004
1609 pub fn buffered_file_writer(path: &Path) -> Result<@Writer, ~str> {
1610 #[fixed_stack_segment]; #[inline(never)];
1613 let f = do path.with_c_str |pathbuf| {
1614 do "w".with_c_str |modebuf| {
1615 libc::fopen(pathbuf, modebuf)
1618 return if f as uint == 0u {
1619 Err(~"error opening " + path.to_str())
1621 Ok(FILE_writer(f, true))
1626 // FIXME (#2004) it would be great if this could be a const
1627 // FIXME (#2004) why are these different from the way stdin() is
1632 * Gives a `Writer` which allows you to write to the standard output.
1637 * let stdout = std::io::stdout();
1638 * stdout.write_str("hello\n");
1641 pub fn stdout() -> @Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) }
1644 * Gives a `Writer` which allows you to write to standard error.
1649 * let stderr = std::io::stderr();
1650 * stderr.write_str("hello\n");
1653 pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) }
1656 * Prints a string to standard output.
1658 * This string will not have an implicit newline at the end. If you want
1659 * an implicit newline, please see `println`.
1664 * // print is imported into the prelude, and so is always available.
1668 pub fn print(s: &str) {
1669 stdout().write_str(s);
1673 * Prints a string to standard output, followed by a newline.
1675 * If you do not want an implicit newline, please see `print`.
1680 * // println is imported into the prelude, and so is always available.
1684 pub fn println(s: &str) {
1685 stdout().write_line(s);
1688 pub struct BytesWriter {
1694 pub fn new() -> BytesWriter {
1702 impl Writer for BytesWriter {
1703 fn write(&self, v: &[u8]) {
1704 let v_len = v.len();
1706 let bytes = &mut *self.bytes;
1707 let count = num::max(bytes.len(), *self.pos + v_len);
1708 bytes.reserve(count);
1711 vec::raw::set_len(bytes, count);
1713 let view = bytes.mut_slice(*self.pos, count);
1714 vec::bytes::copy_memory(view, v, v_len);
1720 fn seek(&self, offset: int, whence: SeekStyle) {
1721 let pos = *self.pos;
1722 let len = self.bytes.len();
1723 *self.pos = seek_in_buf(offset, pos, len, whence);
1726 fn tell(&self) -> uint {
1730 fn flush(&self) -> int {
1734 fn get_type(&self) -> WriterType {
1739 pub fn with_bytes_writer(f: &fn(@Writer)) -> ~[u8] {
1740 let wr = @BytesWriter::new();
1742 let @BytesWriter { bytes, _ } = wr;
1746 pub fn with_str_writer(f: &fn(@Writer)) -> ~str {
1747 str::from_bytes(with_bytes_writer(f))
1750 // Utility functions
1751 pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) ->
1753 let mut bpos = pos as int;
1754 let blen = len as int;
1756 SeekSet => bpos = offset,
1757 SeekCur => bpos += offset,
1758 SeekEnd => bpos = blen + offset
1760 if bpos < 0 { bpos = 0; } else if bpos > blen { bpos = blen; }
1761 return bpos as uint;
1764 pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
1765 do read_whole_file(file).chain |bytes| {
1766 if str::is_utf8(bytes) {
1767 Ok(str::from_bytes(bytes))
1769 Err(file.to_str() + " is not UTF-8")
1774 // FIXME (#2004): implement this in a low-level way. Going through the
1775 // abstractions is pointless.
1776 pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> {
1777 do file_reader(file).chain |rdr| {
1778 Ok(rdr.read_whole_stream())
1785 use io::{FILERes, FdRes, fd_t};
1788 use option::{None, Option, Some};
1792 // whatever fsync does on that platform
1795 // fdatasync on linux, similiar or more on other platforms
1800 // You must additionally sync the parent directory as well!
1805 // Artifacts that need to fsync on destruction
1811 pub fn new(arg: Arg<t>) -> Res<t> {
1816 #[unsafe_destructor]
1817 impl<T> Drop for Res<T> {
1819 match self.arg.opt_level {
1822 // fail hard if not succesful
1823 assert!(((self.arg.fsync_fn)(&self.arg.val, level) != -1));
1831 opt_level: Option<Level>,
1832 fsync_fn: @fn(f: &t, Level) -> int,
1835 // fsync file after executing blk
1836 // FIXME (#2004) find better way to create resources within lifetime of
1838 pub fn FILE_res_sync(file: &FILERes, opt_level: Option<Level>,
1839 blk: &fn(v: Res<*libc::FILE>)) {
1841 val: file.f, opt_level: opt_level,
1842 fsync_fn: |file, l| fsync_fd(fileno(*file), l)
1845 fn fileno(stream: *libc::FILE) -> libc::c_int {
1846 #[fixed_stack_segment]; #[inline(never)];
1847 unsafe { libc::fileno(stream) }
1851 // fsync fd after executing blk
1852 pub fn fd_res_sync(fd: &FdRes, opt_level: Option<Level>,
1853 blk: &fn(v: Res<fd_t>)) {
1855 val: fd.fd, opt_level: opt_level,
1856 fsync_fn: |fd, l| fsync_fd(*fd, l)
1860 fn fsync_fd(fd: libc::c_int, level: Level) -> int {
1861 #[fixed_stack_segment]; #[inline(never)];
1863 os::fsync_fd(fd, level) as int
1866 // Type of objects that may want to fsync
1867 pub trait FSyncable { fn fsync(&self, l: Level) -> int; }
1869 // Call o.fsync after executing blk
1870 pub fn obj_sync(o: @FSyncable, opt_level: Option<Level>,
1871 blk: &fn(v: Res<@FSyncable>)) {
1873 val: o, opt_level: opt_level,
1874 fsync_fn: |o, l| (*o).fsync(l)
1883 use io::{BytesWriter, SeekCur, SeekEnd, SeekSet};
1886 use result::{Ok, Err};
1892 let tmpfile = &Path("tmp/lib-io-test-simple.tmp");
1895 ~"A hoopy frood who really knows where his towel is.";
1896 debug!(frood.clone());
1898 let out = io::file_writer(tmpfile, [io::Create, io::Truncate]).unwrap();
1899 out.write_str(frood);
1901 let inp = io::file_reader(tmpfile).unwrap();
1902 let frood2: ~str = inp.read_c_str();
1903 debug!(frood2.clone());
1904 assert_eq!(frood, frood2);
1908 fn test_each_byte_each_char_file() {
1909 // Issue #5056 -- shouldn't include trailing EOF.
1910 let path = Path("tmp/lib-io-test-each-byte-each-char-file.tmp");
1913 // create empty, enough to reproduce a problem
1914 io::file_writer(&path, [io::Create]).unwrap();
1918 let file = io::file_reader(&path).unwrap();
1919 do file.each_byte() |_| {
1920 fail!("must be empty")
1925 let file = io::file_reader(&path).unwrap();
1926 do file.each_char() |_| {
1927 fail!("must be empty")
1933 fn test_readchars_empty() {
1934 do io::with_str_reader("") |inp| {
1935 let res : ~[char] = inp.read_chars(128);
1936 assert_eq!(res.len(), 0);
1941 fn test_read_line_utf8() {
1942 do io::with_str_reader("生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| {
1943 let line = inp.read_line();
1944 assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤");
1949 fn test_read_lines() {
1950 do io::with_str_reader("a\nb\nc\n") |inp| {
1951 assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1954 do io::with_str_reader("a\nb\nc") |inp| {
1955 assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1958 do io::with_str_reader("") |inp| {
1959 assert!(inp.read_lines().is_empty());
1964 fn test_readchars_wide() {
1965 let wide_test = ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤";
1966 let ivals : ~[int] = ~[
1967 29983, 38152, 30340, 27748,
1968 21273, 20999, 32905, 27748,
1969 104, 101, 108, 108, 111,
1970 29983, 38152, 30340, 27748,
1971 21273, 20999, 32905, 27748];
1972 fn check_read_ln(len : uint, s: &str, ivals: &[int]) {
1973 do io::with_str_reader(s) |inp| {
1974 let res : ~[char] = inp.read_chars(len);
1975 if len <= ivals.len() {
1976 assert_eq!(res.len(), len);
1978 for (iv, c) in ivals.iter().zip(res.iter()) {
1979 assert!(*iv == *c as int)
1985 check_read_ln(i, wide_test, ivals);
1988 // check a long read for good measure
1989 check_read_ln(128, wide_test, ivals);
1993 fn test_readchar() {
1994 do io::with_str_reader("生") |inp| {
1995 let res : char = inp.read_char();
1996 assert_eq!(res as int, 29983);
2001 fn test_readchar_empty() {
2002 do io::with_str_reader("") |inp| {
2003 let res : char = inp.read_char();
2004 assert_eq!(res as int, -1);
2009 fn file_reader_not_exist() {
2010 match io::file_reader(&Path("not a file")) {
2012 assert_eq!(e, ~"error opening not a file");
2020 #[ignore(cfg(windows))]
2021 fn test_read_buffer_too_small() {
2022 let path = &Path("tmp/lib-io-test-read-buffer-too-small.tmp");
2023 // ensure the file exists
2024 io::file_writer(path, [io::Create]).unwrap();
2026 let file = io::file_reader(path).unwrap();
2027 let mut buf = vec::from_elem(5, 0u8);
2028 file.read(buf, 6); // this should fail because buf is too small
2032 fn test_read_buffer_big_enough() {
2033 let path = &Path("tmp/lib-io-test-read-buffer-big-enough.tmp");
2034 // ensure the file exists
2035 io::file_writer(path, [io::Create]).unwrap();
2037 let file = io::file_reader(path).unwrap();
2038 let mut buf = vec::from_elem(5, 0u8);
2039 file.read(buf, 4); // this should succeed because buf is big enough
2043 fn test_write_empty() {
2044 let file = io::file_writer(&Path("tmp/lib-io-test-write-empty.tmp"),
2045 [io::Create]).unwrap();
2050 fn file_writer_bad_name() {
2051 match io::file_writer(&Path("?/?"), []) {
2053 assert!(e.starts_with("error opening"));
2060 fn buffered_file_writer_bad_name() {
2061 match io::buffered_file_writer(&Path("?/?")) {
2063 assert!(e.starts_with("error opening"));
2070 fn bytes_buffer_overwrite() {
2071 let wr = BytesWriter::new();
2072 wr.write([0u8, 1u8, 2u8, 3u8]);
2073 assert!(*wr.bytes == ~[0u8, 1u8, 2u8, 3u8]);
2074 wr.seek(-2, SeekCur);
2075 wr.write([4u8, 5u8, 6u8, 7u8]);
2076 assert!(*wr.bytes == ~[0u8, 1u8, 4u8, 5u8, 6u8, 7u8]);
2077 wr.seek(-2, SeekEnd);
2079 wr.seek(1, SeekSet);
2081 assert!(*wr.bytes == ~[0u8, 9u8, 4u8, 5u8, 8u8, 7u8]);
2085 fn test_read_write_le() {
2086 let path = Path("tmp/lib-io-test-read-write-le.tmp");
2087 let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2089 // write the ints to the file
2091 let file = io::file_writer(&path, [io::Create]).unwrap();
2092 for i in uints.iter() {
2093 file.write_le_u64(*i);
2097 // then read them back and check that they are the same
2099 let file = io::file_reader(&path).unwrap();
2100 for i in uints.iter() {
2101 assert_eq!(file.read_le_u64(), *i);
2107 fn test_read_write_be() {
2108 let path = Path("tmp/lib-io-test-read-write-be.tmp");
2109 let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2111 // write the ints to the file
2113 let file = io::file_writer(&path, [io::Create]).unwrap();
2114 for i in uints.iter() {
2115 file.write_be_u64(*i);
2119 // then read them back and check that they are the same
2121 let file = io::file_reader(&path).unwrap();
2122 for i in uints.iter() {
2123 assert_eq!(file.read_be_u64(), *i);
2129 fn test_read_be_int_n() {
2130 let path = Path("tmp/lib-io-test-read-be-int-n.tmp");
2131 let ints = [i32::min_value, -123456, -42, -5, 0, 1, i32::max_value];
2133 // write the ints to the file
2135 let file = io::file_writer(&path, [io::Create]).unwrap();
2136 for i in ints.iter() {
2137 file.write_be_i32(*i);
2141 // then read them back and check that they are the same
2143 let file = io::file_reader(&path).unwrap();
2144 for i in ints.iter() {
2145 // this tests that the sign extension is working
2146 // (comparing the values as i32 would not test this)
2147 assert_eq!(file.read_be_int_n(4), *i as i64);
2153 fn test_read_f32() {
2154 let path = Path("tmp/lib-io-test-read-f32.tmp");
2155 //big-endian floating-point 8.1250
2156 let buf = ~[0x41, 0x02, 0x00, 0x00];
2159 let file = io::file_writer(&path, [io::Create]).unwrap();
2164 let file = io::file_reader(&path).unwrap();
2165 let f = file.read_be_f32();
2166 assert_eq!(f, 8.1250);
2171 fn test_read_write_f32() {
2172 let path = Path("tmp/lib-io-test-read-write-f32.tmp");
2176 let file = io::file_writer(&path, [io::Create]).unwrap();
2177 file.write_be_f32(f);
2178 file.write_le_f32(f);
2182 let file = io::file_reader(&path).unwrap();
2183 assert_eq!(file.read_be_f32(), 8.1250);
2184 assert_eq!(file.read_le_f32(), 8.1250);