(index<- ) ./libextra/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 std::io::{Reader, BytesReader};
12 use std::io;
13 use std::cast;
14
15 /// An implementation of the io::Reader interface which reads a buffer of bytes
16 pub struct BufReader {
17 /// The buffer of bytes to read
18 buf: ~[u8],
19 /// The current position in the buffer of bytes
20 pos: @mut uint
21 }
22
23 impl BufReader {
24 /// Creates a new buffer reader for the specified buffer
25 pub fn new(v: ~[u8]) -> BufReader {
26 BufReader {
27 buf: v,
28 pos: @mut 0
29 }
30 }
31
32 fn as_bytes_reader<A>(&self, f: &fn(&BytesReader) -> A) -> A {
33 // FIXME(#5723)
34 let bytes = ::std::util::id::<&[u8]>(self.buf);
35 let bytes: &'static [u8] = unsafe { cast::transmute(bytes) };
36 // Recreating the BytesReader state every call since
37 // I can't get the borrowing to work correctly
38 let bytes_reader = BytesReader {
39 bytes: bytes,
40 pos: @mut *self.pos
41 };
42
43 let res = f(&bytes_reader);
44
45 // FIXME #4429: This isn't correct if f fails
46 *self.pos = *bytes_reader.pos;
47
48 return res;
49 }
50 }
51
52 impl Reader for BufReader {
53 fn read(&self, bytes: &mut [u8], len: uint) -> uint {
54 self.as_bytes_reader(|r| r.read(bytes, len) )
55 }
56 fn read_byte(&self) -> int {
57 self.as_bytes_reader(|r| r.read_byte() )
58 }
59 fn eof(&self) -> bool {
60 self.as_bytes_reader(|r| r.eof() )
61 }
62 fn seek(&self, offset: int, whence: io::SeekStyle) {
63 self.as_bytes_reader(|r| r.seek(offset, whence) )
64 }
65 fn tell(&self) -> uint {
66 self.as_bytes_reader(|r| r.tell() )
67 }
68 }