Crates.io | throttled-reader |
lib.rs | throttled-reader |
version | 1.0.1 |
source | src |
created_at | 2018-02-08 17:39:50.956839 |
updated_at | 2018-12-04 18:50:28.311955 |
description | An io::Read proxy that limits calls to read() |
homepage | https://github.com/jonhoo/throttled-reader |
repository | https://github.com/jonhoo/throttled-reader.git |
max_upload_size | |
id | 50226 |
size | 20,971 |
This crate provides ThrottledReader
, a proxy-type for io::Read
that limits how many times
the underlying reader can be read from. If the read budget is exceeded,
io::ErrorKind::WouldBlock
is returned instead. This type can be useful to enforce fairness
when reading from many (potentially asynchronous) input streams with highly varying load. If
one stream always has data available, a worker may continue consuming its input forever,
neglecting the other stream.
let mut buf = [0];
let mut stream = ThrottledReader::new(io::empty());
// initially no limit
assert!(stream.read(&mut buf).is_ok());
assert!(stream.read(&mut buf).is_ok());
// set a limit
stream.set_limit(2);
assert!(stream.read(&mut buf).is_ok()); // first is allowed through
assert!(stream.read(&mut buf).is_ok()); // second is also allowed through
// but now the limit is reached, and the underlying stream is no longer accessible
assert_eq!(
stream.read(&mut buf).unwrap_err().kind(),
io::ErrorKind::WouldBlock
);
// we can then unthrottle it again after checking other streams
stream.unthrottle();
assert!(stream.read(&mut buf).is_ok());
assert!(stream.read(&mut buf).is_ok());