Skip to content

Instantly share code, notes, and snippets.

@txus
Created October 6, 2015 09:01
Show Gist options
  • Save txus/304c168cc3f4ad9b1b2a to your computer and use it in GitHub Desktop.
Save txus/304c168cc3f4ad9b1b2a to your computer and use it in GitHub Desktop.
Piping two channels together in Rust
enum Xor<A, B> {
Left(A),
Right(B)
}
type PipeError<T> = Xor<RecvError, SendError<T>>;
fn pipe<T: 'static + Send, U: 'static + Send>(f: fn(T) -> U, from: Receiver<T>, to: Sender<U>) -> thread::JoinHandle<()> {
thread::spawn(move || {
loop {
from.recv()
.map(f).map_err(Xor::Left)
.and_then(|msg| to.send(msg).map_err(Xor::Right));
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment