File: async-reader.rs

package info (click to toggle)
rust-flate2 1.0.13-2
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 548 kB
  • sloc: makefile: 2
file content (96 lines) | stat: -rw-r--r-- 2,196 bytes parent folder | download | duplicates (19)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
extern crate flate2;
extern crate futures;
extern crate tokio_io;

use flate2::read::{GzDecoder, MultiGzDecoder};
use futures::prelude::*;
use futures::task;
use std::cmp;
use std::fs::File;
use std::io::{self, Read};
use tokio_io::io::read_to_end;
use tokio_io::AsyncRead;

struct BadReader<T> {
    reader: T,
    x: bool,
}

impl<T> BadReader<T> {
    fn new(reader: T) -> BadReader<T> {
        BadReader { reader, x: true }
    }
}

impl<T: Read> Read for BadReader<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if self.x {
            self.x = false;
            let len = cmp::min(buf.len(), 1);
            self.reader.read(&mut buf[..len])
        } else {
            self.x = true;
            Err(io::ErrorKind::WouldBlock.into())
        }
    }
}

struct AssertAsync<T>(T);

impl<T: Read> Read for AssertAsync<T> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        self.0.read(buf)
    }
}

impl<T: Read> AsyncRead for AssertAsync<T> {}

struct AlwaysNotify<T>(T);

impl<T: Future> Future for AlwaysNotify<T> {
    type Item = T::Item;
    type Error = T::Error;

    fn poll(&mut self) -> Poll<Self::Item, Self::Error> {
        let ret = self.0.poll();
        if let Ok(Async::NotReady) = &ret {
            task::current().notify();
        }
        ret
    }
}

#[test]
fn test_gz_asyncread() {
    let f = File::open("tests/good-file.gz").unwrap();

    let fut = read_to_end(AssertAsync(GzDecoder::new(BadReader::new(f))), Vec::new());
    let (_, content) = AlwaysNotify(fut).wait().unwrap();

    let mut expected = Vec::new();
    File::open("tests/good-file.txt")
        .unwrap()
        .read_to_end(&mut expected)
        .unwrap();

    assert_eq!(content, expected);
}

#[test]
fn test_multi_gz_asyncread() {
    let f = File::open("tests/multi.gz").unwrap();

    let fut = read_to_end(
        AssertAsync(MultiGzDecoder::new(BadReader::new(f))),
        Vec::new(),
    );
    let (_, content) = AlwaysNotify(fut).wait().unwrap();

    let mut expected = Vec::new();
    File::open("tests/multi.txt")
        .unwrap()
        .read_to_end(&mut expected)
        .unwrap();

    assert_eq!(content, expected);
}