Defines "provider" traits and implementations for different types of I/O operations.
The purpose of this is mainly for dependency injection: by having your code depend on a generic provider, it can be tested by giving it a virtual, inspectable implementation of that provider. In production, the "real" implementation can be used.
Cargo.toml
:
[dependencies]
io-providers = "0.1"
src/main.rs
```rust extern crate io_providers;
use std::io::Write; use std::path::Path; use ioproviders::{IoProvider, LocalIoProvider, VirtualIoProvider}; use ioproviders::env::Provider as EnvProvider; use io_providers::stream::Provider as StreamProvider;
/// Gets the current working directory and prints it to stdout. fn dowork(io: &mut IoProvider) { let curdir = io.env().currentdir().unwrap(); let stdout = io.stream().output(); writeln!( stdout, "The current directory is: {}", curdir.to_str().unwrap()) .unwrap(); }
fn main() { testdoworkprintscurrent_dir();
// Use a local I/O provider here to get real interaction with the system
let mut io = LocalIoProvider::new();
do_work(&mut io);
}
fn testdoworkprintscurrentdir() { // Use a virtual I/O provider here so we can verify how it was used let mut virtualio = VirtualIoProvider::new(); virtualio.env().setcurrent_dir(Path::new("/foo/bar")).unwrap();
do_work(&mut virtual_io);
assert_eq!(
"The current directory is: /foo/bar\n",
::std::str::from_utf8(virtual_io.virtual_stream().read_output()).unwrap());
} ```
io-providers
is distributed under the MIT license.