blob: 6ed626202b7e20e70c07299f263eb0ba2e325f37 [file] [log] [blame]
Tim Chevalier02742922013-01-11 04:09:261// 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
11use core::io::{Reader, BytesReader};
12use core::io;
Tim Chevalier02742922013-01-11 04:09:2613
14pub struct BufReader {
15 buf: ~[u8],
Patrick Walton92d2ec42013-05-03 05:44:0316 pos: @mut uint
Tim Chevalier02742922013-01-11 04:09:2617}
18
19pub impl BufReader {
Patrick Walton4634f7e2013-03-22 02:07:5420 pub fn new(v: ~[u8]) -> BufReader {
Tim Chevalier02742922013-01-11 04:09:2621 BufReader {
Luqman Aden4cf51c22013-02-15 07:30:3022 buf: v,
Patrick Walton92d2ec42013-05-03 05:44:0323 pos: @mut 0
Tim Chevalier02742922013-01-11 04:09:2624 }
25 }
26
Ben Striegel0fed29c2013-03-08 02:11:0927 priv fn as_bytes_reader<A>(&self, f: &fn(&BytesReader) -> A) -> A {
Tim Chevalier02742922013-01-11 04:09:2628 // 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),
Patrick Walton92d2ec42013-05-03 05:44:0332 pos: *self.pos
Tim Chevalier02742922013-01-11 04:09:2633 };
34
35 let res = f(&bytes_reader);
36
37 // FIXME #4429: This isn't correct if f fails
Patrick Walton92d2ec42013-05-03 05:44:0338 *self.pos = bytes_reader.pos;
Tim Chevalier02742922013-01-11 04:09:2639
Luqman Aden4cf51c22013-02-15 07:30:3040 return res;
Tim Chevalier02742922013-01-11 04:09:2641 }
42}
43
Patrick Walton91436882013-02-14 19:47:0044impl Reader for BufReader {
Ben Striegelf08af9a2013-01-30 02:30:2245 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
Tim Chevalier02742922013-01-11 04:09:2646 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}