]> git.proxmox.com Git - rustc.git/blob - src/libstd/io_util.rs
Imported Upstream version 0.6
[rustc.git] / src / libstd / io_util.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 use core::io::{Reader, BytesReader};
12 use core::io;
13
14 pub struct BufReader {
15 buf: ~[u8],
16 mut pos: uint
17 }
18
19 pub impl BufReader {
20 pub fn new(v: ~[u8]) -> BufReader {
21 BufReader {
22 buf: v,
23 pos: 0
24 }
25 }
26
27 priv fn as_bytes_reader<A>(&self, f: &fn(&BytesReader) -> A) -> A {
28 // Recreating the BytesReader state every call since
29 // I can't get the borrowing to work correctly
30 let bytes_reader = BytesReader {
31 bytes: ::core::util::id::<&[u8]>(self.buf),
32 pos: self.pos
33 };
34
35 let res = f(&bytes_reader);
36
37 // FIXME #4429: This isn't correct if f fails
38 self.pos = bytes_reader.pos;
39
40 return res;
41 }
42 }
43
44 impl Reader for BufReader {
45 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
46 self.as_bytes_reader(|r| r.read(bytes, len) )
47 }
48 fn read_byte(&self) -> int {
49 self.as_bytes_reader(|r| r.read_byte() )
50 }
51 fn eof(&self) -> bool {
52 self.as_bytes_reader(|r| r.eof() )
53 }
54 fn seek(&self, offset: int, whence: io::SeekStyle) {
55 self.as_bytes_reader(|r| r.seek(offset, whence) )
56 }
57 fn tell(&self) -> uint {
58 self.as_bytes_reader(|r| r.tell() )
59 }
60 }