]> git.lizzy.rs Git - rust.git/blob - src/libstd/io/mod.rs
31eab4363d0aaa869216d7595a34d861bbef2e15
[rust.git] / src / libstd / io / mod.rs
1 // Copyright 2013-2014 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 // ignore-lexer-test FIXME #15883
12
13 // FIXME: cover these topics:
14 //        path, reader, writer, stream, raii (close not needed),
15 //        stdio, print!, println!, file access, process spawning,
16 //        error handling
17
18
19 /*! I/O, including files, networking, timers, and processes
20
21 `std::io` provides Rust's basic I/O types,
22 for reading and writing to files, TCP, UDP,
23 and other types of sockets and pipes,
24 manipulating the file system, spawning processes.
25
26 # Examples
27
28 Some examples of obvious things you might want to do
29
30 * Read lines from stdin
31
32     ```rust
33     use std::io;
34
35     for line in io::stdin().lines() {
36         print!("{}", line.unwrap());
37     }
38     ```
39
40 * Read a complete file
41
42     ```rust
43     use std::io::File;
44
45     let contents = File::open(&Path::new("message.txt")).read_to_end();
46     ```
47
48 * Write a line to a file
49
50     ```rust
51     # #![allow(unused_must_use)]
52     use std::io::File;
53
54     let mut file = File::create(&Path::new("message.txt"));
55     file.write(b"hello, file!\n");
56     # drop(file);
57     # ::std::io::fs::unlink(&Path::new("message.txt"));
58     ```
59
60 * Iterate over the lines of a file
61
62     ```rust,no_run
63     use std::io::BufferedReader;
64     use std::io::File;
65
66     let path = Path::new("message.txt");
67     let mut file = BufferedReader::new(File::open(&path));
68     for line in file.lines() {
69         print!("{}", line.unwrap());
70     }
71     ```
72
73 * Pull the lines of a file into a vector of strings
74
75     ```rust,no_run
76     use std::io::BufferedReader;
77     use std::io::File;
78
79     let path = Path::new("message.txt");
80     let mut file = BufferedReader::new(File::open(&path));
81     let lines: Vec<String> = file.lines().map(|x| x.unwrap()).collect();
82     ```
83
84 * Make a simple TCP client connection and request
85
86     ```rust
87     # #![allow(unused_must_use)]
88     use std::io::TcpStream;
89
90     # // connection doesn't fail if a server is running on 8080
91     # // locally, we still want to be type checking this code, so lets
92     # // just stop it running (#11576)
93     # if false {
94     let mut socket = TcpStream::connect("127.0.0.1:8080").unwrap();
95     socket.write(b"GET / HTTP/1.0\n\n");
96     let response = socket.read_to_end();
97     # }
98     ```
99
100 * Make a simple TCP server
101
102     ```rust
103     # fn main() { }
104     # fn foo() {
105     # #![allow(dead_code)]
106     use std::io::{TcpListener, TcpStream};
107     use std::io::{Acceptor, Listener};
108
109     let listener = TcpListener::bind("127.0.0.1:80");
110
111     // bind the listener to the specified address
112     let mut acceptor = listener.listen();
113
114     fn handle_client(mut stream: TcpStream) {
115         // ...
116     # &mut stream; // silence unused mutability/variable warning
117     }
118     // accept connections and process them, spawning a new tasks for each one
119     for stream in acceptor.incoming() {
120         match stream {
121             Err(e) => { /* connection failed */ }
122             Ok(stream) => spawn(proc() {
123                 // connection succeeded
124                 handle_client(stream)
125             })
126         }
127     }
128
129     // close the socket server
130     drop(acceptor);
131     # }
132     ```
133
134
135 # Error Handling
136
137 I/O is an area where nearly every operation can result in unexpected
138 errors. Errors should be painfully visible when they happen, and handling them
139 should be easy to work with. It should be convenient to handle specific I/O
140 errors, and it should also be convenient to not deal with I/O errors.
141
142 Rust's I/O employs a combination of techniques to reduce boilerplate
143 while still providing feedback about errors. The basic strategy:
144
145 * All I/O operations return `IoResult<T>` which is equivalent to
146   `Result<T, IoError>`. The `Result` type is defined in the `std::result`
147   module.
148 * If the `Result` type goes unused, then the compiler will by default emit a
149   warning about the unused result. This is because `Result` has the
150   `#[must_use]` attribute.
151 * Common traits are implemented for `IoResult`, e.g.
152   `impl<R: Reader> Reader for IoResult<R>`, so that error values do not have
153   to be 'unwrapped' before use.
154
155 These features combine in the API to allow for expressions like
156 `File::create(&Path::new("diary.txt")).write(b"Met a girl.\n")`
157 without having to worry about whether "diary.txt" exists or whether
158 the write succeeds. As written, if either `new` or `write_line`
159 encounters an error then the result of the entire expression will
160 be an error.
161
162 If you wanted to handle the error though you might write:
163
164 ```rust
165 # #![allow(unused_must_use)]
166 use std::io::File;
167
168 match File::create(&Path::new("diary.txt")).write(b"Met a girl.\n") {
169     Ok(()) => (), // succeeded
170     Err(e) => println!("failed to write to my diary: {}", e),
171 }
172
173 # ::std::io::fs::unlink(&Path::new("diary.txt"));
174 ```
175
176 So what actually happens if `create` encounters an error?
177 It's important to know that what `new` returns is not a `File`
178 but an `IoResult<File>`.  If the file does not open, then `new` will simply
179 return `Err(..)`. Because there is an implementation of `Writer` (the trait
180 required ultimately required for types to implement `write_line`) there is no
181 need to inspect or unwrap the `IoResult<File>` and we simply call `write_line`
182 on it. If `new` returned an `Err(..)` then the followup call to `write_line`
183 will also return an error.
184
185 ## `try!`
186
187 Explicit pattern matching on `IoResult`s can get quite verbose, especially
188 when performing many I/O operations. Some examples (like those above) are
189 alleviated with extra methods implemented on `IoResult`, but others have more
190 complex interdependencies among each I/O operation.
191
192 The `try!` macro from `std::macros` is provided as a method of early-return
193 inside `Result`-returning functions. It expands to an early-return on `Err`
194 and otherwise unwraps the contained `Ok` value.
195
196 If you wanted to read several `u32`s from a file and return their product:
197
198 ```rust
199 use std::io::{File, IoResult};
200
201 fn file_product(p: &Path) -> IoResult<u32> {
202     let mut f = File::open(p);
203     let x1 = try!(f.read_le_u32());
204     let x2 = try!(f.read_le_u32());
205
206     Ok(x1 * x2)
207 }
208
209 match file_product(&Path::new("numbers.bin")) {
210     Ok(x) => println!("{}", x),
211     Err(e) => println!("Failed to read numbers!")
212 }
213 ```
214
215 With `try!` in `file_product`, each `read_le_u32` need not be directly
216 concerned with error handling; instead its caller is responsible for
217 responding to errors that may occur while attempting to read the numbers.
218
219 */
220
221 #![experimental]
222 #![deny(unused_must_use)]
223
224 use char::Char;
225 use clone::Clone;
226 use default::Default;
227 use error::{FromError, Error};
228 use fmt;
229 use int;
230 use iter::Iterator;
231 use mem::transmute;
232 use ops::{BitOr, BitXor, BitAnd, Sub, Not};
233 use option::{Option, Some, None};
234 use os;
235 use boxed::Box;
236 use result::{Ok, Err, Result};
237 use sys;
238 use slice::{AsSlice, SlicePrelude};
239 use str::{Str, StrPrelude};
240 use str;
241 use string::String;
242 use uint;
243 use unicode::char::UnicodeChar;
244 use vec::Vec;
245
246 // Reexports
247 pub use self::stdio::stdin;
248 pub use self::stdio::stdout;
249 pub use self::stdio::stderr;
250 pub use self::stdio::print;
251 pub use self::stdio::println;
252
253 pub use self::fs::File;
254 pub use self::timer::Timer;
255 pub use self::net::ip::IpAddr;
256 pub use self::net::tcp::TcpListener;
257 pub use self::net::tcp::TcpStream;
258 pub use self::net::udp::UdpStream;
259 pub use self::pipe::PipeStream;
260 pub use self::process::{Process, Command};
261 pub use self::tempfile::TempDir;
262
263 pub use self::mem::{MemReader, BufReader, MemWriter, BufWriter};
264 pub use self::buffered::{BufferedReader, BufferedWriter, BufferedStream,
265                          LineBufferedWriter};
266 pub use self::comm_adapters::{ChanReader, ChanWriter};
267
268 mod buffered;
269 mod comm_adapters;
270 mod mem;
271 mod result;
272 mod tempfile;
273 pub mod extensions;
274 pub mod fs;
275 pub mod net;
276 pub mod pipe;
277 pub mod process;
278 pub mod stdio;
279 pub mod test;
280 pub mod timer;
281 pub mod util;
282
283 /// The default buffer size for various I/O operations
284 // libuv recommends 64k buffers to maximize throughput
285 // https://groups.google.com/forum/#!topic/libuv/oQO1HJAIDdA
286 const DEFAULT_BUF_SIZE: uint = 1024 * 64;
287
288 /// A convenient typedef of the return value of any I/O action.
289 pub type IoResult<T> = Result<T, IoError>;
290
291 /// The type passed to I/O condition handlers to indicate error
292 ///
293 /// # FIXME
294 ///
295 /// Is something like this sufficient? It's kind of archaic
296 #[deriving(PartialEq, Eq, Clone)]
297 pub struct IoError {
298     /// An enumeration which can be matched against for determining the flavor
299     /// of error.
300     pub kind: IoErrorKind,
301     /// A human-readable description about the error
302     pub desc: &'static str,
303     /// Detailed information about this error, not always available
304     pub detail: Option<String>
305 }
306
307 impl IoError {
308     /// Convert an `errno` value into an `IoError`.
309     ///
310     /// If `detail` is `true`, the `detail` field of the `IoError`
311     /// struct is filled with an allocated string describing the error
312     /// in more detail, retrieved from the operating system.
313     pub fn from_errno(errno: uint, detail: bool) -> IoError {
314         let mut err = sys::decode_error(errno as i32);
315         if detail && err.kind == OtherIoError {
316             err.detail = Some(os::error_string(errno).as_slice().chars()
317                                  .map(|c| c.to_lowercase()).collect())
318         }
319         err
320     }
321
322     /// Retrieve the last error to occur as a (detailed) IoError.
323     ///
324     /// This uses the OS `errno`, and so there should not be any task
325     /// descheduling or migration (other than that performed by the
326     /// operating system) between the call(s) for which errors are
327     /// being checked and the call of this function.
328     pub fn last_error() -> IoError {
329         IoError::from_errno(os::errno() as uint, true)
330     }
331 }
332
333 impl fmt::Show for IoError {
334     fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
335         match *self {
336             IoError { kind: OtherIoError, desc: "unknown error", detail: Some(ref detail) } =>
337                 write!(fmt, "{}", detail),
338             IoError { detail: None, desc, .. } =>
339                 write!(fmt, "{}", desc),
340             IoError { detail: Some(ref detail), desc, .. } =>
341                 write!(fmt, "{} ({})", desc, detail)
342         }
343     }
344 }
345
346 impl Error for IoError {
347     fn description(&self) -> &str {
348         self.desc
349     }
350
351     fn detail(&self) -> Option<String> {
352         self.detail.clone()
353     }
354 }
355
356 impl FromError<IoError> for Box<Error> {
357     fn from_error(err: IoError) -> Box<Error> {
358         box err
359     }
360 }
361
362 /// A list specifying general categories of I/O error.
363 #[deriving(PartialEq, Eq, Clone, Show)]
364 pub enum IoErrorKind {
365     /// Any I/O error not part of this list.
366     OtherIoError,
367     /// The operation could not complete because end of file was reached.
368     EndOfFile,
369     /// The file was not found.
370     FileNotFound,
371     /// The file permissions disallowed access to this file.
372     PermissionDenied,
373     /// A network connection failed for some reason not specified in this list.
374     ConnectionFailed,
375     /// The network operation failed because the network connection was closed.
376     Closed,
377     /// The connection was refused by the remote server.
378     ConnectionRefused,
379     /// The connection was reset by the remote server.
380     ConnectionReset,
381     /// The connection was aborted (terminated) by the remote server.
382     ConnectionAborted,
383     /// The network operation failed because it was not connected yet.
384     NotConnected,
385     /// The operation failed because a pipe was closed.
386     BrokenPipe,
387     /// A file already existed with that name.
388     PathAlreadyExists,
389     /// No file exists at that location.
390     PathDoesntExist,
391     /// The path did not specify the type of file that this operation required. For example,
392     /// attempting to copy a directory with the `fs::copy()` operation will fail with this error.
393     MismatchedFileTypeForOperation,
394     /// The operation temporarily failed (for example, because a signal was received), and retrying
395     /// may succeed.
396     ResourceUnavailable,
397     /// No I/O functionality is available for this task.
398     IoUnavailable,
399     /// A parameter was incorrect in a way that caused an I/O error not part of this list.
400     InvalidInput,
401     /// The I/O operation's timeout expired, causing it to be canceled.
402     TimedOut,
403     /// This write operation failed to write all of its data.
404     ///
405     /// Normally the write() method on a Writer guarantees that all of its data
406     /// has been written, but some operations may be terminated after only
407     /// partially writing some data. An example of this is a timed out write
408     /// which successfully wrote a known number of bytes, but bailed out after
409     /// doing so.
410     ///
411     /// The payload contained as part of this variant is the number of bytes
412     /// which are known to have been successfully written.
413     ShortWrite(uint),
414     /// The Reader returned 0 bytes from `read()` too many times.
415     NoProgress,
416 }
417
418 /// A trait that lets you add a `detail` to an IoError easily
419 trait UpdateIoError<T> {
420     /// Returns an IoError with updated description and detail
421     fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> Self;
422
423     /// Returns an IoError with updated detail
424     fn update_detail(self, detail: |&IoError| -> String) -> Self;
425
426     /// Returns an IoError with update description
427     fn update_desc(self, desc: &'static str) -> Self;
428 }
429
430 impl<T> UpdateIoError<T> for IoResult<T> {
431     fn update_err(self, desc: &'static str, detail: |&IoError| -> String) -> IoResult<T> {
432         self.map_err(|mut e| {
433             let detail = detail(&e);
434             e.desc = desc;
435             e.detail = Some(detail);
436             e
437         })
438     }
439
440     fn update_detail(self, detail: |&IoError| -> String) -> IoResult<T> {
441         self.map_err(|mut e| { e.detail = Some(detail(&e)); e })
442     }
443
444     fn update_desc(self, desc: &'static str) -> IoResult<T> {
445         self.map_err(|mut e| { e.desc = desc; e })
446     }
447 }
448
449 static NO_PROGRESS_LIMIT: uint = 1000;
450
451 /// A trait for objects which are byte-oriented streams. Readers are defined by
452 /// one method, `read`. This function will block until data is available,
453 /// filling in the provided buffer with any data read.
454 ///
455 /// Readers are intended to be composable with one another. Many objects
456 /// throughout the I/O and related libraries take and provide types which
457 /// implement the `Reader` trait.
458 pub trait Reader {
459
460     // Only method which need to get implemented for this trait
461
462     /// Read bytes, up to the length of `buf` and place them in `buf`.
463     /// Returns the number of bytes read. The number of bytes read may
464     /// be less than the number requested, even 0. Returns `Err` on EOF.
465     ///
466     /// # Error
467     ///
468     /// If an error occurs during this I/O operation, then it is returned as
469     /// `Err(IoError)`. Note that end-of-file is considered an error, and can be
470     /// inspected for in the error's `kind` field. Also note that reading 0
471     /// bytes is not considered an error in all circumstances
472     ///
473     /// # Implementation Note
474     ///
475     /// When implementing this method on a new Reader, you are strongly encouraged
476     /// not to return 0 if you can avoid it.
477     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint>;
478
479     // Convenient helper methods based on the above methods
480
481     /// Reads at least `min` bytes and places them in `buf`.
482     /// Returns the number of bytes read.
483     ///
484     /// This will continue to call `read` until at least `min` bytes have been
485     /// read. If `read` returns 0 too many times, `NoProgress` will be
486     /// returned.
487     ///
488     /// # Error
489     ///
490     /// If an error occurs at any point, that error is returned, and no further
491     /// bytes are read.
492     fn read_at_least(&mut self, min: uint, buf: &mut [u8]) -> IoResult<uint> {
493         if min > buf.len() {
494             return Err(IoError {
495                 detail: Some(String::from_str("the buffer is too short")),
496                 ..standard_error(InvalidInput)
497             });
498         }
499         let mut read = 0;
500         while read < min {
501             let mut zeroes = 0;
502             loop {
503                 match self.read(buf[mut read..]) {
504                     Ok(0) => {
505                         zeroes += 1;
506                         if zeroes >= NO_PROGRESS_LIMIT {
507                             return Err(standard_error(NoProgress));
508                         }
509                     }
510                     Ok(n) => {
511                         read += n;
512                         break;
513                     }
514                     err@Err(_) => return err
515                 }
516             }
517         }
518         Ok(read)
519     }
520
521     /// Reads a single byte. Returns `Err` on EOF.
522     fn read_byte(&mut self) -> IoResult<u8> {
523         let mut buf = [0];
524         try!(self.read_at_least(1, buf));
525         Ok(buf[0])
526     }
527
528     /// Reads up to `len` bytes and appends them to a vector.
529     /// Returns the number of bytes read. The number of bytes read may be
530     /// less than the number requested, even 0. Returns Err on EOF.
531     ///
532     /// # Error
533     ///
534     /// If an error occurs during this I/O operation, then it is returned
535     /// as `Err(IoError)`. See `read()` for more details.
536     fn push(&mut self, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
537         let start_len = buf.len();
538         buf.reserve(len);
539
540         let n = {
541             let s = unsafe { slice_vec_capacity(buf, start_len, start_len + len) };
542             try!(self.read(s))
543         };
544         unsafe { buf.set_len(start_len + n) };
545         Ok(n)
546     }
547
548     /// Reads at least `min` bytes, but no more than `len`, and appends them to
549     /// a vector.
550     /// Returns the number of bytes read.
551     ///
552     /// This will continue to call `read` until at least `min` bytes have been
553     /// read. If `read` returns 0 too many times, `NoProgress` will be
554     /// returned.
555     ///
556     /// # Error
557     ///
558     /// If an error occurs at any point, that error is returned, and no further
559     /// bytes are read.
560     fn push_at_least(&mut self, min: uint, len: uint, buf: &mut Vec<u8>) -> IoResult<uint> {
561         if min > len {
562             return Err(IoError {
563                 detail: Some(String::from_str("the buffer is too short")),
564                 ..standard_error(InvalidInput)
565             });
566         }
567
568         let start_len = buf.len();
569         buf.reserve(len);
570
571         // we can't just use self.read_at_least(min, slice) because we need to push
572         // successful reads onto the vector before any returned errors.
573
574         let mut read = 0;
575         while read < min {
576             read += {
577                 let s = unsafe { slice_vec_capacity(buf, start_len + read, start_len + len) };
578                 try!(self.read_at_least(1, s))
579             };
580             unsafe { buf.set_len(start_len + read) };
581         }
582         Ok(read)
583     }
584
585     /// Reads exactly `len` bytes and gives you back a new vector of length
586     /// `len`
587     ///
588     /// # Error
589     ///
590     /// Fails with the same conditions as `read`. Additionally returns error
591     /// on EOF. Note that if an error is returned, then some number of bytes may
592     /// have already been consumed from the underlying reader, and they are lost
593     /// (not returned as part of the error). If this is unacceptable, then it is
594     /// recommended to use the `push_at_least` or `read` methods.
595     fn read_exact(&mut self, len: uint) -> IoResult<Vec<u8>> {
596         let mut buf = Vec::with_capacity(len);
597         match self.push_at_least(len, len, &mut buf) {
598             Ok(_) => Ok(buf),
599             Err(e) => Err(e),
600         }
601     }
602
603     /// Reads all remaining bytes from the stream.
604     ///
605     /// # Error
606     ///
607     /// Returns any non-EOF error immediately. Previously read bytes are
608     /// discarded when an error is returned.
609     ///
610     /// When EOF is encountered, all bytes read up to that point are returned.
611     fn read_to_end(&mut self) -> IoResult<Vec<u8>> {
612         let mut buf = Vec::with_capacity(DEFAULT_BUF_SIZE);
613         loop {
614             match self.push_at_least(1, DEFAULT_BUF_SIZE, &mut buf) {
615                 Ok(_) => {}
616                 Err(ref e) if e.kind == EndOfFile => break,
617                 Err(e) => return Err(e)
618             }
619         }
620         return Ok(buf);
621     }
622
623     /// Reads all of the remaining bytes of this stream, interpreting them as a
624     /// UTF-8 encoded stream. The corresponding string is returned.
625     ///
626     /// # Error
627     ///
628     /// This function returns all of the same errors as `read_to_end` with an
629     /// additional error if the reader's contents are not a valid sequence of
630     /// UTF-8 bytes.
631     fn read_to_string(&mut self) -> IoResult<String> {
632         self.read_to_end().and_then(|s| {
633             match String::from_utf8(s) {
634                 Ok(s)  => Ok(s),
635                 Err(_) => Err(standard_error(InvalidInput)),
636             }
637         })
638     }
639
640     // Byte conversion helpers
641
642     /// Reads `n` little-endian unsigned integer bytes.
643     ///
644     /// `n` must be between 1 and 8, inclusive.
645     fn read_le_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
646         assert!(nbytes > 0 && nbytes <= 8);
647
648         let mut val = 0u64;
649         let mut pos = 0;
650         let mut i = nbytes;
651         while i > 0 {
652             val += (try!(self.read_u8()) as u64) << pos;
653             pos += 8;
654             i -= 1;
655         }
656         Ok(val)
657     }
658
659     /// Reads `n` little-endian signed integer bytes.
660     ///
661     /// `n` must be between 1 and 8, inclusive.
662     fn read_le_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
663         self.read_le_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
664     }
665
666     /// Reads `n` big-endian unsigned integer bytes.
667     ///
668     /// `n` must be between 1 and 8, inclusive.
669     fn read_be_uint_n(&mut self, nbytes: uint) -> IoResult<u64> {
670         assert!(nbytes > 0 && nbytes <= 8);
671
672         let mut val = 0u64;
673         let mut i = nbytes;
674         while i > 0 {
675             i -= 1;
676             val += (try!(self.read_u8()) as u64) << i * 8;
677         }
678         Ok(val)
679     }
680
681     /// Reads `n` big-endian signed integer bytes.
682     ///
683     /// `n` must be between 1 and 8, inclusive.
684     fn read_be_int_n(&mut self, nbytes: uint) -> IoResult<i64> {
685         self.read_be_uint_n(nbytes).map(|i| extend_sign(i, nbytes))
686     }
687
688     /// Reads a little-endian unsigned integer.
689     ///
690     /// The number of bytes returned is system-dependent.
691     fn read_le_uint(&mut self) -> IoResult<uint> {
692         self.read_le_uint_n(uint::BYTES).map(|i| i as uint)
693     }
694
695     /// Reads a little-endian integer.
696     ///
697     /// The number of bytes returned is system-dependent.
698     fn read_le_int(&mut self) -> IoResult<int> {
699         self.read_le_int_n(int::BYTES).map(|i| i as int)
700     }
701
702     /// Reads a big-endian unsigned integer.
703     ///
704     /// The number of bytes returned is system-dependent.
705     fn read_be_uint(&mut self) -> IoResult<uint> {
706         self.read_be_uint_n(uint::BYTES).map(|i| i as uint)
707     }
708
709     /// Reads a big-endian integer.
710     ///
711     /// The number of bytes returned is system-dependent.
712     fn read_be_int(&mut self) -> IoResult<int> {
713         self.read_be_int_n(int::BYTES).map(|i| i as int)
714     }
715
716     /// Reads a big-endian `u64`.
717     ///
718     /// `u64`s are 8 bytes long.
719     fn read_be_u64(&mut self) -> IoResult<u64> {
720         self.read_be_uint_n(8)
721     }
722
723     /// Reads a big-endian `u32`.
724     ///
725     /// `u32`s are 4 bytes long.
726     fn read_be_u32(&mut self) -> IoResult<u32> {
727         self.read_be_uint_n(4).map(|i| i as u32)
728     }
729
730     /// Reads a big-endian `u16`.
731     ///
732     /// `u16`s are 2 bytes long.
733     fn read_be_u16(&mut self) -> IoResult<u16> {
734         self.read_be_uint_n(2).map(|i| i as u16)
735     }
736
737     /// Reads a big-endian `i64`.
738     ///
739     /// `i64`s are 8 bytes long.
740     fn read_be_i64(&mut self) -> IoResult<i64> {
741         self.read_be_int_n(8)
742     }
743
744     /// Reads a big-endian `i32`.
745     ///
746     /// `i32`s are 4 bytes long.
747     fn read_be_i32(&mut self) -> IoResult<i32> {
748         self.read_be_int_n(4).map(|i| i as i32)
749     }
750
751     /// Reads a big-endian `i16`.
752     ///
753     /// `i16`s are 2 bytes long.
754     fn read_be_i16(&mut self) -> IoResult<i16> {
755         self.read_be_int_n(2).map(|i| i as i16)
756     }
757
758     /// Reads a big-endian `f64`.
759     ///
760     /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
761     fn read_be_f64(&mut self) -> IoResult<f64> {
762         self.read_be_u64().map(|i| unsafe {
763             transmute::<u64, f64>(i)
764         })
765     }
766
767     /// Reads a big-endian `f32`.
768     ///
769     /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
770     fn read_be_f32(&mut self) -> IoResult<f32> {
771         self.read_be_u32().map(|i| unsafe {
772             transmute::<u32, f32>(i)
773         })
774     }
775
776     /// Reads a little-endian `u64`.
777     ///
778     /// `u64`s are 8 bytes long.
779     fn read_le_u64(&mut self) -> IoResult<u64> {
780         self.read_le_uint_n(8)
781     }
782
783     /// Reads a little-endian `u32`.
784     ///
785     /// `u32`s are 4 bytes long.
786     fn read_le_u32(&mut self) -> IoResult<u32> {
787         self.read_le_uint_n(4).map(|i| i as u32)
788     }
789
790     /// Reads a little-endian `u16`.
791     ///
792     /// `u16`s are 2 bytes long.
793     fn read_le_u16(&mut self) -> IoResult<u16> {
794         self.read_le_uint_n(2).map(|i| i as u16)
795     }
796
797     /// Reads a little-endian `i64`.
798     ///
799     /// `i64`s are 8 bytes long.
800     fn read_le_i64(&mut self) -> IoResult<i64> {
801         self.read_le_int_n(8)
802     }
803
804     /// Reads a little-endian `i32`.
805     ///
806     /// `i32`s are 4 bytes long.
807     fn read_le_i32(&mut self) -> IoResult<i32> {
808         self.read_le_int_n(4).map(|i| i as i32)
809     }
810
811     /// Reads a little-endian `i16`.
812     ///
813     /// `i16`s are 2 bytes long.
814     fn read_le_i16(&mut self) -> IoResult<i16> {
815         self.read_le_int_n(2).map(|i| i as i16)
816     }
817
818     /// Reads a little-endian `f64`.
819     ///
820     /// `f64`s are 8 byte, IEEE754 double-precision floating point numbers.
821     fn read_le_f64(&mut self) -> IoResult<f64> {
822         self.read_le_u64().map(|i| unsafe {
823             transmute::<u64, f64>(i)
824         })
825     }
826
827     /// Reads a little-endian `f32`.
828     ///
829     /// `f32`s are 4 byte, IEEE754 single-precision floating point numbers.
830     fn read_le_f32(&mut self) -> IoResult<f32> {
831         self.read_le_u32().map(|i| unsafe {
832             transmute::<u32, f32>(i)
833         })
834     }
835
836     /// Read a u8.
837     ///
838     /// `u8`s are 1 byte.
839     fn read_u8(&mut self) -> IoResult<u8> {
840         self.read_byte()
841     }
842
843     /// Read an i8.
844     ///
845     /// `i8`s are 1 byte.
846     fn read_i8(&mut self) -> IoResult<i8> {
847         self.read_byte().map(|i| i as i8)
848     }
849 }
850
851 /// A reader which can be converted to a RefReader.
852 pub trait AsRefReader {
853     /// Creates a wrapper around a mutable reference to the reader.
854     ///
855     /// This is useful to allow applying adaptors while still
856     /// retaining ownership of the original value.
857     fn by_ref<'a>(&'a mut self) -> RefReader<'a, Self>;
858 }
859
860 impl<T: Reader> AsRefReader for T {
861     fn by_ref<'a>(&'a mut self) -> RefReader<'a, T> {
862         RefReader { inner: self }
863     }
864 }
865
866 /// A reader which can be converted to bytes.
867 pub trait BytesReader {
868     /// Create an iterator that reads a single byte on
869     /// each iteration, until EOF.
870     ///
871     /// # Error
872     ///
873     /// Any error other than `EndOfFile` that is produced by the underlying Reader
874     /// is returned by the iterator and should be handled by the caller.
875     fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, Self>;
876 }
877
878 impl<T: Reader> BytesReader for T {
879     fn bytes<'r>(&'r mut self) -> extensions::Bytes<'r, T> {
880         extensions::Bytes::new(self)
881     }
882 }
883
884 impl<'a> Reader for Box<Reader+'a> {
885     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
886         let reader: &mut Reader = &mut **self;
887         reader.read(buf)
888     }
889 }
890
891 impl<'a> Reader for &'a mut Reader+'a {
892     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { (*self).read(buf) }
893 }
894
895 /// Returns a slice of `v` between `start` and `end`.
896 ///
897 /// Similar to `slice()` except this function only bounds the slice on the
898 /// capacity of `v`, not the length.
899 ///
900 /// # Failure
901 ///
902 /// Fails when `start` or `end` point outside the capacity of `v`, or when
903 /// `start` > `end`.
904 // Private function here because we aren't sure if we want to expose this as
905 // API yet. If so, it should be a method on Vec.
906 unsafe fn slice_vec_capacity<'a, T>(v: &'a mut Vec<T>, start: uint, end: uint) -> &'a mut [T] {
907     use raw::Slice;
908     use ptr::RawPtr;
909
910     assert!(start <= end);
911     assert!(end <= v.capacity());
912     transmute(Slice {
913         data: v.as_ptr().offset(start as int),
914         len: end - start
915     })
916 }
917
918 /// A `RefReader` is a struct implementing `Reader` which contains a reference
919 /// to another reader. This is often useful when composing streams.
920 ///
921 /// # Example
922 ///
923 /// ```
924 /// # fn main() {}
925 /// # fn process_input<R: Reader>(r: R) {}
926 /// # fn foo() {
927 /// use std::io;
928 /// use std::io::AsRefReader;
929 /// use std::io::util::LimitReader;
930 ///
931 /// let mut stream = io::stdin();
932 ///
933 /// // Only allow the function to process at most one kilobyte of input
934 /// {
935 ///     let stream = LimitReader::new(stream.by_ref(), 1024);
936 ///     process_input(stream);
937 /// }
938 ///
939 /// // 'stream' is still available for use here
940 ///
941 /// # }
942 /// ```
943 pub struct RefReader<'a, R:'a> {
944     /// The underlying reader which this is referencing
945     inner: &'a mut R
946 }
947
948 impl<'a, R: Reader> Reader for RefReader<'a, R> {
949     fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> { self.inner.read(buf) }
950 }
951
952 impl<'a, R: Buffer> Buffer for RefReader<'a, R> {
953     fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]> { self.inner.fill_buf() }
954     fn consume(&mut self, amt: uint) { self.inner.consume(amt) }
955 }
956
957 fn extend_sign(val: u64, nbytes: uint) -> i64 {
958     let shift = (8 - nbytes) * 8;
959     (val << shift) as i64 >> shift
960 }
961
962 /// A trait for objects which are byte-oriented streams. Writers are defined by
963 /// one method, `write`. This function will block until the provided buffer of
964 /// bytes has been entirely written, and it will return any failures which occur.
965 ///
966 /// Another commonly overridden method is the `flush` method for writers such as
967 /// buffered writers.
968 ///
969 /// Writers are intended to be composable with one another. Many objects
970 /// throughout the I/O and related libraries take and provide types which
971 /// implement the `Writer` trait.
972 pub trait Writer {
973     /// Write the entirety of a given buffer
974     ///
975     /// # Errors
976     ///
977     /// If an error happens during the I/O operation, the error is returned as
978     /// `Err`. Note that it is considered an error if the entire buffer could
979     /// not be written, and if an error is returned then it is unknown how much
980     /// data (if any) was actually written.
981     fn write(&mut self, buf: &[u8]) -> IoResult<()>;
982
983     /// Flush this output stream, ensuring that all intermediately buffered
984     /// contents reach their destination.
985     ///
986     /// This is by default a no-op and implementers of the `Writer` trait should
987     /// decide whether their stream needs to be buffered or not.
988     fn flush(&mut self) -> IoResult<()> { Ok(()) }
989
990     /// Writes a formatted string into this writer, returning any error
991     /// encountered.
992     ///
993     /// This method is primarily used to interface with the `format_args!`
994     /// macro, but it is rare that this should explicitly be called. The
995     /// `write!` macro should be favored to invoke this method instead.
996     ///
997     /// # Errors
998     ///
999     /// This function will return any I/O error reported while formatting.
1000     fn write_fmt(&mut self, fmt: &fmt::Arguments) -> IoResult<()> {
1001         // Create a shim which translates a Writer to a FormatWriter and saves
1002         // off I/O errors. instead of discarding them
1003         struct Adaptor<'a, T:'a> {
1004             inner: &'a mut T,
1005             error: IoResult<()>,
1006         }
1007
1008         impl<'a, T: Writer> fmt::FormatWriter for Adaptor<'a, T> {
1009             fn write(&mut self, bytes: &[u8]) -> fmt::Result {
1010                 match self.inner.write(bytes) {
1011                     Ok(()) => Ok(()),
1012                     Err(e) => {
1013                         self.error = Err(e);
1014                         Err(fmt::WriteError)
1015                     }
1016                 }
1017             }
1018         }
1019
1020         let mut output = Adaptor { inner: self, error: Ok(()) };
1021         match fmt::write(&mut output, fmt) {
1022             Ok(()) => Ok(()),
1023             Err(..) => output.error
1024         }
1025     }
1026
1027     /// Write a rust string into this sink.
1028     ///
1029     /// The bytes written will be the UTF-8 encoded version of the input string.
1030     /// If other encodings are desired, it is recommended to compose this stream
1031     /// with another performing the conversion, or to use `write` with a
1032     /// converted byte-array instead.
1033     #[inline]
1034     fn write_str(&mut self, s: &str) -> IoResult<()> {
1035         self.write(s.as_bytes())
1036     }
1037
1038     /// Writes a string into this sink, and then writes a literal newline (`\n`)
1039     /// byte afterwards. Note that the writing of the newline is *not* atomic in
1040     /// the sense that the call to `write` is invoked twice (once with the
1041     /// string and once with a newline character).
1042     ///
1043     /// If other encodings or line ending flavors are desired, it is recommended
1044     /// that the `write` method is used specifically instead.
1045     #[inline]
1046     fn write_line(&mut self, s: &str) -> IoResult<()> {
1047         self.write_str(s).and_then(|()| self.write([b'\n']))
1048     }
1049
1050     /// Write a single char, encoded as UTF-8.
1051     #[inline]
1052     fn write_char(&mut self, c: char) -> IoResult<()> {
1053         let mut buf = [0u8, ..4];
1054         let n = c.encode_utf8(buf[mut]).unwrap_or(0);
1055         self.write(buf[..n])
1056     }
1057
1058     /// Write the result of passing n through `int::to_str_bytes`.
1059     #[inline]
1060     fn write_int(&mut self, n: int) -> IoResult<()> {
1061         write!(self, "{:d}", n)
1062     }
1063
1064     /// Write the result of passing n through `uint::to_str_bytes`.
1065     #[inline]
1066     fn write_uint(&mut self, n: uint) -> IoResult<()> {
1067         write!(self, "{:u}", n)
1068     }
1069
1070     /// Write a little-endian uint (number of bytes depends on system).
1071     #[inline]
1072     fn write_le_uint(&mut self, n: uint) -> IoResult<()> {
1073         extensions::u64_to_le_bytes(n as u64, uint::BYTES, |v| self.write(v))
1074     }
1075
1076     /// Write a little-endian int (number of bytes depends on system).
1077     #[inline]
1078     fn write_le_int(&mut self, n: int) -> IoResult<()> {
1079         extensions::u64_to_le_bytes(n as u64, int::BYTES, |v| self.write(v))
1080     }
1081
1082     /// Write a big-endian uint (number of bytes depends on system).
1083     #[inline]
1084     fn write_be_uint(&mut self, n: uint) -> IoResult<()> {
1085         extensions::u64_to_be_bytes(n as u64, uint::BYTES, |v| self.write(v))
1086     }
1087
1088     /// Write a big-endian int (number of bytes depends on system).
1089     #[inline]
1090     fn write_be_int(&mut self, n: int) -> IoResult<()> {
1091         extensions::u64_to_be_bytes(n as u64, int::BYTES, |v| self.write(v))
1092     }
1093
1094     /// Write a big-endian u64 (8 bytes).
1095     #[inline]
1096     fn write_be_u64(&mut self, n: u64) -> IoResult<()> {
1097         extensions::u64_to_be_bytes(n, 8u, |v| self.write(v))
1098     }
1099
1100     /// Write a big-endian u32 (4 bytes).
1101     #[inline]
1102     fn write_be_u32(&mut self, n: u32) -> IoResult<()> {
1103         extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1104     }
1105
1106     /// Write a big-endian u16 (2 bytes).
1107     #[inline]
1108     fn write_be_u16(&mut self, n: u16) -> IoResult<()> {
1109         extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1110     }
1111
1112     /// Write a big-endian i64 (8 bytes).
1113     #[inline]
1114     fn write_be_i64(&mut self, n: i64) -> IoResult<()> {
1115         extensions::u64_to_be_bytes(n as u64, 8u, |v| self.write(v))
1116     }
1117
1118     /// Write a big-endian i32 (4 bytes).
1119     #[inline]
1120     fn write_be_i32(&mut self, n: i32) -> IoResult<()> {
1121         extensions::u64_to_be_bytes(n as u64, 4u, |v| self.write(v))
1122     }
1123
1124     /// Write a big-endian i16 (2 bytes).
1125     #[inline]
1126     fn write_be_i16(&mut self, n: i16) -> IoResult<()> {
1127         extensions::u64_to_be_bytes(n as u64, 2u, |v| self.write(v))
1128     }
1129
1130     /// Write a big-endian IEEE754 double-precision floating-point (8 bytes).
1131     #[inline]
1132     fn write_be_f64(&mut self, f: f64) -> IoResult<()> {
1133         unsafe {
1134             self.write_be_u64(transmute(f))
1135         }
1136     }
1137
1138     /// Write a big-endian IEEE754 single-precision floating-point (4 bytes).
1139     #[inline]
1140     fn write_be_f32(&mut self, f: f32) -> IoResult<()> {
1141         unsafe {
1142             self.write_be_u32(transmute(f))
1143         }
1144     }
1145
1146     /// Write a little-endian u64 (8 bytes).
1147     #[inline]
1148     fn write_le_u64(&mut self, n: u64) -> IoResult<()> {
1149         extensions::u64_to_le_bytes(n, 8u, |v| self.write(v))
1150     }
1151
1152     /// Write a little-endian u32 (4 bytes).
1153     #[inline]
1154     fn write_le_u32(&mut self, n: u32) -> IoResult<()> {
1155         extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1156     }
1157
1158     /// Write a little-endian u16 (2 bytes).
1159     #[inline]
1160     fn write_le_u16(&mut self, n: u16) -> IoResult<()> {
1161         extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1162     }
1163
1164     /// Write a little-endian i64 (8 bytes).
1165     #[inline]
1166     fn write_le_i64(&mut self, n: i64) -> IoResult<()> {
1167         extensions::u64_to_le_bytes(n as u64, 8u, |v| self.write(v))
1168     }
1169
1170     /// Write a little-endian i32 (4 bytes).
1171     #[inline]
1172     fn write_le_i32(&mut self, n: i32) -> IoResult<()> {
1173         extensions::u64_to_le_bytes(n as u64, 4u, |v| self.write(v))
1174     }
1175
1176     /// Write a little-endian i16 (2 bytes).
1177     #[inline]
1178     fn write_le_i16(&mut self, n: i16) -> IoResult<()> {
1179         extensions::u64_to_le_bytes(n as u64, 2u, |v| self.write(v))
1180     }
1181
1182     /// Write a little-endian IEEE754 double-precision floating-point
1183     /// (8 bytes).
1184     #[inline]
1185     fn write_le_f64(&mut self, f: f64) -> IoResult<()> {
1186         unsafe {
1187             self.write_le_u64(transmute(f))
1188         }
1189     }
1190
1191     /// Write a little-endian IEEE754 single-precision floating-point
1192     /// (4 bytes).
1193     #[inline]
1194     fn write_le_f32(&mut self, f: f32) -> IoResult<()> {
1195         unsafe {
1196             self.write_le_u32(transmute(f))
1197         }
1198     }
1199
1200     /// Write a u8 (1 byte).
1201     #[inline]
1202     fn write_u8(&mut self, n: u8) -> IoResult<()> {
1203         self.write([n])
1204     }
1205
1206     /// Write an i8 (1 byte).
1207     #[inline]
1208     fn write_i8(&mut self, n: i8) -> IoResult<()> {
1209         self.write([n as u8])
1210     }
1211 }
1212
1213 /// A writer which can be converted to a RefWriter.
1214 pub trait AsRefWriter {
1215     /// Creates a wrapper around a mutable reference to the writer.
1216     ///
1217     /// This is useful to allow applying wrappers while still
1218     /// retaining ownership of the original value.
1219     #[inline]
1220     fn by_ref<'a>(&'a mut self) -> RefWriter<'a, Self>;
1221 }
1222
1223 impl<T: Writer> AsRefWriter for T {
1224     fn by_ref<'a>(&'a mut self) -> RefWriter<'a, T> {
1225         RefWriter { inner: self }
1226     }
1227 }
1228
1229 impl<'a> Writer for Box<Writer+'a> {
1230     #[inline]
1231     fn write(&mut self, buf: &[u8]) -> IoResult<()> {
1232         (&mut **self).write(buf)
1233     }
1234
1235     #[inline]
1236     fn flush(&mut self) -> IoResult<()> {
1237         (&mut **self).flush()
1238     }
1239 }
1240
1241 impl<'a> Writer for &'a mut Writer+'a {
1242     #[inline]
1243     fn write(&mut self, buf: &[u8]) -> IoResult<()> { (**self).write(buf) }
1244
1245     #[inline]
1246     fn flush(&mut self) -> IoResult<()> { (**self).flush() }
1247 }
1248
1249 /// A `RefWriter` is a struct implementing `Writer` which contains a reference
1250 /// to another writer. This is often useful when composing streams.
1251 ///
1252 /// # Example
1253 ///
1254 /// ```
1255 /// # fn main() {}
1256 /// # fn process_input<R: Reader>(r: R) {}
1257 /// # fn foo () {
1258 /// use std::io::util::TeeReader;
1259 /// use std::io::{stdin, MemWriter, AsRefWriter};
1260 ///
1261 /// let mut output = MemWriter::new();
1262 ///
1263 /// {
1264 ///     // Don't give ownership of 'output' to the 'tee'. Instead we keep a
1265 ///     // handle to it in the outer scope
1266 ///     let mut tee = TeeReader::new(stdin(), output.by_ref());
1267 ///     process_input(tee);
1268 /// }
1269 ///
1270 /// println!("input processed: {}", output.unwrap());
1271 /// # }
1272 /// ```
1273 pub struct RefWriter<'a, W:'a> {
1274     /// The underlying writer which this is referencing
1275     inner: &'a mut W
1276 }
1277
1278 impl<'a, W: Writer> Writer for RefWriter<'a, W> {
1279     #[inline]
1280     fn write(&mut self, buf: &[u8]) -> IoResult<()> { self.inner.write(buf) }
1281
1282     #[inline]
1283     fn flush(&mut self) -> IoResult<()> { self.inner.flush() }
1284 }
1285
1286
1287 /// A Stream is a readable and a writable object. Data written is typically
1288 /// received by the object which reads receive data from.
1289 pub trait Stream: Reader + Writer { }
1290
1291 impl<T: Reader + Writer> Stream for T {}
1292
1293 /// An iterator that reads a line on each iteration,
1294 /// until `.read_line()` encounters `EndOfFile`.
1295 ///
1296 /// # Notes about the Iteration Protocol
1297 ///
1298 /// The `Lines` may yield `None` and thus terminate
1299 /// an iteration, but continue to yield elements if iteration
1300 /// is attempted again.
1301 ///
1302 /// # Error
1303 ///
1304 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1305 /// is returned by the iterator and should be handled by the caller.
1306 pub struct Lines<'r, T:'r> {
1307     buffer: &'r mut T,
1308 }
1309
1310 impl<'r, T: Buffer> Iterator<IoResult<String>> for Lines<'r, T> {
1311     fn next(&mut self) -> Option<IoResult<String>> {
1312         match self.buffer.read_line() {
1313             Ok(x) => Some(Ok(x)),
1314             Err(IoError { kind: EndOfFile, ..}) => None,
1315             Err(y) => Some(Err(y))
1316         }
1317     }
1318 }
1319
1320 /// An iterator that reads a utf8-encoded character on each iteration,
1321 /// until `.read_char()` encounters `EndOfFile`.
1322 ///
1323 /// # Notes about the Iteration Protocol
1324 ///
1325 /// The `Chars` may yield `None` and thus terminate
1326 /// an iteration, but continue to yield elements if iteration
1327 /// is attempted again.
1328 ///
1329 /// # Error
1330 ///
1331 /// Any error other than `EndOfFile` that is produced by the underlying Reader
1332 /// is returned by the iterator and should be handled by the caller.
1333 pub struct Chars<'r, T:'r> {
1334     buffer: &'r mut T
1335 }
1336
1337 impl<'r, T: Buffer> Iterator<IoResult<char>> for Chars<'r, T> {
1338     fn next(&mut self) -> Option<IoResult<char>> {
1339         match self.buffer.read_char() {
1340             Ok(x) => Some(Ok(x)),
1341             Err(IoError { kind: EndOfFile, ..}) => None,
1342             Err(y) => Some(Err(y))
1343         }
1344     }
1345 }
1346
1347 /// A Buffer is a type of reader which has some form of internal buffering to
1348 /// allow certain kinds of reading operations to be more optimized than others.
1349 /// This type extends the `Reader` trait with a few methods that are not
1350 /// possible to reasonably implement with purely a read interface.
1351 pub trait Buffer: Reader {
1352     /// Fills the internal buffer of this object, returning the buffer contents.
1353     /// Note that none of the contents will be "read" in the sense that later
1354     /// calling `read` may return the same contents.
1355     ///
1356     /// The `consume` function must be called with the number of bytes that are
1357     /// consumed from this buffer returned to ensure that the bytes are never
1358     /// returned twice.
1359     ///
1360     /// # Error
1361     ///
1362     /// This function will return an I/O error if the underlying reader was
1363     /// read, but returned an error. Note that it is not an error to return a
1364     /// 0-length buffer.
1365     fn fill_buf<'a>(&'a mut self) -> IoResult<&'a [u8]>;
1366
1367     /// Tells this buffer that `amt` bytes have been consumed from the buffer,
1368     /// so they should no longer be returned in calls to `read`.
1369     fn consume(&mut self, amt: uint);
1370
1371     /// Reads the next line of input, interpreted as a sequence of UTF-8
1372     /// encoded Unicode codepoints. If a newline is encountered, then the
1373     /// newline is contained in the returned string.
1374     ///
1375     /// # Example
1376     ///
1377     /// ```rust
1378     /// use std::io;
1379     ///
1380     /// let mut reader = io::stdin();
1381     /// let input = reader.read_line().ok().unwrap_or("nothing".to_string());
1382     /// ```
1383     ///
1384     /// # Error
1385     ///
1386     /// This function has the same error semantics as `read_until`:
1387     ///
1388     /// * All non-EOF errors will be returned immediately
1389     /// * If an error is returned previously consumed bytes are lost
1390     /// * EOF is only returned if no bytes have been read
1391     /// * Reach EOF may mean that the delimiter is not present in the return
1392     ///   value
1393     ///
1394     /// Additionally, this function can fail if the line of input read is not a
1395     /// valid UTF-8 sequence of bytes.
1396     fn read_line(&mut self) -> IoResult<String> {
1397         self.read_until(b'\n').and_then(|line|
1398             match String::from_utf8(line) {
1399                 Ok(s)  => Ok(s),
1400                 Err(_) => Err(standard_error(InvalidInput)),
1401             }
1402         )
1403     }
1404
1405     /// Create an iterator that reads a line on each iteration until EOF.
1406     ///
1407     /// # Error
1408     ///
1409     /// Any error other than `EndOfFile` that is produced by the underlying Reader
1410     /// is returned by the iterator and should be handled by the caller.
1411     fn lines<'r>(&'r mut self) -> Lines<'r, Self> {
1412         Lines { buffer: self }
1413     }
1414
1415     /// Reads a sequence of bytes leading up to a specified delimiter. Once the
1416     /// specified byte is encountered, reading ceases and the bytes up to and
1417     /// including the delimiter are returned.
1418     ///
1419     /// # Error
1420     ///
1421     /// If any I/O error is encountered other than EOF, the error is immediately
1422     /// returned. Note that this may discard bytes which have already been read,
1423     /// and those bytes will *not* be returned. It is recommended to use other
1424     /// methods if this case is worrying.
1425     ///
1426     /// If EOF is encountered, then this function will return EOF if 0 bytes
1427     /// have been read, otherwise the pending byte buffer is returned. This
1428     /// is the reason that the byte buffer returned may not always contain the
1429     /// delimiter.
1430     fn read_until(&mut self, byte: u8) -> IoResult<Vec<u8>> {
1431         let mut res = Vec::new();
1432
1433         let mut used;
1434         loop {
1435             {
1436                 let available = match self.fill_buf() {
1437                     Ok(n) => n,
1438                     Err(ref e) if res.len() > 0 && e.kind == EndOfFile => {
1439                         used = 0;
1440                         break
1441                     }
1442                     Err(e) => return Err(e)
1443                 };
1444                 match available.iter().position(|&b| b == byte) {
1445                     Some(i) => {
1446                         res.push_all(available[..i + 1]);
1447                         used = i + 1;
1448                         break
1449                     }
1450                     None => {
1451                         res.push_all(available);
1452                         used = available.len();
1453                     }
1454                 }
1455             }
1456             self.consume(used);
1457         }
1458         self.consume(used);
1459         Ok(res)
1460     }
1461
1462     /// Reads the next utf8-encoded character from the underlying stream.
1463     ///
1464     /// # Error
1465     ///
1466     /// If an I/O error occurs, or EOF, then this function will return `Err`.
1467     /// This function will also return error if the stream does not contain a
1468     /// valid utf-8 encoded codepoint as the next few bytes in the stream.
1469     fn read_char(&mut self) -> IoResult<char> {
1470         let first_byte = try!(self.read_byte());
1471         let width = str::utf8_char_width(first_byte);
1472         if width == 1 { return Ok(first_byte as char) }
1473         if width == 0 { return Err(standard_error(InvalidInput)) } // not utf8
1474         let mut buf = [first_byte, 0, 0, 0];
1475         {
1476             let mut start = 1;
1477             while start < width {
1478                 match try!(self.read(buf[mut start..width])) {
1479                     n if n == width - start => break,
1480                     n if n < width - start => { start += n; }
1481                     _ => return Err(standard_error(InvalidInput)),
1482                 }
1483             }
1484         }
1485         match str::from_utf8(buf[..width]) {
1486             Some(s) => Ok(s.char_at(0)),
1487             None => Err(standard_error(InvalidInput))
1488         }
1489     }
1490
1491     /// Create an iterator that reads a utf8-encoded character on each iteration
1492     /// until EOF.
1493     ///
1494     /// # Error
1495     ///
1496     /// Any error other than `EndOfFile` that is produced by the underlying Reader
1497     /// is returned by the iterator and should be handled by the caller.
1498     fn chars<'r>(&'r mut self) -> Chars<'r, Self> {
1499         Chars { buffer: self }
1500     }
1501 }
1502
1503 /// When seeking, the resulting cursor is offset from a base by the offset given
1504 /// to the `seek` function. The base used is specified by this enumeration.
1505 pub enum SeekStyle {
1506     /// Seek from the beginning of the stream
1507     SeekSet,
1508     /// Seek from the end of the stream
1509     SeekEnd,
1510     /// Seek from the current position
1511     SeekCur,
1512 }
1513
1514 /// An object implementing `Seek` internally has some form of cursor which can
1515 /// be moved within a stream of bytes. The stream typically has a fixed size,
1516 /// allowing seeking relative to either end.
1517 pub trait Seek {
1518     /// Return position of file cursor in the stream
1519     fn tell(&self) -> IoResult<u64>;
1520
1521     /// Seek to an offset in a stream
1522     ///
1523     /// A successful seek clears the EOF indicator. Seeking beyond EOF is
1524     /// allowed, but seeking before position 0 is not allowed.
1525     ///
1526     /// # Errors
1527     ///
1528     /// * Seeking to a negative offset is considered an error
1529     /// * Seeking past the end of the stream does not modify the underlying
1530     ///   stream, but the next write may cause the previous data to be filled in
1531     ///   with a bit pattern.
1532     fn seek(&mut self, pos: i64, style: SeekStyle) -> IoResult<()>;
1533 }
1534
1535 /// A listener is a value that can consume itself to start listening for
1536 /// connections.
1537 ///
1538 /// Doing so produces some sort of Acceptor.
1539 pub trait Listener<T, A: Acceptor<T>> {
1540     /// Spin up the listener and start queuing incoming connections
1541     ///
1542     /// # Error
1543     ///
1544     /// Returns `Err` if this listener could not be bound to listen for
1545     /// connections. In all cases, this listener is consumed.
1546     fn listen(self) -> IoResult<A>;
1547 }
1548
1549 /// An acceptor is a value that presents incoming connections
1550 pub trait Acceptor<T> {
1551     /// Wait for and accept an incoming connection
1552     ///
1553     /// # Error
1554     ///
1555     /// Returns `Err` if an I/O error is encountered.
1556     fn accept(&mut self) -> IoResult<T>;
1557
1558     /// Create an iterator over incoming connection attempts.
1559     ///
1560     /// Note that I/O errors will be yielded by the iterator itself.
1561     fn incoming<'r>(&'r mut self) -> IncomingConnections<'r, Self> {
1562         IncomingConnections { inc: self }
1563     }
1564 }
1565
1566 /// An infinite iterator over incoming connection attempts.
1567 /// Calling `next` will block the task until a connection is attempted.
1568 ///
1569 /// Since connection attempts can continue forever, this iterator always returns
1570 /// `Some`. The `Some` contains the `IoResult` representing whether the
1571 /// connection attempt was successful.  A successful connection will be wrapped
1572 /// in `Ok`. A failed connection is represented as an `Err`.
1573 pub struct IncomingConnections<'a, A:'a> {
1574     inc: &'a mut A,
1575 }
1576
1577 impl<'a, T, A: Acceptor<T>> Iterator<IoResult<T>> for IncomingConnections<'a, A> {
1578     fn next(&mut self) -> Option<IoResult<T>> {
1579         Some(self.inc.accept())
1580     }
1581 }
1582
1583 /// Creates a standard error for a commonly used flavor of error. The `detail`
1584 /// field of the returned error will always be `None`.
1585 ///
1586 /// # Example
1587 ///
1588 /// ```
1589 /// use std::io;
1590 ///
1591 /// let eof = io::standard_error(io::EndOfFile);
1592 /// let einval = io::standard_error(io::InvalidInput);
1593 /// ```
1594 pub fn standard_error(kind: IoErrorKind) -> IoError {
1595     let desc = match kind {
1596         EndOfFile => "end of file",
1597         IoUnavailable => "I/O is unavailable",
1598         InvalidInput => "invalid input",
1599         OtherIoError => "unknown I/O error",
1600         FileNotFound => "file not found",
1601         PermissionDenied => "permission denied",
1602         ConnectionFailed => "connection failed",
1603         Closed => "stream is closed",
1604         ConnectionRefused => "connection refused",
1605         ConnectionReset => "connection reset",
1606         ConnectionAborted => "connection aborted",
1607         NotConnected => "not connected",
1608         BrokenPipe => "broken pipe",
1609         PathAlreadyExists => "file already exists",
1610         PathDoesntExist => "no such file",
1611         MismatchedFileTypeForOperation => "mismatched file type",
1612         ResourceUnavailable => "resource unavailable",
1613         TimedOut => "operation timed out",
1614         ShortWrite(..) => "short write",
1615         NoProgress => "no progress",
1616     };
1617     IoError {
1618         kind: kind,
1619         desc: desc,
1620         detail: None,
1621     }
1622 }
1623
1624 /// A mode specifies how a file should be opened or created. These modes are
1625 /// passed to `File::open_mode` and are used to control where the file is
1626 /// positioned when it is initially opened.
1627 pub enum FileMode {
1628     /// Opens a file positioned at the beginning.
1629     Open,
1630     /// Opens a file positioned at EOF.
1631     Append,
1632     /// Opens a file, truncating it if it already exists.
1633     Truncate,
1634 }
1635
1636 /// Access permissions with which the file should be opened. `File`s
1637 /// opened with `Read` will return an error if written to.
1638 pub enum FileAccess {
1639     /// Read-only access, requests to write will result in an error
1640     Read,
1641     /// Write-only access, requests to read will result in an error
1642     Write,
1643     /// Read-write access, no requests are denied by default
1644     ReadWrite,
1645 }
1646
1647 /// Different kinds of files which can be identified by a call to stat
1648 #[deriving(PartialEq, Show, Hash, Clone)]
1649 pub enum FileType {
1650     /// This is a normal file, corresponding to `S_IFREG`
1651     TypeFile,
1652
1653     /// This file is a directory, corresponding to `S_IFDIR`
1654     TypeDirectory,
1655
1656     /// This file is a named pipe, corresponding to `S_IFIFO`
1657     TypeNamedPipe,
1658
1659     /// This file is a block device, corresponding to `S_IFBLK`
1660     TypeBlockSpecial,
1661
1662     /// This file is a symbolic link to another file, corresponding to `S_IFLNK`
1663     TypeSymlink,
1664
1665     /// The type of this file is not recognized as one of the other categories
1666     TypeUnknown,
1667 }
1668
1669 /// A structure used to describe metadata information about a file. This
1670 /// structure is created through the `stat` method on a `Path`.
1671 ///
1672 /// # Example
1673 ///
1674 /// ```
1675 /// # use std::io::fs::PathExtensions;
1676 /// # fn main() {}
1677 /// # fn foo() {
1678 /// let info = match Path::new("foo.txt").stat() {
1679 ///     Ok(stat) => stat,
1680 ///     Err(e) => panic!("couldn't read foo.txt: {}", e),
1681 /// };
1682 ///
1683 /// println!("byte size: {}", info.size);
1684 /// # }
1685 /// ```
1686 #[deriving(Hash)]
1687 pub struct FileStat {
1688     /// The size of the file, in bytes
1689     pub size: u64,
1690     /// The kind of file this path points to (directory, file, pipe, etc.)
1691     pub kind: FileType,
1692     /// The file permissions currently on the file
1693     pub perm: FilePermission,
1694
1695     // FIXME(#10301): These time fields are pretty useless without an actual
1696     //                time representation, what are the milliseconds relative
1697     //                to?
1698
1699     /// The time that the file was created at, in platform-dependent
1700     /// milliseconds
1701     pub created: u64,
1702     /// The time that this file was last modified, in platform-dependent
1703     /// milliseconds
1704     pub modified: u64,
1705     /// The time that this file was last accessed, in platform-dependent
1706     /// milliseconds
1707     pub accessed: u64,
1708
1709     /// Information returned by stat() which is not guaranteed to be
1710     /// platform-independent. This information may be useful on some platforms,
1711     /// but it may have different meanings or no meaning at all on other
1712     /// platforms.
1713     ///
1714     /// Usage of this field is discouraged, but if access is desired then the
1715     /// fields are located here.
1716     #[unstable]
1717     pub unstable: UnstableFileStat,
1718 }
1719
1720 /// This structure represents all of the possible information which can be
1721 /// returned from a `stat` syscall which is not contained in the `FileStat`
1722 /// structure. This information is not necessarily platform independent, and may
1723 /// have different meanings or no meaning at all on some platforms.
1724 #[unstable]
1725 #[deriving(Hash)]
1726 pub struct UnstableFileStat {
1727     /// The ID of the device containing the file.
1728     pub device: u64,
1729     /// The file serial number.
1730     pub inode: u64,
1731     /// The device ID.
1732     pub rdev: u64,
1733     /// The number of hard links to this file.
1734     pub nlink: u64,
1735     /// The user ID of the file.
1736     pub uid: u64,
1737     /// The group ID of the file.
1738     pub gid: u64,
1739     /// The optimal block size for I/O.
1740     pub blksize: u64,
1741     /// The blocks allocated for this file.
1742     pub blocks: u64,
1743     /// User-defined flags for the file.
1744     pub flags: u64,
1745     /// The file generation number.
1746     pub gen: u64,
1747 }
1748
1749 bitflags! {
1750     #[doc = "A set of permissions for a file or directory is represented"]
1751     #[doc = "by a set of flags which are or'd together."]
1752     flags FilePermission: u32 {
1753         const USER_READ     = 0o400,
1754         const USER_WRITE    = 0o200,
1755         const USER_EXECUTE  = 0o100,
1756         const GROUP_READ    = 0o040,
1757         const GROUP_WRITE   = 0o020,
1758         const GROUP_EXECUTE = 0o010,
1759         const OTHER_READ    = 0o004,
1760         const OTHER_WRITE   = 0o002,
1761         const OTHER_EXECUTE = 0o001,
1762
1763         const USER_RWX  = USER_READ.bits | USER_WRITE.bits | USER_EXECUTE.bits,
1764         const GROUP_RWX = GROUP_READ.bits | GROUP_WRITE.bits | GROUP_EXECUTE.bits,
1765         const OTHER_RWX = OTHER_READ.bits | OTHER_WRITE.bits | OTHER_EXECUTE.bits,
1766
1767         #[doc = "Permissions for user owned files, equivalent to 0644 on"]
1768         #[doc = "unix-like systems."]
1769         const USER_FILE = USER_READ.bits | USER_WRITE.bits | GROUP_READ.bits | OTHER_READ.bits,
1770
1771         #[doc = "Permissions for user owned directories, equivalent to 0755 on"]
1772         #[doc = "unix-like systems."]
1773         const USER_DIR  = USER_RWX.bits | GROUP_READ.bits | GROUP_EXECUTE.bits |
1774                    OTHER_READ.bits | OTHER_EXECUTE.bits,
1775
1776         #[doc = "Permissions for user owned executables, equivalent to 0755"]
1777         #[doc = "on unix-like systems."]
1778         const USER_EXEC = USER_DIR.bits,
1779
1780         #[doc = "All possible permissions enabled."]
1781         const ALL_PERMISSIONS = USER_RWX.bits | GROUP_RWX.bits | OTHER_RWX.bits,
1782
1783         // Deprecated names
1784         #[allow(non_upper_case_globals)]
1785         #[deprecated = "use USER_READ instead"]
1786         const UserRead     = USER_READ.bits,
1787         #[allow(non_upper_case_globals)]
1788         #[deprecated = "use USER_WRITE instead"]
1789         const UserWrite    = USER_WRITE.bits,
1790         #[allow(non_upper_case_globals)]
1791         #[deprecated = "use USER_EXECUTE instead"]
1792         const UserExecute  = USER_EXECUTE.bits,
1793         #[allow(non_upper_case_globals)]
1794         #[deprecated = "use GROUP_READ instead"]
1795         const GroupRead    = GROUP_READ.bits,
1796         #[allow(non_upper_case_globals)]
1797         #[deprecated = "use GROUP_WRITE instead"]
1798         const GroupWrite   = GROUP_WRITE.bits,
1799         #[allow(non_upper_case_globals)]
1800         #[deprecated = "use GROUP_EXECUTE instead"]
1801         const GroupExecute = GROUP_EXECUTE.bits,
1802         #[allow(non_upper_case_globals)]
1803         #[deprecated = "use OTHER_READ instead"]
1804         const OtherRead    = OTHER_READ.bits,
1805         #[allow(non_upper_case_globals)]
1806         #[deprecated = "use OTHER_WRITE instead"]
1807         const OtherWrite   = OTHER_WRITE.bits,
1808         #[allow(non_upper_case_globals)]
1809         #[deprecated = "use OTHER_EXECUTE instead"]
1810         const OtherExecute = OTHER_EXECUTE.bits,
1811
1812         #[allow(non_upper_case_globals)]
1813         #[deprecated = "use USER_RWX instead"]
1814         const UserRWX  = USER_RWX.bits,
1815         #[allow(non_upper_case_globals)]
1816         #[deprecated = "use GROUP_RWX instead"]
1817         const GroupRWX = GROUP_RWX.bits,
1818         #[allow(non_upper_case_globals)]
1819         #[deprecated = "use OTHER_RWX instead"]
1820         const OtherRWX = OTHER_RWX.bits,
1821
1822         #[doc = "Deprecated: use `USER_FILE` instead."]
1823         #[allow(non_upper_case_globals)]
1824         #[deprecated = "use USER_FILE instead"]
1825         const UserFile = USER_FILE.bits,
1826
1827         #[doc = "Deprecated: use `USER_DIR` instead."]
1828         #[allow(non_upper_case_globals)]
1829         #[deprecated = "use USER_DIR instead"]
1830         const UserDir  = USER_DIR.bits,
1831         #[doc = "Deprecated: use `USER_EXEC` instead."]
1832         #[allow(non_upper_case_globals)]
1833         #[deprecated = "use USER_EXEC instead"]
1834         const UserExec = USER_EXEC.bits,
1835
1836         #[doc = "Deprecated: use `ALL_PERMISSIONS` instead"]
1837         #[allow(non_upper_case_globals)]
1838         #[deprecated = "use ALL_PERMISSIONS instead"]
1839         const AllPermissions = ALL_PERMISSIONS.bits,
1840     }
1841 }
1842
1843 impl Default for FilePermission {
1844     #[inline]
1845     fn default() -> FilePermission { FilePermission::empty() }
1846 }
1847
1848 impl fmt::Show for FilePermission {
1849     fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1850         formatter.fill = '0';
1851         formatter.width = Some(4);
1852         (&self.bits as &fmt::Octal).fmt(formatter)
1853     }
1854 }
1855
1856 #[cfg(test)]
1857 mod tests {
1858     use super::{IoResult, Reader, MemReader, NoProgress, InvalidInput};
1859     use prelude::*;
1860     use uint;
1861
1862     #[deriving(Clone, PartialEq, Show)]
1863     enum BadReaderBehavior {
1864         GoodBehavior(uint),
1865         BadBehavior(uint)
1866     }
1867
1868     struct BadReader<T> {
1869         r: T,
1870         behavior: Vec<BadReaderBehavior>,
1871     }
1872
1873     impl<T: Reader> BadReader<T> {
1874         fn new(r: T, behavior: Vec<BadReaderBehavior>) -> BadReader<T> {
1875             BadReader { behavior: behavior, r: r }
1876         }
1877     }
1878
1879     impl<T: Reader> Reader for BadReader<T> {
1880         fn read(&mut self, buf: &mut [u8]) -> IoResult<uint> {
1881             let BadReader { ref mut behavior, ref mut r } = *self;
1882             loop {
1883                 if behavior.is_empty() {
1884                     // fall back on good
1885                     return r.read(buf);
1886                 }
1887                 match behavior.as_mut_slice()[0] {
1888                     GoodBehavior(0) => (),
1889                     GoodBehavior(ref mut x) => {
1890                         *x -= 1;
1891                         return r.read(buf);
1892                     }
1893                     BadBehavior(0) => (),
1894                     BadBehavior(ref mut x) => {
1895                         *x -= 1;
1896                         return Ok(0);
1897                     }
1898                 };
1899                 behavior.remove(0);
1900             }
1901         }
1902     }
1903
1904     #[test]
1905     fn test_read_at_least() {
1906         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1907                                    vec![GoodBehavior(uint::MAX)]);
1908         let mut buf = [0u8, ..5];
1909         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1910         assert!(r.read_exact(5).unwrap().len() == 5); // read_exact uses read_at_least
1911         assert!(r.read_at_least(0, buf).is_ok());
1912
1913         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1914                                    vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
1915         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1916
1917         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1918                                    vec![BadBehavior(1), GoodBehavior(1),
1919                                         BadBehavior(50), GoodBehavior(uint::MAX)]);
1920         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1921         assert!(r.read_at_least(1, buf).unwrap() >= 1);
1922
1923         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1924                                    vec![BadBehavior(uint::MAX)]);
1925         assert_eq!(r.read_at_least(1, buf).unwrap_err().kind, NoProgress);
1926
1927         let mut r = MemReader::new(b"hello, world!".to_vec());
1928         assert_eq!(r.read_at_least(5, buf).unwrap(), 5);
1929         assert_eq!(r.read_at_least(6, buf).unwrap_err().kind, InvalidInput);
1930     }
1931
1932     #[test]
1933     fn test_push_at_least() {
1934         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1935                                    vec![GoodBehavior(uint::MAX)]);
1936         let mut buf = Vec::new();
1937         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1938         assert!(r.push_at_least(0, 5, &mut buf).is_ok());
1939
1940         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1941                                    vec![BadBehavior(50), GoodBehavior(uint::MAX)]);
1942         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1943
1944         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1945                                    vec![BadBehavior(1), GoodBehavior(1),
1946                                         BadBehavior(50), GoodBehavior(uint::MAX)]);
1947         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1948         assert!(r.push_at_least(1, 5, &mut buf).unwrap() >= 1);
1949
1950         let mut r = BadReader::new(MemReader::new(b"hello, world!".to_vec()),
1951                                    vec![BadBehavior(uint::MAX)]);
1952         assert_eq!(r.push_at_least(1, 5, &mut buf).unwrap_err().kind, NoProgress);
1953
1954         let mut r = MemReader::new(b"hello, world!".to_vec());
1955         assert_eq!(r.push_at_least(5, 1, &mut buf).unwrap_err().kind, InvalidInput);
1956     }
1957
1958     #[test]
1959     fn test_show() {
1960         use super::*;
1961
1962         assert_eq!(format!("{}", USER_READ), "0400".to_string());
1963         assert_eq!(format!("{}", USER_FILE), "0644".to_string());
1964         assert_eq!(format!("{}", USER_EXEC), "0755".to_string());
1965         assert_eq!(format!("{}", USER_RWX),  "0700".to_string());
1966         assert_eq!(format!("{}", GROUP_RWX), "0070".to_string());
1967         assert_eq!(format!("{}", OTHER_RWX), "0007".to_string());
1968         assert_eq!(format!("{}", ALL_PERMISSIONS), "0777".to_string());
1969         assert_eq!(format!("{}", USER_READ | USER_WRITE | OTHER_WRITE), "0602".to_string());
1970     }
1971 }