1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 use mpsc = std::sync::mpsc_queue;
12 use std::sync::arc::UnsafeArc;
13
14 pub enum PopResult<T> {
15 Inconsistent,
16 Empty,
17 Data(T),
18 }
19
20 pub fn queue<T: Send>() -> (Consumer<T>, Producer<T>) {
21 let (a, b) = UnsafeArc::new2(mpsc::Queue::new());
22 (Consumer { inner: a }, Producer { inner: b })
23 }
24
25 pub struct Producer<T> {
26 inner: UnsafeArc<mpsc::Queue<T>>,
27 }
28
29 pub struct Consumer<T> {
30 inner: UnsafeArc<mpsc::Queue<T>>,
31 }
32
33 impl<T: Send> Consumer<T> {
34 pub fn pop(&mut self) -> PopResult<T> {
35 match unsafe { (*self.inner.get()).pop() } {
36 mpsc::Inconsistent => Inconsistent,
37 mpsc::Empty => Empty,
38 mpsc::Data(t) => Data(t),
39 }
40 }
41
42 pub fn casual_pop(&mut self) -> Option<T> {
43 match unsafe { (*self.inner.get()).pop() } {
44 mpsc::Inconsistent => None,
45 mpsc::Empty => None,
46 mpsc::Data(t) => Some(t),
47 }
48 }
49 }
50
51 impl<T: Send> Producer<T> {
52 pub fn push(&mut self, t: T) {
53 unsafe { (*self.inner.get()).push(t); }
54 }
55 }
56
57 impl<T: Send> Clone for Producer<T> {
58 fn clone(&self) -> Producer<T> {
59 Producer { inner: self.inner.clone() }
60 }
61 }