https://github.com/jonhoo/throttled-reader
An io::Read proxy that limits calls to read()
https://github.com/jonhoo/throttled-reader
Last synced: over 1 year ago
JSON representation
An io::Read proxy that limits calls to read()
- Host: GitHub
- URL: https://github.com/jonhoo/throttled-reader
- Owner: jonhoo
- License: apache-2.0
- Created: 2018-02-08T17:38:47.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2018-12-04T18:50:27.000Z (over 7 years ago)
- Last Synced: 2025-04-11T01:48:31.646Z (over 1 year ago)
- Language: Rust
- Size: 9.77 KB
- Stars: 7
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE-APACHE
Awesome Lists containing this project
README
# throttled-reader
[](https://crates.io/crates/throttled-reader)
[](https://docs.rs/throttled-reader/)
[](https://travis-ci.org/jonhoo/throttled-reader)
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.
## Examples
```rust
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());
```