]> git.lizzy.rs Git - rust.git/blob - src/libstd/io.rs
Find the cratemap at runtime on windows.
[rust.git] / src / libstd / io.rs
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.
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 /*!
12
13 The `io` module contains basic input and output routines.
14
15 A quick summary:
16
17 ## `Reader` and `Writer` traits
18
19 These traits define the minimal set of methods that anything that can do
20 input and output should implement.
21
22 ## `ReaderUtil` and `WriterUtil` traits
23
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
26 line, for example.
27
28 Generally, these richer methods are probably the ones you want to actually
29 use in day-to-day Rust.
30
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.
34
35 ## `print` and `println`
36
37 These very useful functions are defined here. You generally don't need to
38 import them, though, as the prelude already does.
39
40 ## `stdin`, `stdout`, and `stderr`
41
42 These functions return references to the classic three file descriptors. They
43 implement `Reader` and `Writer`, where appropriate.
44
45 */
46
47 #[allow(missing_doc)];
48
49 use cast;
50 use cast::transmute;
51 use clone::Clone;
52 use c_str::ToCStr;
53 use container::Container;
54 use int;
55 use iter::Iterator;
56 use libc::consts::os::posix88::*;
57 use libc::{c_int, c_void, size_t};
58 use libc;
59 use num;
60 use ops::Drop;
61 use option::{Some, None};
62 use os;
63 use path::Path;
64 use ptr;
65 use result::{Result, Ok, Err};
66 use str::{StrSlice, OwnedStr};
67 use str;
68 use to_str::ToStr;
69 use uint;
70 use vec::{MutableVector, ImmutableVector, OwnedVector, OwnedCopyableVector, CopyableVector};
71 use vec;
72
73 #[allow(non_camel_case_types)] // not sure what to do about this
74 pub type fd_t = c_int;
75
76 pub mod rustrt {
77     use libc;
78
79     #[abi = "cdecl"]
80     #[link_name = "rustrt"]
81     extern {
82         pub fn rust_get_stdin() -> *libc::FILE;
83         pub fn rust_get_stdout() -> *libc::FILE;
84         pub fn rust_get_stderr() -> *libc::FILE;
85     }
86 }
87
88 // Reading
89
90 // FIXME (#2004): This is all buffered. We might need an unbuffered variant
91 // as well
92 /**
93 * The SeekStyle enum describes the relationship between the position
94 * we'd like to seek to from our current position. It's used as an argument
95 * to the `seek` method defined on the `Reader` trait.
96 *
97 * There are three seek styles:
98 *
99 * 1. `SeekSet` means that the new position should become our position.
100 * 2. `SeekCur` means that we should seek from the current position.
101 * 3. `SeekEnd` means that we should seek from the end.
102 *
103 * # Examples
104 *
105 * None right now.
106 */
107 pub enum SeekStyle { SeekSet, SeekEnd, SeekCur, }
108
109
110 /**
111 * The core Reader trait. All readers must implement this trait.
112 *
113 * # Examples
114 *
115 * None right now.
116 */
117 pub trait Reader {
118     // FIXME (#2004): Seekable really should be orthogonal.
119
120     // FIXME (#2982): This should probably return an error.
121     /**
122     * Reads bytes and puts them into `bytes`, advancing the cursor. Returns the
123     * number of bytes read.
124     *
125     * The number of bytes to be read is `len` or the end of the file,
126     * whichever comes first.
127     *
128     * The buffer must be at least `len` bytes long.
129     *
130     * `read` is conceptually similar to C's `fread` function.
131     *
132     * # Examples
133     *
134     * None right now.
135     */
136     fn read(&self, bytes: &mut [u8], len: uint) -> uint;
137
138     /**
139     * Reads a single byte, advancing the cursor.
140     *
141     * In the case of an EOF or an error, returns a negative value.
142     *
143     * `read_byte` is conceptually similar to C's `getc` function.
144     *
145     * # Examples
146     *
147     * None right now.
148     */
149     fn read_byte(&self) -> int;
150
151     /**
152     * Returns a boolean value: are we currently at EOF?
153     *
154     * Note that stream position may be already at the end-of-file point,
155     * but `eof` returns false until an attempt to read at that position.
156     *
157     * `eof` is conceptually similar to C's `feof` function.
158     *
159     * # Examples
160     *
161     * None right now.
162     */
163     fn eof(&self) -> bool;
164
165     /**
166     * Seek to a given `position` in the stream.
167     *
168     * Takes an optional SeekStyle, which affects how we seek from the
169     * position. See `SeekStyle` docs for more details.
170     *
171     * `seek` is conceptually similar to C's `fseek` function.
172     *
173     * # Examples
174     *
175     * None right now.
176     */
177     fn seek(&self, position: int, style: SeekStyle);
178
179     /**
180     * Returns the current position within the stream.
181     *
182     * `tell` is conceptually similar to C's `ftell` function.
183     *
184     * # Examples
185     *
186     * None right now.
187     */
188     fn tell(&self) -> uint;
189 }
190
191 impl Reader for @Reader {
192     fn read(&self, bytes: &mut [u8], len: uint) -> uint {
193         self.read(bytes, len)
194     }
195     fn read_byte(&self) -> int {
196         self.read_byte()
197     }
198     fn eof(&self) -> bool {
199         self.eof()
200     }
201     fn seek(&self, position: int, style: SeekStyle) {
202         self.seek(position, style)
203     }
204     fn tell(&self) -> uint {
205         self.tell()
206     }
207 }
208
209 /**
210 * The `ReaderUtil` trait is a home for many of the utility functions
211 * a particular Reader should implement.
212 *
213 * The default `Reader` trait is focused entirely on bytes. `ReaderUtil` is based
214 * on higher-level concepts like 'chars' and 'lines.'
215 *
216 * # Examples:
217 *
218 * None right now.
219 */
220 pub trait ReaderUtil {
221
222     /**
223     * Reads `len` number of bytes, and gives you a new vector back.
224     *
225     * # Examples
226     *
227     * None right now.
228     */
229     fn read_bytes(&self, len: uint) -> ~[u8];
230
231     /**
232     * Reads up until a specific byte is seen or EOF.
233     *
234     * The `include` parameter specifies if the character should be included
235     * in the returned string.
236     *
237     * # Examples
238     *
239     * None right now.
240     */
241     fn read_until(&self, c: u8, include: bool) -> ~str;
242
243     /**
244     * Reads up until the first '\n' or EOF.
245     *
246     * The '\n' is not included in the result.
247     *
248     * # Examples
249     *
250     * None right now.
251     */
252     fn read_line(&self) -> ~str;
253
254     /**
255     * Reads `n` chars.
256     *
257     * Assumes that those chars are UTF-8 encoded.
258     *
259     * The '\n' is not included in the result.
260     *
261     * # Examples
262     *
263     * None right now.
264     */
265     fn read_chars(&self, n: uint) -> ~[char];
266
267     /**
268     * Reads a single UTF-8 encoded char.
269     *
270     * # Examples
271     *
272     * None right now.
273     */
274     fn read_char(&self) -> char;
275
276     /**
277     * Reads up until the first null byte or EOF.
278     *
279     * The null byte is not returned.
280     *
281     * # Examples
282     *
283     * None right now.
284     */
285     fn read_c_str(&self) -> ~str;
286
287     /**
288     * Reads all remaining data in the stream.
289     *
290     * # Examples
291     *
292     * None right now.
293     */
294     fn read_whole_stream(&self) -> ~[u8];
295
296     /**
297     * Iterate over every byte until EOF or the iterator breaks.
298     *
299     * # Examples
300     *
301     * None right now.
302     */
303     fn each_byte(&self, it: &fn(int) -> bool) -> bool;
304
305     /**
306     * Iterate over every char until EOF or the iterator breaks.
307     *
308     * # Examples
309     *
310     * None right now.
311     */
312     fn each_char(&self, it: &fn(char) -> bool) -> bool;
313
314     /**
315     * Iterate over every line until EOF or the iterator breaks.
316     *
317     * # Examples
318     *
319     * None right now.
320     */
321     fn each_line(&self, it: &fn(&str) -> bool) -> bool;
322
323     /**
324     * Reads all of the lines in the stream.
325     *
326     * Returns a vector of those lines.
327     *
328     * # Examples
329     *
330     * None right now.
331     */
332     fn read_lines(&self) -> ~[~str];
333
334     /**
335     * Reads `n` little-endian unsigned integer bytes.
336     *
337     * `n` must be between 1 and 8, inclusive.
338     *
339     * # Examples
340     *
341     * None right now.
342     */
343     fn read_le_uint_n(&self, nbytes: uint) -> u64;
344
345     /**
346     * Reads `n` little-endian signed integer bytes.
347     *
348     * `n` must be between 1 and 8, inclusive.
349     *
350     * # Examples
351     *
352     * None right now.
353     */
354     fn read_le_int_n(&self, nbytes: uint) -> i64;
355
356     /**
357     * Reads `n` big-endian unsigned integer bytes.
358     *
359     * `n` must be between 1 and 8, inclusive.
360     *
361     * # Examples
362     *
363     * None right now.
364     */
365     fn read_be_uint_n(&self, nbytes: uint) -> u64;
366
367     /**
368     * Reads `n` big-endian signed integer bytes.
369     *
370     * `n` must be between 1 and 8, inclusive.
371     *
372     * # Examples
373     *
374     * None right now.
375     */
376     fn read_be_int_n(&self, nbytes: uint) -> i64;
377
378     /**
379     * Reads a little-endian unsigned integer.
380     *
381     * The number of bytes returned is system-dependant.
382     *
383     * # Examples
384     *
385     * None right now.
386     */
387     fn read_le_uint(&self) -> uint;
388
389     /**
390     * Reads a little-endian integer.
391     *
392     * The number of bytes returned is system-dependant.
393     *
394     * # Examples
395     *
396     * None right now.
397     */
398     fn read_le_int(&self) -> int;
399
400     /**
401     * Reads a big-endian unsigned integer.
402     *
403     * The number of bytes returned is system-dependant.
404     *
405     * # Examples
406     *
407     * None right now.
408     */
409     fn read_be_uint(&self) -> uint;
410
411     /**
412     * Reads a big-endian integer.
413     *
414     * The number of bytes returned is system-dependant.
415     *
416     * # Examples
417     *
418     * None right now.
419     */
420     fn read_be_int(&self) -> int;
421
422     /**
423     * Reads a big-endian `u64`.
424     *
425     * `u64`s are 8 bytes long.
426     *
427     * # Examples
428     *
429     * None right now.
430     */
431     fn read_be_u64(&self) -> u64;
432
433     /**
434     * Reads a big-endian `u32`.
435     *
436     * `u32`s are 4 bytes long.
437     *
438     * # Examples
439     *
440     * None right now.
441     */
442     fn read_be_u32(&self) -> u32;
443
444     /**
445     * Reads a big-endian `u16`.
446     *
447     * `u16`s are 2 bytes long.
448     *
449     * # Examples
450     *
451     * None right now.
452     */
453     fn read_be_u16(&self) -> u16;
454
455     /**
456     * Reads a big-endian `i64`.
457     *
458     * `i64`s are 8 bytes long.
459     *
460     * # Examples
461     *
462     * None right now.
463     */
464     fn read_be_i64(&self) -> i64;
465
466     /**
467     * Reads a big-endian `i32`.
468     *
469     * `i32`s are 4 bytes long.
470     *
471     * # Examples
472     *
473     * None right now.
474     */
475     fn read_be_i32(&self) -> i32;
476
477     /**
478     * Reads a big-endian `i16`.
479     *
480     * `i16`s are 2 bytes long.
481     *
482     * # Examples
483     *
484     * None right now.
485     */
486     fn read_be_i16(&self) -> i16;
487
488     /**
489     * Reads a big-endian `f64`.
490     *
491     * `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
492     *
493     * # Examples
494     *
495     * None right now.
496     */
497     fn read_be_f64(&self) -> f64;
498
499     /**
500     * Reads a big-endian `f32`.
501     *
502     * `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
503     *
504     * # Examples
505     *
506     * None right now.
507     */
508     fn read_be_f32(&self) -> f32;
509
510     /**
511     * Reads a little-endian `u64`.
512     *
513     * `u64`s are 8 bytes long.
514     *
515     * # Examples
516     *
517     * None right now.
518     */
519     fn read_le_u64(&self) -> u64;
520
521     /**
522     * Reads a little-endian `u32`.
523     *
524     * `u32`s are 4 bytes long.
525     *
526     * # Examples
527     *
528     * None right now.
529     */
530     fn read_le_u32(&self) -> u32;
531
532     /**
533     * Reads a little-endian `u16`.
534     *
535     * `u16`s are 2 bytes long.
536     *
537     * # Examples
538     *
539     * None right now.
540     */
541     fn read_le_u16(&self) -> u16;
542
543     /**
544     * Reads a little-endian `i64`.
545     *
546     * `i64`s are 8 bytes long.
547     *
548     * # Examples
549     *
550     * None right now.
551     */
552     fn read_le_i64(&self) -> i64;
553
554     /**
555     * Reads a little-endian `i32`.
556     *
557     * `i32`s are 4 bytes long.
558     *
559     * # Examples
560     *
561     * None right now.
562     */
563     fn read_le_i32(&self) -> i32;
564
565     /**
566     * Reads a little-endian `i16`.
567     *
568     * `i16`s are 2 bytes long.
569     *
570     * # Examples
571     *
572     * None right now.
573     */
574     fn read_le_i16(&self) -> i16;
575
576     /**
577     * Reads a little-endian `f64`.
578     *
579     * `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
580     *
581     * # Examples
582     *
583     * None right now.
584     */
585     fn read_le_f64(&self) -> f64;
586
587     /**
588     * Reads a little-endian `f32`.
589     *
590     * `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
591     *
592     * # Examples
593     *
594     * None right now.
595     */
596     fn read_le_f32(&self) -> f32;
597
598     /**
599     * Read a u8.
600     *
601     * `u8`s are 1 byte.
602     *
603     * # Examples
604     *
605     * None right now.
606     */
607     fn read_u8(&self) -> u8;
608
609     /**
610     * Read an i8.
611     *
612     * `i8`s are 1 byte.
613     *
614     * # Examples
615     *
616     * None right now.
617     */
618     fn read_i8(&self) -> i8;
619 }
620
621 impl<T:Reader> ReaderUtil for T {
622
623     fn read_bytes(&self, len: uint) -> ~[u8] {
624         let mut bytes = vec::with_capacity(len);
625         unsafe { vec::raw::set_len(&mut bytes, len); }
626
627         let count = self.read(bytes, len);
628
629         unsafe { vec::raw::set_len(&mut bytes, count); }
630         bytes
631     }
632
633     fn read_until(&self, c: u8, include: bool) -> ~str {
634         let mut bytes = ~[];
635         loop {
636             let ch = self.read_byte();
637             if ch == -1 || ch == c as int {
638                 if include && ch == c as int {
639                     bytes.push(ch as u8);
640                 }
641                 break;
642             }
643             bytes.push(ch as u8);
644         }
645         str::from_utf8(bytes)
646     }
647
648     fn read_line(&self) -> ~str {
649         self.read_until('\n' as u8, false)
650     }
651
652     fn read_chars(&self, n: uint) -> ~[char] {
653         // returns the (consumed offset, n_req), appends characters to &chars
654         fn chars_from_utf8<T:Reader>(bytes: &~[u8], chars: &mut ~[char])
655             -> (uint, uint) {
656             let mut i = 0;
657             let bytes_len = bytes.len();
658             while i < bytes_len {
659                 let b0 = bytes[i];
660                 let w = str::utf8_char_width(b0);
661                 let end = i + w;
662                 i += 1;
663                 assert!((w > 0));
664                 if w == 1 {
665                     unsafe {
666                         chars.push(transmute(b0 as u32));
667                     }
668                     loop;
669                 }
670                 // can't satisfy this char with the existing data
671                 if end > bytes_len {
672                     return (i - 1, end - bytes_len);
673                 }
674                 let mut val = 0;
675                 while i < end {
676                     let next = bytes[i] as int;
677                     i += 1;
678                     assert!((next > -1));
679                     assert_eq!(next & 192, 128);
680                     val <<= 6;
681                     val += (next & 63) as uint;
682                 }
683                 // See str::StrSlice::char_at
684                 val += ((b0 << ((w + 1) as u8)) as uint)
685                     << (w - 1) * 6 - w - 1u;
686                 unsafe {
687                     chars.push(transmute(val as u32));
688                 }
689             }
690             return (i, 0);
691         }
692         let mut bytes = ~[];
693         let mut chars = ~[];
694         // might need more bytes, but reading n will never over-read
695         let mut nbread = n;
696         while nbread > 0 {
697             let data = self.read_bytes(nbread);
698             if data.is_empty() {
699                 // eof - FIXME (#2004): should we do something if
700                 // we're split in a unicode char?
701                 break;
702             }
703             bytes.push_all(data);
704             let (offset, nbreq) = chars_from_utf8::<T>(&bytes, &mut chars);
705             let ncreq = n - chars.len();
706             // again we either know we need a certain number of bytes
707             // to complete a character, or we make sure we don't
708             // over-read by reading 1-byte per char needed
709             nbread = if ncreq > nbreq { ncreq } else { nbreq };
710             if nbread > 0 {
711                 bytes = bytes.slice(offset, bytes.len()).to_owned();
712             }
713         }
714         chars
715     }
716
717     fn read_char(&self) -> char {
718         let c = self.read_chars(1);
719         if c.len() == 0 {
720             return unsafe { transmute(-1u32) }; // FIXME: #8971: unsound
721         }
722         assert_eq!(c.len(), 1);
723         return c[0];
724     }
725
726     fn read_c_str(&self) -> ~str {
727         self.read_until(0u8, false)
728     }
729
730     fn read_whole_stream(&self) -> ~[u8] {
731         let mut bytes: ~[u8] = ~[];
732         while !self.eof() { bytes.push_all(self.read_bytes(2048u)); }
733         bytes
734     }
735
736     fn each_byte(&self, it: &fn(int) -> bool) -> bool {
737         loop {
738             match self.read_byte() {
739                 -1 => break,
740                 ch => if !it(ch) { return false; }
741             }
742         }
743         return true;
744     }
745
746     fn each_char(&self, it: &fn(char) -> bool) -> bool {
747         // FIXME: #8971: unsound
748         let eof: char = unsafe { transmute(-1u32) };
749         loop {
750             match self.read_char() {
751                 c if c == eof => break,
752                 ch => if !it(ch) { return false; }
753             }
754         }
755         return true;
756     }
757
758     fn each_line(&self, it: &fn(s: &str) -> bool) -> bool {
759         while !self.eof() {
760             // include the \n, so that we can distinguish an entirely empty
761             // line read after "...\n", and the trailing empty line in
762             // "...\n\n".
763             let mut line = self.read_until('\n' as u8, true);
764
765             // blank line at the end of the reader is ignored
766             if self.eof() && line.is_empty() { break; }
767
768             // trim the \n, so that each_line is consistent with read_line
769             let n = line.len();
770             if line[n-1] == '\n' as u8 {
771                 unsafe { str::raw::set_len(&mut line, n-1); }
772             }
773
774             if !it(line) { return false; }
775         }
776         return true;
777     }
778
779     fn read_lines(&self) -> ~[~str] {
780         do vec::build(None) |push| {
781             do self.each_line |line| {
782                 push(line.to_owned());
783                 true
784             };
785         }
786     }
787
788     // FIXME int reading methods need to deal with eof - issue #2004
789
790     fn read_le_uint_n(&self, nbytes: uint) -> u64 {
791         assert!(nbytes > 0 && nbytes <= 8);
792
793         let mut val = 0u64;
794         let mut pos = 0;
795         let mut i = nbytes;
796         while i > 0 {
797             val += (self.read_u8() as u64) << pos;
798             pos += 8;
799             i -= 1;
800         }
801         val
802     }
803
804     fn read_le_int_n(&self, nbytes: uint) -> i64 {
805         extend_sign(self.read_le_uint_n(nbytes), nbytes)
806     }
807
808     fn read_be_uint_n(&self, nbytes: uint) -> u64 {
809         assert!(nbytes > 0 && nbytes <= 8);
810
811         let mut val = 0u64;
812         let mut i = nbytes;
813         while i > 0 {
814             i -= 1;
815             val += (self.read_u8() as u64) << i * 8;
816         }
817         val
818     }
819
820     fn read_be_int_n(&self, nbytes: uint) -> i64 {
821         extend_sign(self.read_be_uint_n(nbytes), nbytes)
822     }
823
824     fn read_le_uint(&self) -> uint {
825         self.read_le_uint_n(uint::bytes) as uint
826     }
827
828     fn read_le_int(&self) -> int {
829         self.read_le_int_n(int::bytes) as int
830     }
831
832     fn read_be_uint(&self) -> uint {
833         self.read_be_uint_n(uint::bytes) as uint
834     }
835
836     fn read_be_int(&self) -> int {
837         self.read_be_int_n(int::bytes) as int
838     }
839
840     fn read_be_u64(&self) -> u64 {
841         self.read_be_uint_n(8) as u64
842     }
843
844     fn read_be_u32(&self) -> u32 {
845         self.read_be_uint_n(4) as u32
846     }
847
848     fn read_be_u16(&self) -> u16 {
849         self.read_be_uint_n(2) as u16
850     }
851
852     fn read_be_i64(&self) -> i64 {
853         self.read_be_int_n(8) as i64
854     }
855
856     fn read_be_i32(&self) -> i32 {
857         self.read_be_int_n(4) as i32
858     }
859
860     fn read_be_i16(&self) -> i16 {
861         self.read_be_int_n(2) as i16
862     }
863
864     fn read_be_f64(&self) -> f64 {
865         unsafe {
866             cast::transmute::<u64, f64>(self.read_be_u64())
867         }
868     }
869
870     fn read_be_f32(&self) -> f32 {
871         unsafe {
872             cast::transmute::<u32, f32>(self.read_be_u32())
873         }
874     }
875
876     fn read_le_u64(&self) -> u64 {
877         self.read_le_uint_n(8) as u64
878     }
879
880     fn read_le_u32(&self) -> u32 {
881         self.read_le_uint_n(4) as u32
882     }
883
884     fn read_le_u16(&self) -> u16 {
885         self.read_le_uint_n(2) as u16
886     }
887
888     fn read_le_i64(&self) -> i64 {
889         self.read_le_int_n(8) as i64
890     }
891
892     fn read_le_i32(&self) -> i32 {
893         self.read_le_int_n(4) as i32
894     }
895
896     fn read_le_i16(&self) -> i16 {
897         self.read_le_int_n(2) as i16
898     }
899
900     fn read_le_f64(&self) -> f64 {
901         unsafe {
902             cast::transmute::<u64, f64>(self.read_le_u64())
903         }
904     }
905
906     fn read_le_f32(&self) -> f32 {
907         unsafe {
908             cast::transmute::<u32, f32>(self.read_le_u32())
909         }
910     }
911
912     fn read_u8(&self) -> u8 {
913         self.read_byte() as u8
914     }
915
916     fn read_i8(&self) -> i8 {
917         self.read_byte() as i8
918     }
919 }
920
921 fn extend_sign(val: u64, nbytes: uint) -> i64 {
922     let shift = (8 - nbytes) * 8;
923     (val << shift) as i64 >> shift
924 }
925
926 // Reader implementations
927
928 fn convert_whence(whence: SeekStyle) -> i32 {
929     return match whence {
930       SeekSet => 0i32,
931       SeekCur => 1i32,
932       SeekEnd => 2i32
933     };
934 }
935
936 impl Reader for *libc::FILE {
937     fn read(&self, bytes: &mut [u8], len: uint) -> uint {
938         #[fixed_stack_segment]; #[inline(never)];
939
940         unsafe {
941             do bytes.as_mut_buf |buf_p, buf_len| {
942                 assert!(buf_len >= len);
943
944                 let count = libc::fread(buf_p as *mut c_void, 1u as size_t,
945                                         len as size_t, *self) as uint;
946                 if count < len {
947                   match libc::ferror(*self) {
948                     0 => (),
949                     _ => {
950                       error!("error reading buffer");
951                       error!("%s", os::last_os_error());
952                       fail!();
953                     }
954                   }
955                 }
956
957                 count
958             }
959         }
960     }
961     fn read_byte(&self) -> int {
962         #[fixed_stack_segment]; #[inline(never)];
963
964         unsafe {
965             libc::fgetc(*self) as int
966         }
967     }
968     fn eof(&self) -> bool {
969         #[fixed_stack_segment]; #[inline(never)];
970
971         unsafe {
972             return libc::feof(*self) != 0 as c_int;
973         }
974     }
975     fn seek(&self, offset: int, whence: SeekStyle) {
976         #[fixed_stack_segment]; #[inline(never)];
977
978         unsafe {
979             assert!(libc::fseek(*self,
980                                      offset as libc::c_long,
981                                      convert_whence(whence)) == 0 as c_int);
982         }
983     }
984     fn tell(&self) -> uint {
985         #[fixed_stack_segment]; #[inline(never)];
986
987         unsafe {
988             return libc::ftell(*self) as uint;
989         }
990     }
991 }
992
993 struct Wrapper<T, C> {
994     base: T,
995     cleanup: C,
996 }
997
998 // A forwarding impl of reader that also holds on to a resource for the
999 // duration of its lifetime.
1000 // FIXME there really should be a better way to do this // #2004
1001 impl<R:Reader,C> Reader for Wrapper<R, C> {
1002     fn read(&self, bytes: &mut [u8], len: uint) -> uint {
1003         self.base.read(bytes, len)
1004     }
1005     fn read_byte(&self) -> int { self.base.read_byte() }
1006     fn eof(&self) -> bool { self.base.eof() }
1007     fn seek(&self, off: int, whence: SeekStyle) {
1008         self.base.seek(off, whence)
1009     }
1010     fn tell(&self) -> uint { self.base.tell() }
1011 }
1012
1013 pub struct FILERes {
1014     f: *libc::FILE,
1015 }
1016
1017 impl FILERes {
1018     pub fn new(f: *libc::FILE) -> FILERes {
1019         FILERes { f: f }
1020     }
1021 }
1022
1023 impl Drop for FILERes {
1024     fn drop(&mut self) {
1025         #[fixed_stack_segment]; #[inline(never)];
1026
1027         unsafe {
1028             libc::fclose(self.f);
1029         }
1030     }
1031 }
1032
1033 pub fn FILE_reader(f: *libc::FILE, cleanup: bool) -> @Reader {
1034     if cleanup {
1035         @Wrapper { base: f, cleanup: FILERes::new(f) } as @Reader
1036     } else {
1037         @f as @Reader
1038     }
1039 }
1040
1041 // FIXME (#2004): this should either be an trait-less impl, a set of
1042 // top-level functions that take a reader, or a set of default methods on
1043 // reader (which can then be called reader)
1044
1045 /**
1046 * Gives a `Reader` that allows you to read values from standard input.
1047 *
1048 * # Example
1049 *
1050 * ~~~ {.rust}
1051 * let stdin = std::io::stdin();
1052 * let line = stdin.read_line();
1053 * std::io::print(line);
1054 * ~~~
1055 */
1056 pub fn stdin() -> @Reader {
1057     #[fixed_stack_segment]; #[inline(never)];
1058
1059     unsafe {
1060         @rustrt::rust_get_stdin() as @Reader
1061     }
1062 }
1063
1064 pub fn file_reader(path: &Path) -> Result<@Reader, ~str> {
1065     #[fixed_stack_segment]; #[inline(never)];
1066
1067     let f = do path.with_c_str |pathbuf| {
1068         do "rb".with_c_str |modebuf| {
1069             unsafe { libc::fopen(pathbuf, modebuf as *libc::c_char) }
1070         }
1071     };
1072
1073     if f as uint == 0u {
1074         Err(~"error opening " + path.to_str())
1075     } else {
1076         Ok(FILE_reader(f, true))
1077     }
1078 }
1079
1080
1081 // Byte readers
1082 pub struct BytesReader {
1083     // FIXME(#5723) see other FIXME below
1084     // FIXME(#7268) this should also be parameterized over <'self>
1085     bytes: &'static [u8],
1086     pos: @mut uint
1087 }
1088
1089 impl Reader for BytesReader {
1090     fn read(&self, bytes: &mut [u8], len: uint) -> uint {
1091         let count = num::min(len, self.bytes.len() - *self.pos);
1092
1093         let view = self.bytes.slice(*self.pos, self.bytes.len());
1094         vec::bytes::copy_memory(bytes, view, count);
1095
1096         *self.pos += count;
1097
1098         count
1099     }
1100
1101     fn read_byte(&self) -> int {
1102         if *self.pos == self.bytes.len() {
1103             return -1;
1104         }
1105
1106         let b = self.bytes[*self.pos];
1107         *self.pos += 1u;
1108         b as int
1109     }
1110
1111     fn eof(&self) -> bool {
1112         *self.pos == self.bytes.len()
1113     }
1114
1115     fn seek(&self, offset: int, whence: SeekStyle) {
1116         let pos = *self.pos;
1117         *self.pos = seek_in_buf(offset, pos, self.bytes.len(), whence);
1118     }
1119
1120     fn tell(&self) -> uint {
1121         *self.pos
1122     }
1123 }
1124
1125 pub fn with_bytes_reader<T>(bytes: &[u8], f: &fn(@Reader) -> T) -> T {
1126     // XXX XXX XXX this is glaringly unsound
1127     // FIXME(#5723) Use a &Reader for the callback's argument. Should be:
1128     // fn with_bytes_reader<'r, T>(bytes: &'r [u8], f: &fn(&'r Reader) -> T) -> T
1129     let bytes: &'static [u8] = unsafe { cast::transmute(bytes) };
1130     f(@BytesReader {
1131         bytes: bytes,
1132         pos: @mut 0
1133     } as @Reader)
1134 }
1135
1136 pub fn with_str_reader<T>(s: &str, f: &fn(@Reader) -> T) -> T {
1137     // FIXME(#5723): As above.
1138     with_bytes_reader(s.as_bytes(), f)
1139 }
1140
1141 // Writing
1142 pub enum FileFlag { Append, Create, Truncate, NoFlag, }
1143
1144 // What type of writer are we?
1145 #[deriving(Eq)]
1146 pub enum WriterType { Screen, File }
1147
1148 // FIXME (#2004): Seekable really should be orthogonal.
1149 // FIXME (#2004): eventually u64
1150 /// The raw underlying writer trait. All writers must implement this.
1151 pub trait Writer {
1152
1153     /// Write all of the given bytes.
1154     fn write(&self, v: &[u8]);
1155
1156     /// Move the current position within the stream. The second parameter
1157     /// determines the position that the first parameter is relative to.
1158     fn seek(&self, int, SeekStyle);
1159
1160     /// Return the current position within the stream.
1161     fn tell(&self) -> uint;
1162
1163     /// Flush the output buffer for this stream (if there is one).
1164     fn flush(&self) -> int;
1165
1166     /// Determine if this Writer is writing to a file or not.
1167     fn get_type(&self) -> WriterType;
1168 }
1169
1170 impl Writer for @Writer {
1171     fn write(&self, v: &[u8]) { self.write(v) }
1172     fn seek(&self, a: int, b: SeekStyle) { self.seek(a, b) }
1173     fn tell(&self) -> uint { self.tell() }
1174     fn flush(&self) -> int { self.flush() }
1175     fn get_type(&self) -> WriterType { self.get_type() }
1176 }
1177
1178 impl<W:Writer,C> Writer for Wrapper<W, C> {
1179     fn write(&self, bs: &[u8]) { self.base.write(bs); }
1180     fn seek(&self, off: int, style: SeekStyle) { self.base.seek(off, style); }
1181     fn tell(&self) -> uint { self.base.tell() }
1182     fn flush(&self) -> int { self.base.flush() }
1183     fn get_type(&self) -> WriterType { File }
1184 }
1185
1186 impl Writer for *libc::FILE {
1187     fn write(&self, v: &[u8]) {
1188         #[fixed_stack_segment]; #[inline(never)];
1189
1190         unsafe {
1191             do v.as_imm_buf |vbuf, len| {
1192                 let nout = libc::fwrite(vbuf as *c_void,
1193                                         1,
1194                                         len as size_t,
1195                                         *self);
1196                 if nout != len as size_t {
1197                     error!("error writing buffer");
1198                     error!("%s", os::last_os_error());
1199                     fail!();
1200                 }
1201             }
1202         }
1203     }
1204     fn seek(&self, offset: int, whence: SeekStyle) {
1205         #[fixed_stack_segment]; #[inline(never)];
1206
1207         unsafe {
1208             assert!(libc::fseek(*self,
1209                                      offset as libc::c_long,
1210                                      convert_whence(whence)) == 0 as c_int);
1211         }
1212     }
1213     fn tell(&self) -> uint {
1214         #[fixed_stack_segment]; #[inline(never)];
1215
1216         unsafe {
1217             libc::ftell(*self) as uint
1218         }
1219     }
1220     fn flush(&self) -> int {
1221         #[fixed_stack_segment]; #[inline(never)];
1222
1223         unsafe {
1224             libc::fflush(*self) as int
1225         }
1226     }
1227     fn get_type(&self) -> WriterType {
1228         #[fixed_stack_segment]; #[inline(never)];
1229
1230         unsafe {
1231             let fd = libc::fileno(*self);
1232             if libc::isatty(fd) == 0 { File   }
1233             else                     { Screen }
1234         }
1235     }
1236 }
1237
1238 pub fn FILE_writer(f: *libc::FILE, cleanup: bool) -> @Writer {
1239     if cleanup {
1240         @Wrapper { base: f, cleanup: FILERes::new(f) } as @Writer
1241     } else {
1242         @f as @Writer
1243     }
1244 }
1245
1246 impl Writer for fd_t {
1247     fn write(&self, v: &[u8]) {
1248         #[fixed_stack_segment]; #[inline(never)];
1249
1250         #[cfg(windows)]
1251         type IoSize = libc::c_uint;
1252         #[cfg(windows)]
1253         type IoRet = c_int;
1254
1255         #[cfg(unix)]
1256         type IoSize = size_t;
1257         #[cfg(unix)]
1258         type IoRet = libc::ssize_t;
1259
1260         unsafe {
1261             let mut count = 0u;
1262             do v.as_imm_buf |vbuf, len| {
1263                 while count < len {
1264                     let vb = ptr::offset(vbuf, count as int) as *c_void;
1265                     let nout = libc::write(*self, vb, len as IoSize);
1266                     if nout < 0 as IoRet {
1267                         error!("error writing buffer");
1268                         error!("%s", os::last_os_error());
1269                         fail!();
1270                     }
1271                     count += nout as uint;
1272                 }
1273             }
1274         }
1275     }
1276     fn seek(&self, _offset: int, _whence: SeekStyle) {
1277         error!("need 64-bit foreign calls for seek, sorry");
1278         fail!();
1279     }
1280     fn tell(&self) -> uint {
1281         error!("need 64-bit foreign calls for tell, sorry");
1282         fail!();
1283     }
1284     fn flush(&self) -> int { 0 }
1285     fn get_type(&self) -> WriterType {
1286         #[fixed_stack_segment]; #[inline(never)];
1287
1288         unsafe {
1289             if libc::isatty(*self) == 0 { File } else { Screen }
1290         }
1291     }
1292 }
1293
1294 pub struct FdRes {
1295     fd: fd_t,
1296 }
1297
1298 impl FdRes {
1299     pub fn new(fd: fd_t) -> FdRes {
1300         FdRes { fd: fd }
1301     }
1302 }
1303
1304 impl Drop for FdRes {
1305     fn drop(&mut self) {
1306         #[fixed_stack_segment]; #[inline(never)];
1307
1308         unsafe {
1309             libc::close(self.fd);
1310         }
1311     }
1312 }
1313
1314 pub fn fd_writer(fd: fd_t, cleanup: bool) -> @Writer {
1315     if cleanup {
1316         @Wrapper { base: fd, cleanup: FdRes::new(fd) } as @Writer
1317     } else {
1318         @fd as @Writer
1319     }
1320 }
1321
1322
1323 pub fn mk_file_writer(path: &Path, flags: &[FileFlag])
1324                    -> Result<@Writer, ~str> {
1325     #[fixed_stack_segment]; #[inline(never)];
1326
1327     #[cfg(windows)]
1328     fn wb() -> c_int {
1329       (O_WRONLY | libc::consts::os::extra::O_BINARY) as c_int
1330     }
1331
1332     #[cfg(unix)]
1333     fn wb() -> c_int { O_WRONLY as c_int }
1334
1335     let mut fflags: c_int = wb();
1336     for f in flags.iter() {
1337         match *f {
1338           Append => fflags |= O_APPEND as c_int,
1339           Create => fflags |= O_CREAT as c_int,
1340           Truncate => fflags |= O_TRUNC as c_int,
1341           NoFlag => ()
1342         }
1343     }
1344     let fd = unsafe {
1345         do path.with_c_str |pathbuf| {
1346             libc::open(pathbuf, fflags, (S_IRUSR | S_IWUSR) as c_int)
1347         }
1348     };
1349     if fd < (0 as c_int) {
1350         Err(fmt!("error opening %s: %s", path.to_str(), os::last_os_error()))
1351     } else {
1352         Ok(fd_writer(fd, true))
1353     }
1354 }
1355
1356 pub fn u64_to_le_bytes<T>(n: u64, size: uint,
1357                           f: &fn(v: &[u8]) -> T) -> T {
1358     assert!(size <= 8u);
1359     match size {
1360       1u => f(&[n as u8]),
1361       2u => f(&[n as u8,
1362               (n >> 8) as u8]),
1363       4u => f(&[n as u8,
1364               (n >> 8) as u8,
1365               (n >> 16) as u8,
1366               (n >> 24) as u8]),
1367       8u => f(&[n as u8,
1368               (n >> 8) as u8,
1369               (n >> 16) as u8,
1370               (n >> 24) as u8,
1371               (n >> 32) as u8,
1372               (n >> 40) as u8,
1373               (n >> 48) as u8,
1374               (n >> 56) as u8]),
1375       _ => {
1376
1377         let mut bytes: ~[u8] = ~[];
1378         let mut i = size;
1379         let mut n = n;
1380         while i > 0u {
1381             bytes.push((n & 255_u64) as u8);
1382             n >>= 8_u64;
1383             i -= 1u;
1384         }
1385         f(bytes)
1386       }
1387     }
1388 }
1389
1390 pub fn u64_to_be_bytes<T>(n: u64, size: uint,
1391                            f: &fn(v: &[u8]) -> T) -> T {
1392     assert!(size <= 8u);
1393     match size {
1394       1u => f(&[n as u8]),
1395       2u => f(&[(n >> 8) as u8,
1396               n as u8]),
1397       4u => f(&[(n >> 24) as u8,
1398               (n >> 16) as u8,
1399               (n >> 8) as u8,
1400               n as u8]),
1401       8u => f(&[(n >> 56) as u8,
1402               (n >> 48) as u8,
1403               (n >> 40) as u8,
1404               (n >> 32) as u8,
1405               (n >> 24) as u8,
1406               (n >> 16) as u8,
1407               (n >> 8) as u8,
1408               n as u8]),
1409       _ => {
1410         let mut bytes: ~[u8] = ~[];
1411         let mut i = size;
1412         while i > 0u {
1413             let shift = ((i - 1u) * 8u) as u64;
1414             bytes.push((n >> shift) as u8);
1415             i -= 1u;
1416         }
1417         f(bytes)
1418       }
1419     }
1420 }
1421
1422 pub fn u64_from_be_bytes(data: &[u8],
1423                          start: uint,
1424                          size: uint)
1425                       -> u64 {
1426     let mut sz = size;
1427     assert!((sz <= 8u));
1428     let mut val = 0_u64;
1429     let mut pos = start;
1430     while sz > 0u {
1431         sz -= 1u;
1432         val += (data[pos] as u64) << ((sz * 8u) as u64);
1433         pos += 1u;
1434     }
1435     return val;
1436 }
1437
1438 // FIXME: #3048 combine trait+impl (or just move these to
1439 // default methods on writer)
1440 /// Generic utility functions defined on writers.
1441 pub trait WriterUtil {
1442
1443     /// Write a single utf-8 encoded char.
1444     fn write_char(&self, ch: char);
1445
1446     /// Write every char in the given str, encoded as utf-8.
1447     fn write_str(&self, s: &str);
1448
1449     /// Write the given str, as utf-8, followed by '\n'.
1450     fn write_line(&self, s: &str);
1451
1452     /// Write the result of passing n through `int::to_str_bytes`.
1453     fn write_int(&self, n: int);
1454
1455     /// Write the result of passing n through `uint::to_str_bytes`.
1456     fn write_uint(&self, n: uint);
1457
1458     /// Write a little-endian uint (number of bytes depends on system).
1459     fn write_le_uint(&self, n: uint);
1460
1461     /// Write a little-endian int (number of bytes depends on system).
1462     fn write_le_int(&self, n: int);
1463
1464     /// Write a big-endian uint (number of bytes depends on system).
1465     fn write_be_uint(&self, n: uint);
1466
1467     /// Write a big-endian int (number of bytes depends on system).
1468     fn write_be_int(&self, n: int);
1469
1470     /// Write a big-endian u64 (8 bytes).
1471     fn write_be_u64(&self, n: u64);
1472
1473     /// Write a big-endian u32 (4 bytes).
1474     fn write_be_u32(&self, n: u32);
1475
1476     /// Write a big-endian u16 (2 bytes).
1477     fn write_be_u16(&self, n: u16);
1478
1479     /// Write a big-endian i64 (8 bytes).
1480     fn write_be_i64(&self, n: i64);
1481
1482     /// Write a big-endian i32 (4 bytes).
1483     fn write_be_i32(&self, n: i32);
1484
1485     /// Write a big-endian i16 (2 bytes).
1486     fn write_be_i16(&self, n: i16);
1487
1488     /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1489     fn write_be_f64(&self, f: f64);
1490
1491     /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1492     fn write_be_f32(&self, f: f32);
1493
1494     /// Write a little-endian u64 (8 bytes).
1495     fn write_le_u64(&self, n: u64);
1496
1497     /// Write a little-endian u32 (4 bytes).
1498     fn write_le_u32(&self, n: u32);
1499
1500     /// Write a little-endian u16 (2 bytes).
1501     fn write_le_u16(&self, n: u16);
1502
1503     /// Write a little-endian i64 (8 bytes).
1504     fn write_le_i64(&self, n: i64);
1505
1506     /// Write a little-endian i32 (4 bytes).
1507     fn write_le_i32(&self, n: i32);
1508
1509     /// Write a little-endian i16 (2 bytes).
1510     fn write_le_i16(&self, n: i16);
1511
1512     /// Write a little-endian IEEE754 double-precision floating-point
1513     /// (8 bytes).
1514     fn write_le_f64(&self, f: f64);
1515
1516     /// Write a little-endian IEEE754 single-precision floating-point
1517     /// (4 bytes).
1518     fn write_le_f32(&self, f: f32);
1519
1520     /// Write a u8 (1 byte).
1521     fn write_u8(&self, n: u8);
1522
1523     /// Write a i8 (1 byte).
1524     fn write_i8(&self, n: i8);
1525 }
1526
1527 impl<T:Writer> WriterUtil for T {
1528     fn write_char(&self, ch: char) {
1529         if (ch as uint) < 128u {
1530             self.write(&[ch as u8]);
1531         } else {
1532             self.write_str(str::from_char(ch));
1533         }
1534     }
1535     fn write_str(&self, s: &str) { self.write(s.as_bytes()) }
1536     fn write_line(&self, s: &str) {
1537         self.write_str(s);
1538         self.write_str(&"\n");
1539     }
1540     fn write_int(&self, n: int) {
1541         int::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1542     }
1543     fn write_uint(&self, n: uint) {
1544         uint::to_str_bytes(n, 10u, |bytes| self.write(bytes))
1545     }
1546     fn write_le_uint(&self, n: uint) {
1547         u64_to_le_bytes(n as u64, uint::bytes, |v| self.write(v))
1548     }
1549     fn write_le_int(&self, n: int) {
1550         u64_to_le_bytes(n as u64, int::bytes, |v| self.write(v))
1551     }
1552     fn write_be_uint(&self, n: uint) {
1553         u64_to_be_bytes(n as u64, uint::bytes, |v| self.write(v))
1554     }
1555     fn write_be_int(&self, n: int) {
1556         u64_to_be_bytes(n as u64, int::bytes, |v| self.write(v))
1557     }
1558     fn write_be_u64(&self, n: u64) {
1559         u64_to_be_bytes(n, 8u, |v| self.write(v))
1560     }
1561     fn write_be_u32(&self, n: u32) {
1562         u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1563     }
1564     fn write_be_u16(&self, n: u16) {
1565         u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1566     }
1567     fn write_be_i64(&self, n: i64) {
1568         u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1569     }
1570     fn write_be_i32(&self, n: i32) {
1571         u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1572     }
1573     fn write_be_i16(&self, n: i16) {
1574         u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1575     }
1576     fn write_be_f64(&self, f:f64) {
1577         unsafe {
1578             self.write_be_u64(cast::transmute(f))
1579         }
1580     }
1581     fn write_be_f32(&self, f:f32) {
1582         unsafe {
1583             self.write_be_u32(cast::transmute(f))
1584         }
1585     }
1586     fn write_le_u64(&self, n: u64) {
1587         u64_to_le_bytes(n, 8u, |v| self.write(v))
1588     }
1589     fn write_le_u32(&self, n: u32) {
1590         u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1591     }
1592     fn write_le_u16(&self, n: u16) {
1593         u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1594     }
1595     fn write_le_i64(&self, n: i64) {
1596         u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1597     }
1598     fn write_le_i32(&self, n: i32) {
1599         u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1600     }
1601     fn write_le_i16(&self, n: i16) {
1602         u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1603     }
1604     fn write_le_f64(&self, f:f64) {
1605         unsafe {
1606             self.write_le_u64(cast::transmute(f))
1607         }
1608     }
1609     fn write_le_f32(&self, f:f32) {
1610         unsafe {
1611             self.write_le_u32(cast::transmute(f))
1612         }
1613     }
1614
1615     fn write_u8(&self, n: u8) { self.write([n]) }
1616     fn write_i8(&self, n: i8) { self.write([n as u8]) }
1617
1618 }
1619
1620 pub fn file_writer(path: &Path, flags: &[FileFlag]) -> Result<@Writer, ~str> {
1621     mk_file_writer(path, flags).and_then(|w| Ok(w))
1622 }
1623
1624
1625 // FIXME: fileflags // #2004
1626 pub fn buffered_file_writer(path: &Path) -> Result<@Writer, ~str> {
1627     #[fixed_stack_segment]; #[inline(never)];
1628
1629     unsafe {
1630         let f = do path.with_c_str |pathbuf| {
1631             do "w".with_c_str |modebuf| {
1632                 libc::fopen(pathbuf, modebuf)
1633             }
1634         };
1635         return if f as uint == 0u {
1636             Err(~"error opening " + path.to_str())
1637         } else {
1638             Ok(FILE_writer(f, true))
1639         }
1640     }
1641 }
1642
1643 // FIXME (#2004) it would be great if this could be a const
1644 // FIXME (#2004) why are these different from the way stdin() is
1645 // implemented?
1646
1647
1648 /**
1649 * Gives a `Writer` which allows you to write to the standard output.
1650 *
1651 * # Example
1652 *
1653 * ~~~ {.rust}
1654 * let stdout = std::io::stdout();
1655 * stdout.write_str("hello\n");
1656 * ~~~
1657 */
1658 pub fn stdout() -> @Writer { fd_writer(libc::STDOUT_FILENO as c_int, false) }
1659
1660 /**
1661 * Gives a `Writer` which allows you to write to standard error.
1662 *
1663 * # Example
1664 *
1665 * ~~~ {.rust}
1666 * let stderr = std::io::stderr();
1667 * stderr.write_str("hello\n");
1668 * ~~~
1669 */
1670 pub fn stderr() -> @Writer { fd_writer(libc::STDERR_FILENO as c_int, false) }
1671
1672 /**
1673 * Prints a string to standard output.
1674 *
1675 * This string will not have an implicit newline at the end. If you want
1676 * an implicit newline, please see `println`.
1677 *
1678 * # Example
1679 *
1680 * ~~~ {.rust}
1681 * // print is imported into the prelude, and so is always available.
1682 * print("hello");
1683 * ~~~
1684 */
1685 pub fn print(s: &str) {
1686     stdout().write_str(s);
1687 }
1688
1689 /**
1690 * Prints a string to standard output, followed by a newline.
1691 *
1692 * If you do not want an implicit newline, please see `print`.
1693 *
1694 * # Example
1695 *
1696 * ~~~ {.rust}
1697 * // println is imported into the prelude, and so is always available.
1698 * println("hello");
1699 * ~~~
1700 */
1701 pub fn println(s: &str) {
1702     stdout().write_line(s);
1703 }
1704
1705 pub struct BytesWriter {
1706     bytes: @mut ~[u8],
1707     pos: @mut uint,
1708 }
1709
1710 impl BytesWriter {
1711     pub fn new() -> BytesWriter {
1712         BytesWriter {
1713             bytes: @mut ~[],
1714             pos: @mut 0
1715         }
1716     }
1717 }
1718
1719 impl Writer for BytesWriter {
1720     fn write(&self, v: &[u8]) {
1721         let v_len = v.len();
1722
1723         let bytes = &mut *self.bytes;
1724         let count = num::max(bytes.len(), *self.pos + v_len);
1725         bytes.reserve(count);
1726
1727         unsafe {
1728             vec::raw::set_len(bytes, count);
1729
1730             let view = bytes.mut_slice(*self.pos, count);
1731             vec::bytes::copy_memory(view, v, v_len);
1732         }
1733
1734         *self.pos += v_len;
1735     }
1736
1737     fn seek(&self, offset: int, whence: SeekStyle) {
1738         let pos = *self.pos;
1739         let len = self.bytes.len();
1740         *self.pos = seek_in_buf(offset, pos, len, whence);
1741     }
1742
1743     fn tell(&self) -> uint {
1744         *self.pos
1745     }
1746
1747     fn flush(&self) -> int {
1748         0
1749     }
1750
1751     fn get_type(&self) -> WriterType {
1752         File
1753     }
1754 }
1755
1756 pub fn with_bytes_writer(f: &fn(@Writer)) -> ~[u8] {
1757     let wr = @BytesWriter::new();
1758     f(wr as @Writer);
1759     let @BytesWriter { bytes, _ } = wr;
1760     (*bytes).clone()
1761 }
1762
1763 pub fn with_str_writer(f: &fn(@Writer)) -> ~str {
1764     str::from_utf8(with_bytes_writer(f))
1765 }
1766
1767 // Utility functions
1768 pub fn seek_in_buf(offset: int, pos: uint, len: uint, whence: SeekStyle) ->
1769    uint {
1770     let mut bpos = pos as int;
1771     let blen = len as int;
1772     match whence {
1773       SeekSet => bpos = offset,
1774       SeekCur => bpos += offset,
1775       SeekEnd => bpos = blen + offset
1776     }
1777     if bpos < 0 { bpos = 0; } else if bpos > blen { bpos = blen; }
1778     return bpos as uint;
1779 }
1780
1781 pub fn read_whole_file_str(file: &Path) -> Result<~str, ~str> {
1782     do read_whole_file(file).and_then |bytes| {
1783         if str::is_utf8(bytes) {
1784             Ok(str::from_utf8(bytes))
1785         } else {
1786             Err(file.to_str() + " is not UTF-8")
1787         }
1788     }
1789 }
1790
1791 // FIXME (#2004): implement this in a low-level way. Going through the
1792 // abstractions is pointless.
1793 pub fn read_whole_file(file: &Path) -> Result<~[u8], ~str> {
1794     do file_reader(file).and_then |rdr| {
1795         Ok(rdr.read_whole_stream())
1796     }
1797 }
1798
1799 // fsync related
1800
1801 pub mod fsync {
1802     use io::{FILERes, FdRes, fd_t};
1803     use libc;
1804     use ops::Drop;
1805     use option::{None, Option, Some};
1806     use os;
1807
1808     pub enum Level {
1809         // whatever fsync does on that platform
1810         FSync,
1811
1812         // fdatasync on linux, similiar or more on other platforms
1813         FDataSync,
1814
1815         // full fsync
1816         //
1817         // You must additionally sync the parent directory as well!
1818         FullFSync,
1819     }
1820
1821
1822     // Artifacts that need to fsync on destruction
1823     pub struct Res<t> {
1824         arg: Arg<t>,
1825     }
1826
1827     impl <t> Res<t> {
1828         pub fn new(arg: Arg<t>) -> Res<t> {
1829             Res { arg: arg }
1830         }
1831     }
1832
1833     #[unsafe_destructor]
1834     impl<T> Drop for Res<T> {
1835         fn drop(&mut self) {
1836             match self.arg.opt_level {
1837                 None => (),
1838                 Some(level) => {
1839                   // fail hard if not succesful
1840                   assert!(((self.arg.fsync_fn)(&self.arg.val, level) != -1));
1841                 }
1842             }
1843         }
1844     }
1845
1846     pub struct Arg<t> {
1847         val: t,
1848         opt_level: Option<Level>,
1849         fsync_fn: @fn(f: &t, Level) -> int,
1850     }
1851
1852     // fsync file after executing blk
1853     // FIXME (#2004) find better way to create resources within lifetime of
1854     // outer res
1855     pub fn FILE_res_sync(file: &FILERes, opt_level: Option<Level>,
1856                          blk: &fn(v: Res<*libc::FILE>)) {
1857         blk(Res::new(Arg {
1858             val: file.f, opt_level: opt_level,
1859             fsync_fn: |file, l| fsync_fd(fileno(*file), l)
1860         }));
1861
1862         fn fileno(stream: *libc::FILE) -> libc::c_int {
1863             #[fixed_stack_segment]; #[inline(never)];
1864             unsafe { libc::fileno(stream) }
1865         }
1866     }
1867
1868     // fsync fd after executing blk
1869     pub fn fd_res_sync(fd: &FdRes, opt_level: Option<Level>,
1870                        blk: &fn(v: Res<fd_t>)) {
1871         blk(Res::new(Arg {
1872             val: fd.fd, opt_level: opt_level,
1873             fsync_fn: |fd, l| fsync_fd(*fd, l)
1874         }));
1875     }
1876
1877     fn fsync_fd(fd: libc::c_int, level: Level) -> int {
1878         #[fixed_stack_segment]; #[inline(never)];
1879
1880         os::fsync_fd(fd, level) as int
1881     }
1882
1883     // Type of objects that may want to fsync
1884     pub trait FSyncable { fn fsync(&self, l: Level) -> int; }
1885
1886     // Call o.fsync after executing blk
1887     pub fn obj_sync(o: @FSyncable, opt_level: Option<Level>,
1888                     blk: &fn(v: Res<@FSyncable>)) {
1889         blk(Res::new(Arg {
1890             val: o, opt_level: opt_level,
1891             fsync_fn: |o, l| (*o).fsync(l)
1892         }));
1893     }
1894 }
1895
1896 #[cfg(test)]
1897 mod tests {
1898     use prelude::*;
1899     use i32;
1900     use io::{BytesWriter, SeekCur, SeekEnd, SeekSet};
1901     use io;
1902     use path::Path;
1903     use result::{Ok, Err};
1904     use u64;
1905     use vec;
1906     use cast::transmute;
1907
1908     #[test]
1909     fn test_simple() {
1910         let tmpfile = &Path("tmp/lib-io-test-simple.tmp");
1911         debug!(tmpfile);
1912         let frood: ~str =
1913             ~"A hoopy frood who really knows where his towel is.";
1914         debug!(frood.clone());
1915         {
1916             let out = io::file_writer(tmpfile, [io::Create, io::Truncate]).unwrap();
1917             out.write_str(frood);
1918         }
1919         let inp = io::file_reader(tmpfile).unwrap();
1920         let frood2: ~str = inp.read_c_str();
1921         debug!(frood2.clone());
1922         assert_eq!(frood, frood2);
1923     }
1924
1925     #[test]
1926     fn test_each_byte_each_char_file() {
1927         // Issue #5056 -- shouldn't include trailing EOF.
1928         let path = Path("tmp/lib-io-test-each-byte-each-char-file.tmp");
1929
1930         {
1931             // create empty, enough to reproduce a problem
1932             io::file_writer(&path, [io::Create]).unwrap();
1933         }
1934
1935         {
1936             let file = io::file_reader(&path).unwrap();
1937             do file.each_byte() |_| {
1938                 fail!("must be empty")
1939             };
1940         }
1941
1942         {
1943             let file = io::file_reader(&path).unwrap();
1944             do file.each_char() |_| {
1945                 fail!("must be empty")
1946             };
1947         }
1948     }
1949
1950     #[test]
1951     fn test_readchars_empty() {
1952         do io::with_str_reader("") |inp| {
1953             let res : ~[char] = inp.read_chars(128);
1954             assert_eq!(res.len(), 0);
1955         }
1956     }
1957
1958     #[test]
1959     fn test_read_line_utf8() {
1960         do io::with_str_reader("生锈的汤匙切肉汤hello生锈的汤匙切肉汤") |inp| {
1961             let line = inp.read_line();
1962             assert_eq!(line, ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤");
1963         }
1964     }
1965
1966     #[test]
1967     fn test_read_lines() {
1968         do io::with_str_reader("a\nb\nc\n") |inp| {
1969             assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1970         }
1971
1972         do io::with_str_reader("a\nb\nc") |inp| {
1973             assert_eq!(inp.read_lines(), ~[~"a", ~"b", ~"c"]);
1974         }
1975
1976         do io::with_str_reader("") |inp| {
1977             assert!(inp.read_lines().is_empty());
1978         }
1979     }
1980
1981     #[test]
1982     fn test_readchars_wide() {
1983         let wide_test = ~"生锈的汤匙切肉汤hello生锈的汤匙切肉汤";
1984         let ivals : ~[int] = ~[
1985             29983, 38152, 30340, 27748,
1986             21273, 20999, 32905, 27748,
1987             104, 101, 108, 108, 111,
1988             29983, 38152, 30340, 27748,
1989             21273, 20999, 32905, 27748];
1990         fn check_read_ln(len : uint, s: &str, ivals: &[int]) {
1991             do io::with_str_reader(s) |inp| {
1992                 let res : ~[char] = inp.read_chars(len);
1993                 if len <= ivals.len() {
1994                     assert_eq!(res.len(), len);
1995                 }
1996                 for (iv, c) in ivals.iter().zip(res.iter()) {
1997                     assert!(*iv == *c as int)
1998                 }
1999             }
2000         }
2001         let mut i = 0;
2002         while i < 8 {
2003             check_read_ln(i, wide_test, ivals);
2004             i += 1;
2005         }
2006         // check a long read for good measure
2007         check_read_ln(128, wide_test, ivals);
2008     }
2009
2010     #[test]
2011     fn test_readchar() {
2012         do io::with_str_reader("生") |inp| {
2013             let res = inp.read_char();
2014             assert_eq!(res as int, 29983);
2015         }
2016     }
2017
2018     #[test]
2019     fn test_readchar_empty() {
2020         do io::with_str_reader("") |inp| {
2021             let res = inp.read_char();
2022             assert_eq!(res, unsafe { transmute(-1u32) }); // FIXME: #8971: unsound
2023         }
2024     }
2025
2026     #[test]
2027     fn file_reader_not_exist() {
2028         match io::file_reader(&Path("not a file")) {
2029           Err(e) => {
2030             assert_eq!(e, ~"error opening not a file");
2031           }
2032           Ok(_) => fail!()
2033         }
2034     }
2035
2036     #[test]
2037     #[should_fail]
2038     fn test_read_buffer_too_small() {
2039         let path = &Path("tmp/lib-io-test-read-buffer-too-small.tmp");
2040         // ensure the file exists
2041         io::file_writer(path, [io::Create]).unwrap();
2042
2043         let file = io::file_reader(path).unwrap();
2044         let mut buf = vec::from_elem(5, 0u8);
2045         file.read(buf, 6); // this should fail because buf is too small
2046     }
2047
2048     #[test]
2049     fn test_read_buffer_big_enough() {
2050         let path = &Path("tmp/lib-io-test-read-buffer-big-enough.tmp");
2051         // ensure the file exists
2052         io::file_writer(path, [io::Create]).unwrap();
2053
2054         let file = io::file_reader(path).unwrap();
2055         let mut buf = vec::from_elem(5, 0u8);
2056         file.read(buf, 4); // this should succeed because buf is big enough
2057     }
2058
2059     #[test]
2060     fn test_write_empty() {
2061         let file = io::file_writer(&Path("tmp/lib-io-test-write-empty.tmp"),
2062                                    [io::Create]).unwrap();
2063         file.write([]);
2064     }
2065
2066     #[test]
2067     fn file_writer_bad_name() {
2068         match io::file_writer(&Path("?/?"), []) {
2069           Err(e) => {
2070             assert!(e.starts_with("error opening"));
2071           }
2072           Ok(_) => fail!()
2073         }
2074     }
2075
2076     #[test]
2077     fn buffered_file_writer_bad_name() {
2078         match io::buffered_file_writer(&Path("?/?")) {
2079           Err(e) => {
2080             assert!(e.starts_with("error opening"));
2081           }
2082           Ok(_) => fail!()
2083         }
2084     }
2085
2086     #[test]
2087     fn bytes_buffer_overwrite() {
2088         let wr = BytesWriter::new();
2089         wr.write([0u8, 1u8, 2u8, 3u8]);
2090         assert!(*wr.bytes == ~[0u8, 1u8, 2u8, 3u8]);
2091         wr.seek(-2, SeekCur);
2092         wr.write([4u8, 5u8, 6u8, 7u8]);
2093         assert!(*wr.bytes == ~[0u8, 1u8, 4u8, 5u8, 6u8, 7u8]);
2094         wr.seek(-2, SeekEnd);
2095         wr.write([8u8]);
2096         wr.seek(1, SeekSet);
2097         wr.write([9u8]);
2098         assert!(*wr.bytes == ~[0u8, 9u8, 4u8, 5u8, 8u8, 7u8]);
2099     }
2100
2101     #[test]
2102     fn test_read_write_le() {
2103         let path = Path("tmp/lib-io-test-read-write-le.tmp");
2104         let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2105
2106         // write the ints to the file
2107         {
2108             let file = io::file_writer(&path, [io::Create]).unwrap();
2109             for i in uints.iter() {
2110                 file.write_le_u64(*i);
2111             }
2112         }
2113
2114         // then read them back and check that they are the same
2115         {
2116             let file = io::file_reader(&path).unwrap();
2117             for i in uints.iter() {
2118                 assert_eq!(file.read_le_u64(), *i);
2119             }
2120         }
2121     }
2122
2123     #[test]
2124     fn test_read_write_be() {
2125         let path = Path("tmp/lib-io-test-read-write-be.tmp");
2126         let uints = [0, 1, 2, 42, 10_123, 100_123_456, u64::max_value];
2127
2128         // write the ints to the file
2129         {
2130             let file = io::file_writer(&path, [io::Create]).unwrap();
2131             for i in uints.iter() {
2132                 file.write_be_u64(*i);
2133             }
2134         }
2135
2136         // then read them back and check that they are the same
2137         {
2138             let file = io::file_reader(&path).unwrap();
2139             for i in uints.iter() {
2140                 assert_eq!(file.read_be_u64(), *i);
2141             }
2142         }
2143     }
2144
2145     #[test]
2146     fn test_read_be_int_n() {
2147         let path = Path("tmp/lib-io-test-read-be-int-n.tmp");
2148         let ints = [i32::min_value, -123456, -42, -5, 0, 1, i32::max_value];
2149
2150         // write the ints to the file
2151         {
2152             let file = io::file_writer(&path, [io::Create]).unwrap();
2153             for i in ints.iter() {
2154                 file.write_be_i32(*i);
2155             }
2156         }
2157
2158         // then read them back and check that they are the same
2159         {
2160             let file = io::file_reader(&path).unwrap();
2161             for i in ints.iter() {
2162                 // this tests that the sign extension is working
2163                 // (comparing the values as i32 would not test this)
2164                 assert_eq!(file.read_be_int_n(4), *i as i64);
2165             }
2166         }
2167     }
2168
2169     #[test]
2170     fn test_read_f32() {
2171         let path = Path("tmp/lib-io-test-read-f32.tmp");
2172         //big-endian floating-point 8.1250
2173         let buf = ~[0x41, 0x02, 0x00, 0x00];
2174
2175         {
2176             let file = io::file_writer(&path, [io::Create]).unwrap();
2177             file.write(buf);
2178         }
2179
2180         {
2181             let file = io::file_reader(&path).unwrap();
2182             let f = file.read_be_f32();
2183             assert_eq!(f, 8.1250);
2184         }
2185     }
2186
2187     #[test]
2188     fn test_read_write_f32() {
2189         let path = Path("tmp/lib-io-test-read-write-f32.tmp");
2190         let f:f32 = 8.1250;
2191
2192         {
2193             let file = io::file_writer(&path, [io::Create]).unwrap();
2194             file.write_be_f32(f);
2195             file.write_le_f32(f);
2196         }
2197
2198         {
2199             let file = io::file_reader(&path).unwrap();
2200             assert_eq!(file.read_be_f32(), 8.1250);
2201             assert_eq!(file.read_le_f32(), 8.1250);
2202         }
2203     }
2204 }