[][src]Crate rev_buf_reader

This crate provides a buffered reader capable of reading chunks of bytes of a data stream in reverse order. Its implementation is an adapted copy of BufReader from the nightly std::io.

Usage

Reading chunks of bytes in reverse order:

extern crate rev_buf_reader;

use rev_buf_reader::RevBufReader;
use std::io::{self, Read};

fn main() {
    let data = [0, 1, 2, 3, 4, 5, 6, 7];
    let inner = io::Cursor::new(&data);
    let mut reader = RevBufReader::new(inner);

    let mut buffer = [0, 0, 0];
    assert_eq!(reader.read(&mut buffer).ok(), Some(3));
    assert_eq!(buffer, [5, 6, 7]);

    let mut buffer = [0, 0, 0, 0, 0];
    assert_eq!(reader.read(&mut buffer).ok(), Some(5));
    assert_eq!(buffer, [0, 1, 2, 3, 4]);
}

Reading text lines in reverse order:

extern crate rev_buf_reader;

use rev_buf_reader::RevBufReader;
use std::io::{self, BufRead};

fn main() {
    let data = "a\nb\nc";
    let inner = io::Cursor::new(&data);
    let reader = RevBufReader::new(inner);
    let mut lines = reader.lines();

    assert_eq!(lines.next().unwrap().unwrap(), "c".to_string());
    assert_eq!(lines.next().unwrap().unwrap(), "b".to_string());
    assert_eq!(lines.next().unwrap().unwrap(), "a".to_string());
    assert!(lines.next().is_none());
}

Structs

RevBufReader

RevBufReader is a struct similar to std::io::BufReader, which adds buffering to any reader. But unlike BufReader, RevBufReader reads a data stream from the end to the start. The order of the bytes, however, remains the same. For example, when using RevBufReader to read a text file, we can read the same lines as we would by using BufReader, but starting from the last line until we get to the first one.