]> git.lizzy.rs Git - rust.git/commitdiff
Added a select2 trait. Fixes #2898
authorEric Holk <eric.holk@gmail.com>
Wed, 25 Jul 2012 21:46:15 +0000 (14:46 -0700)
committerEric Holk <eric.holk@gmail.com>
Wed, 25 Jul 2012 22:15:46 +0000 (15:15 -0700)
src/libcore/pipes.rs

index a999d615e31b45d0146da275841030c1e82a14b2..4ffa040250f65a0c453fff2b6cc04e0a4b3eb983 100644 (file)
@@ -822,3 +822,52 @@ fn send(+x: T) {
 fn shared_chan<T:send>(+c: chan<T>) -> shared_chan<T> {
     arc::exclusive(c)
 }
+
+trait select2<T: send, U: send> {
+    fn try_select() -> either<option<T>, option<U>>;
+    fn select() -> either<T, U>;
+}
+
+impl<T: send, U: send, Left: selectable recv<T>, Right: selectable recv<U>>
+    of select2<T, U> for (Left, Right) {
+
+    fn select() -> either<T, U> {
+        alt self {
+          (lp, rp) {
+            alt select2i(lp, rp) {
+              left(())  { left (lp.recv()) }
+              right(()) { right(rp.recv()) }
+            }
+          }
+        }
+    }
+
+    fn try_select() -> either<option<T>, option<U>> {
+        alt self {
+          (lp, rp) {
+            alt select2i(lp, rp) {
+              left(())  { left (lp.try_recv()) }
+              right(()) { right(rp.try_recv()) }
+            }
+          }
+        }
+    }
+}
+
+#[cfg(test)]
+mod test {
+    #[test]
+    fn test_select2() {
+        let (c1, p1) = pipes::stream();
+        let (c2, p2) = pipes::stream();
+
+        c1.send("abc");
+
+        alt (p1, p2).select() {
+          right(_) { fail }
+          _ { }
+        }
+
+        c2.send(123);
+    }
+}