rust/src/libcore/pipes.rs

1250 lines
34 KiB
Rust
Raw Normal View History

2012-08-01 13:56:46 -05:00
/*! Runtime support for message passing with protocol enforcement.
Pipes consist of two endpoints. One endpoint can send messages and
the other can receive messages. The set of legal messages and which
directions they can flow at any given point are determined by a
protocol. Below is an example protocol.
~~~
proto! pingpong (
2012-08-01 13:56:46 -05:00
ping: send {
ping -> pong
}
pong: recv {
pong -> ping
}
)
2012-08-01 13:56:46 -05:00
~~~
The `proto!` syntax extension will convert this into a module called
`pingpong`, which includes a set of types and functions that can be
used to write programs that follow the pingpong protocol.
*/
/* IMPLEMENTATION NOTES
The initial design for this feature is available at:
https://github.com/eholk/rust/wiki/Proposal-for-channel-contracts
Much of the design in that document is still accurate. There are
several components for the pipe implementation. First of all is the
syntax extension. To see how that works, it is best see comments in
libsyntax/ext/pipes.rs.
This module includes two related pieces of the runtime
implementation: support for unbounded and bounded
2012-08-01 13:56:46 -05:00
protocols. The main difference between the two is the type of the
buffer that is carried along in the endpoint data structures.
The heart of the implementation is the packet type. It contains a
header and a payload field. Much of the code in this module deals with
the header field. This is where the synchronization information is
stored. In the case of a bounded protocol, the header also includes a
pointer to the buffer the packet is contained in.
Packets represent a single message in a protocol. The payload field
gets instatiated at the type of the message, which is usually an enum
generated by the pipe compiler. Packets are conceptually single use,
although in bounded protocols they are reused each time around the
loop.
Packets are usually handled through a send_packet_buffered or
recv_packet_buffered object. Each packet is referenced by one
send_packet and one recv_packet, and these wrappers enforce that only
one end can send and only one end can receive. The structs also
include a destructor that marks packets are terminated if the sender
or receiver destroys the object before sending or receiving a value.
The *_packet_buffered structs take two type parameters. The first is
the message type for the current packet (or state). The second
represents the type of the whole buffer. For bounded protocols, the
protocol compiler generates a struct with a field for each protocol
state. This generated struct is used as the buffer type parameter. For
unbounded protocols, the buffer is simply one packet, so there is a
shorthand struct called send_packet and recv_packet, where the buffer
type is just `packet<T>`. Using the same underlying structure for both
bounded and unbounded protocols allows for less code duplication.
2012-08-01 13:56:46 -05:00
*/
2012-08-14 18:39:57 -05:00
// NB: transitionary, de-mode-ing.
#[forbid(deprecated_mode)];
#[forbid(deprecated_pattern)];
2012-09-04 13:12:17 -05:00
use cmp::Eq;
2012-09-18 19:34:08 -05:00
use cast::{forget, reinterpret_cast, transmute};
2012-09-04 13:12:17 -05:00
use either::{Either, Left, Right};
use option::unwrap;
// Things used by code generated by the pipe compiler.
export entangle, get_buffer, drop_buffer;
2012-08-28 13:11:15 -05:00
export SendPacketBuffered, RecvPacketBuffered;
export Packet, packet, mk_packet, entangle_buffer, HasBuffer, BufferHeader;
// export these so we can find them in the buffer_resource
2012-08-01 13:56:46 -05:00
// destructor. This is probably a symptom of #3005.
export atomic_add_acq, atomic_sub_rel;
// User-level things
2012-08-28 13:11:15 -05:00
export SendPacket, RecvPacket, send, recv, try_recv, peek;
export select, select2, selecti, select2i, selectable;
export spawn_service, spawn_service_recv;
2012-08-28 13:11:15 -05:00
export stream, Port, Chan, SharedChan, PortSet, Channel;
export oneshot, ChanOne, PortOne;
export recv_one, try_recv_one, send_one, try_send_one;
// Functions used by the protocol compiler
export rt;
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
const SPIN_COUNT: uint = 0;
2012-08-22 19:24:52 -05:00
macro_rules! move_it (
{ $x:expr } => { unsafe { let y <- *ptr::addr_of($x); move y } }
2012-08-22 19:24:52 -05:00
)
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-28 13:11:15 -05:00
enum State {
Empty,
Full,
Blocked,
Terminated
}
2012-08-27 18:26:35 -05:00
impl State: Eq {
pure fn eq(&&other: State) -> bool {
(self as uint) == (other as uint)
}
pure fn ne(&&other: State) -> bool { !self.eq(other) }
2012-08-27 18:26:35 -05:00
}
2012-08-28 13:11:15 -05:00
struct BufferHeader {
// Tracks whether this buffer needs to be freed. We can probably
// get away with restricting it to 0 or 1, if we're careful.
2012-09-06 21:40:15 -05:00
mut ref_count: int,
// We may want a drop, and to be careful about stringing this
// thing along.
}
2012-09-04 17:23:28 -05:00
fn BufferHeader() -> BufferHeader{
BufferHeader {
ref_count: 0
}
}
// This is for protocols to associate extra data to thread around.
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
type Buffer<T: Send> = {
2012-08-28 13:11:15 -05:00
header: BufferHeader,
data: T,
};
2012-08-28 13:11:15 -05:00
struct PacketHeader {
2012-09-06 21:40:15 -05:00
mut state: State,
mut blocked_task: *rust_task,
// This is a reinterpret_cast of a ~buffer, that can also be cast
// to a buffer_header if need be.
2012-09-06 21:40:15 -05:00
mut buffer: *libc::c_void,
}
fn PacketHeader() -> PacketHeader {
PacketHeader {
state: Empty,
blocked_task: ptr::null(),
buffer: ptr::null()
}
}
impl PacketHeader {
// Returns the old state.
2012-08-28 13:11:15 -05:00
unsafe fn mark_blocked(this: *rust_task) -> State {
rustrt::rust_task_ref(this);
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut self.blocked_task, this);
assert old_task.is_null();
2012-08-28 13:11:15 -05:00
swap_state_acq(&mut self.state, Blocked)
}
unsafe fn unblock() {
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut self.blocked_task, ptr::null());
if !old_task.is_null() { rustrt::rust_task_deref(old_task) }
2012-08-28 13:11:15 -05:00
match swap_state_acq(&mut self.state, Empty) {
Empty | Blocked => (),
Terminated => self.state = Terminated,
Full => self.state = Full
}
}
// unsafe because this can do weird things to the space/time
// continuum. It ends making multiple unique pointers to the same
// thing. You'll proobably want to forget them when you're done.
2012-08-28 13:11:15 -05:00
unsafe fn buf_header() -> ~BufferHeader {
assert self.buffer.is_not_null();
2012-08-29 18:00:36 -05:00
reinterpret_cast(&self.buffer)
}
fn set_buffer<T: Send>(b: ~Buffer<T>) unsafe {
2012-08-29 18:00:36 -05:00
self.buffer = reinterpret_cast(&b);
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
type Packet<T: Send> = {
2012-08-28 13:11:15 -05:00
header: PacketHeader,
2012-08-20 14:23:37 -05:00
mut payload: Option<T>,
};
2012-08-28 13:11:15 -05:00
#[doc(hidden)]
trait HasBuffer {
// XXX This should not have a trailing underscore
fn set_buffer_(b: *libc::c_void);
}
impl<T: Send> Packet<T>: HasBuffer {
2012-08-28 13:11:15 -05:00
fn set_buffer_(b: *libc::c_void) {
self.header.buffer = b;
}
}
#[doc(hidden)]
fn mk_packet<T: Send>() -> Packet<T> {
{
2012-08-28 13:11:15 -05:00
header: PacketHeader(),
2012-08-20 14:23:37 -05:00
mut payload: None
}
}
#[doc(hidden)]
fn unibuffer<T: Send>() -> ~Buffer<Packet<T>> {
let b = ~{
2012-08-28 13:11:15 -05:00
header: BufferHeader(),
data: {
2012-08-28 13:11:15 -05:00
header: PacketHeader(),
2012-08-20 14:23:37 -05:00
mut payload: None,
}
};
unsafe {
2012-08-29 18:00:36 -05:00
b.data.header.buffer = reinterpret_cast(&b);
}
move b
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn packet<T: Send>() -> *Packet<T> {
let b = unibuffer();
let p = ptr::addr_of(b.data);
// We'll take over memory management from here.
2012-09-11 19:17:54 -05:00
unsafe { forget(move b) }
p
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn entangle_buffer<T: Send, Tstart: Send>(
2012-08-28 13:11:15 -05:00
+buffer: ~Buffer<T>,
init: fn(*libc::c_void, x: &T) -> *Packet<Tstart>)
-> (SendPacketBuffered<Tstart, T>, RecvPacketBuffered<Tstart, T>)
{
2012-08-29 18:00:36 -05:00
let p = init(unsafe { reinterpret_cast(&buffer) }, &buffer.data);
2012-09-11 19:17:54 -05:00
unsafe { forget(move buffer) }
2012-08-28 13:11:15 -05:00
(SendPacketBuffered(p), RecvPacketBuffered(p))
}
#[abi = "rust-intrinsic"]
#[doc(hidden)]
extern mod rusti {
2012-08-21 14:18:50 -05:00
fn atomic_xchg(dst: &mut int, src: int) -> int;
fn atomic_xchg_acq(dst: &mut int, src: int) -> int;
fn atomic_xchg_rel(dst: &mut int, src: int) -> int;
2012-08-21 14:18:50 -05:00
fn atomic_xadd_acq(dst: &mut int, src: int) -> int;
fn atomic_xsub_rel(dst: &mut int, src: int) -> int;
}
// If I call the rusti versions directly from a polymorphic function,
// I get link errors. This is a bug that needs investigated more.
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-14 18:39:57 -05:00
fn atomic_xchng_rel(dst: &mut int, src: int) -> int {
2012-08-21 14:18:50 -05:00
rusti::atomic_xchg_rel(dst, src)
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-14 18:39:57 -05:00
fn atomic_add_acq(dst: &mut int, src: int) -> int {
2012-08-21 14:18:50 -05:00
rusti::atomic_xadd_acq(dst, src)
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-14 18:39:57 -05:00
fn atomic_sub_rel(dst: &mut int, src: int) -> int {
2012-08-21 14:18:50 -05:00
rusti::atomic_xsub_rel(dst, src)
}
#[doc(hidden)]
2012-08-21 14:18:50 -05:00
fn swap_task(+dst: &mut *rust_task, src: *rust_task) -> *rust_task {
// It might be worth making both acquire and release versions of
// this.
unsafe {
2012-09-11 19:17:54 -05:00
transmute(rusti::atomic_xchg(transmute(move dst), src as int))
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-28 13:11:15 -05:00
#[allow(non_camel_case_types)]
2012-07-02 19:42:58 -05:00
type rust_task = libc::c_void;
#[doc(hidden)]
extern mod rustrt {
2012-07-02 19:42:58 -05:00
#[rust_stack]
fn rust_get_task() -> *rust_task;
#[rust_stack]
fn rust_task_ref(task: *rust_task);
fn rust_task_deref(task: *rust_task);
2012-07-02 19:42:58 -05:00
#[rust_stack]
fn task_clear_event_reject(task: *rust_task);
fn task_wait_event(this: *rust_task, killed: &mut *libc::c_void) -> bool;
pure fn task_signal_event(target: *rust_task, event: *libc::c_void);
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn wait_event(this: *rust_task) -> *libc::c_void {
let mut event = ptr::null();
let killed = rustrt::task_wait_event(this, &mut event);
if killed && !task::failing() {
fail ~"killed"
}
event
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-28 13:11:15 -05:00
fn swap_state_acq(+dst: &mut State, src: State) -> State {
unsafe {
2012-09-11 19:17:54 -05:00
transmute(rusti::atomic_xchg_acq(transmute(move dst), src as int))
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
2012-08-28 13:11:15 -05:00
fn swap_state_rel(+dst: &mut State, src: State) -> State {
unsafe {
2012-09-11 19:17:54 -05:00
transmute(rusti::atomic_xchg_rel(transmute(move dst), src as int))
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
unsafe fn get_buffer<T: Send>(p: *PacketHeader) -> ~Buffer<T> {
transmute((*p).buf_header())
}
// This could probably be done with SharedMutableState to avoid move_it!().
struct BufferResource<T: Send> {
2012-09-06 21:40:15 -05:00
buffer: ~Buffer<T>,
drop unsafe {
2012-08-22 19:24:52 -05:00
let b = move_it!(self.buffer);
//let p = ptr::addr_of(*b);
2012-08-22 19:24:52 -05:00
//error!("drop %?", p);
2012-08-14 18:39:57 -05:00
let old_count = atomic_sub_rel(&mut b.header.ref_count, 1);
//let old_count = atomic_xchng_rel(b.header.ref_count, 0);
if old_count == 1 {
// The new count is 0.
// go go gadget drop glue
}
else {
2012-09-11 19:17:54 -05:00
forget(move b)
}
}
}
fn BufferResource<T: Send>(+b: ~Buffer<T>) -> BufferResource<T> {
2012-09-04 17:23:28 -05:00
//let p = ptr::addr_of(*b);
//error!("take %?", p);
atomic_add_acq(&mut b.header.ref_count, 1);
BufferResource {
buffer: b
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn send<T: Send, Tbuffer: Send>(+p: SendPacketBuffered<T, Tbuffer>,
2012-08-14 18:39:57 -05:00
+payload: T) -> bool {
let header = p.header();
2012-07-02 19:42:58 -05:00
let p_ = p.unwrap();
let p = unsafe { &*p_ };
assert ptr::addr_of(p.header) == header;
2012-08-27 19:43:15 -05:00
assert p.payload.is_none();
p.payload <- Some(move payload);
2012-08-28 13:11:15 -05:00
let old_state = swap_state_rel(&mut p.header.state, Full);
2012-08-06 14:34:08 -05:00
match old_state {
2012-08-28 13:11:15 -05:00
Empty => {
// Yay, fastpath.
// The receiver will eventually clean this up.
//unsafe { forget(p); }
return true;
}
2012-08-28 13:11:15 -05:00
Full => fail ~"duplicate send",
Blocked => {
2012-08-22 19:24:52 -05:00
debug!("waking up task for %?", p_);
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
rustrt::task_signal_event(
old_task, ptr::addr_of(p.header) as *libc::c_void);
rustrt::rust_task_deref(old_task);
}
// The receiver will eventually clean this up.
//unsafe { forget(p); }
return true;
}
2012-08-28 13:11:15 -05:00
Terminated => {
// The receiver will never receive this. Rely on drop_glue
// to clean everything up.
return false;
}
}
}
2012-08-01 13:56:46 -05:00
/** Receives a message from a pipe.
Fails if the sender closes the connection.
*/
fn recv<T: Send, Tbuffer: Send>(+p: RecvPacketBuffered<T, Tbuffer>) -> T {
option::unwrap_expect(try_recv(move p), "connection closed")
}
2012-08-01 13:56:46 -05:00
/** Attempts to receive a message from a pipe.
Returns `none` if the sender has closed the connection without sending
2012-08-20 14:23:37 -05:00
a message, or `Some(T)` if a message was received.
2012-08-01 13:56:46 -05:00
*/
fn try_recv<T: Send, Tbuffer: Send>(+p: RecvPacketBuffered<T, Tbuffer>)
2012-08-20 14:23:37 -05:00
-> Option<T>
{
2012-07-02 19:42:58 -05:00
let p_ = p.unwrap();
let p = unsafe { &*p_ };
2012-08-28 13:11:15 -05:00
struct DropState {
p: &PacketHeader,
drop {
if task::failing() {
2012-08-28 13:11:15 -05:00
self.p.state = Terminated;
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut self.p.blocked_task,
ptr::null());
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
}
}
}
};
2012-08-28 13:11:15 -05:00
let _drop_state = DropState { p: &p.header };
// optimistic path
match p.header.state {
2012-08-28 13:11:15 -05:00
Full => {
2012-08-20 14:23:37 -05:00
let mut payload = None;
payload <-> p.payload;
2012-08-28 13:11:15 -05:00
p.header.state = Empty;
2012-09-11 19:17:54 -05:00
return Some(option::unwrap(move payload))
},
2012-08-28 13:11:15 -05:00
Terminated => return None,
_ => {}
}
// regular path
2012-07-02 19:42:58 -05:00
let this = rustrt::rust_get_task();
rustrt::task_clear_event_reject(this);
rustrt::rust_task_ref(this);
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, this);
assert old_task.is_null();
let mut first = true;
let mut count = SPIN_COUNT;
loop {
rustrt::task_clear_event_reject(this);
2012-08-14 18:39:57 -05:00
let old_state = swap_state_acq(&mut p.header.state,
2012-08-28 13:11:15 -05:00
Blocked);
2012-08-06 14:34:08 -05:00
match old_state {
2012-08-28 13:11:15 -05:00
Empty => {
2012-08-22 19:24:52 -05:00
debug!("no data available on %?, going to sleep.", p_);
if count == 0 {
wait_event(this);
}
else {
count -= 1;
// FIXME (#524): Putting the yield here destroys a lot
// of the benefit of spinning, since we still go into
// the scheduler at every iteration. However, without
// this everything spins too much because we end up
// sometimes blocking the thing we are waiting on.
task::yield();
}
2012-08-22 19:24:52 -05:00
debug!("woke up, p.state = %?", copy p.header.state);
}
2012-08-28 13:11:15 -05:00
Blocked => if first {
2012-08-03 21:59:04 -05:00
fail ~"blocking on already blocked packet"
},
2012-08-28 13:11:15 -05:00
Full => {
2012-08-20 14:23:37 -05:00
let mut payload = None;
payload <-> p.payload;
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
}
2012-08-28 13:11:15 -05:00
p.header.state = Empty;
2012-09-11 19:17:54 -05:00
return Some(option::unwrap(move payload))
}
2012-08-28 13:11:15 -05:00
Terminated => {
2012-08-03 13:43:10 -05:00
// This assert detects when we've accidentally unsafely
// casted too big of a number to a state.
2012-08-28 13:11:15 -05:00
assert old_state == Terminated;
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
}
2012-08-20 14:23:37 -05:00
return None;
}
}
first = false;
}
}
2012-07-09 17:29:23 -05:00
/// Returns true if messages are available.
pure fn peek<T: Send, Tb: Send>(p: &RecvPacketBuffered<T, Tb>) -> bool {
2012-08-06 14:34:08 -05:00
match unsafe {(*p.header()).state} {
2012-08-28 13:11:15 -05:00
Empty => false,
Blocked => fail ~"peeking on blocked packet",
Full | Terminated => true
2012-07-09 17:29:23 -05:00
}
}
impl<T: Send, Tb: Send> RecvPacketBuffered<T, Tb> {
2012-07-26 19:10:21 -05:00
pure fn peek() -> bool {
2012-08-14 18:39:57 -05:00
peek(&self)
2012-07-26 19:10:21 -05:00
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn sender_terminate<T: Send>(p: *Packet<T>) {
let p = unsafe { &*p };
2012-08-28 13:11:15 -05:00
match swap_state_rel(&mut p.header.state, Terminated) {
Empty => {
// The receiver will eventually clean up.
}
2012-08-28 13:11:15 -05:00
Blocked => {
// wake up the target
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
2012-08-03 13:43:10 -05:00
rustrt::task_signal_event(
old_task,
ptr::addr_of(p.header) as *libc::c_void);
rustrt::rust_task_deref(old_task);
2012-08-03 13:43:10 -05:00
}
// The receiver will eventually clean up.
}
2012-08-28 13:11:15 -05:00
Full => {
// This is impossible
fail ~"you dun goofed"
}
2012-08-28 13:11:15 -05:00
Terminated => {
assert p.header.blocked_task.is_null();
// I have to clean up, use drop_glue
}
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn receiver_terminate<T: Send>(p: *Packet<T>) {
let p = unsafe { &*p };
2012-08-28 13:11:15 -05:00
match swap_state_rel(&mut p.header.state, Terminated) {
Empty => {
assert p.header.blocked_task.is_null();
// the sender will clean up
}
2012-08-28 13:11:15 -05:00
Blocked => {
2012-08-14 18:39:57 -05:00
let old_task = swap_task(&mut p.header.blocked_task, ptr::null());
if !old_task.is_null() {
rustrt::rust_task_deref(old_task);
assert old_task == rustrt::rust_get_task();
}
}
2012-08-28 13:11:15 -05:00
Terminated | Full => {
assert p.header.blocked_task.is_null();
// I have to clean up, use drop_glue
}
}
}
2012-08-01 13:56:46 -05:00
/** Returns when one of the packet headers reports data is available.
This function is primarily intended for building higher level waiting
functions, such as `select`, `select2`, etc.
It takes a vector slice of packet_headers and returns an index into
that vector. The index points to an endpoint that has either been
closed by the sender or has a message waiting to be received.
*/
2012-08-28 13:11:15 -05:00
fn wait_many<T: Selectable>(pkts: &[T]) -> uint {
let this = rustrt::rust_get_task();
rustrt::task_clear_event_reject(this);
let mut data_avail = false;
let mut ready_packet = pkts.len();
for pkts.eachi |i, p| unsafe {
let p = unsafe { &*p.header() };
let old = p.mark_blocked(this);
2012-08-06 14:34:08 -05:00
match old {
2012-08-28 13:11:15 -05:00
Full | Terminated => {
data_avail = true;
ready_packet = i;
(*p).state = old;
break;
}
2012-08-28 13:11:15 -05:00
Blocked => fail ~"blocking on blocked packet",
Empty => ()
}
}
while !data_avail {
2012-08-22 19:24:52 -05:00
debug!("sleeping on %? packets", pkts.len());
2012-08-28 13:11:15 -05:00
let event = wait_event(this) as *PacketHeader;
let pos = vec::position(pkts, |p| p.header() == event);
2012-08-06 14:34:08 -05:00
match pos {
2012-08-20 14:23:37 -05:00
Some(i) => {
ready_packet = i;
data_avail = true;
}
2012-08-20 14:23:37 -05:00
None => debug!("ignoring spurious event, %?", event)
}
}
2012-08-22 19:24:52 -05:00
debug!("%?", pkts[ready_packet]);
for pkts.each |p| { unsafe{ (*p.header()).unblock()} }
2012-08-03 13:43:10 -05:00
debug!("%?, %?", ready_packet, pkts[ready_packet]);
unsafe {
2012-08-28 13:11:15 -05:00
assert (*pkts[ready_packet].header()).state == Full
|| (*pkts[ready_packet].header()).state == Terminated;
}
ready_packet
}
2012-08-01 13:56:46 -05:00
/** Receives a message from one of two endpoints.
The return value is `left` if the first endpoint received something,
or `right` if the second endpoint receives something. In each case,
the result includes the other endpoint as well so it can be used
again. Below is an example of using `select2`.
~~~
match select2(a, b) {
left((none, b)) {
// endpoint a was closed.
}
right((a, none)) {
// endpoint b was closed.
}
2012-08-20 14:23:37 -05:00
left((Some(_), b)) {
2012-08-01 13:56:46 -05:00
// endpoint a received a message
}
2012-08-20 14:23:37 -05:00
right(a, Some(_)) {
2012-08-01 13:56:46 -05:00
// endpoint b received a message.
}
}
~~~
Sometimes messages will be available on both endpoints at once. In
this case, `select2` may return either `left` or `right`.
*/
fn select2<A: Send, Ab: Send, B: Send, Bb: Send>(
2012-08-28 13:11:15 -05:00
+a: RecvPacketBuffered<A, Ab>,
+b: RecvPacketBuffered<B, Bb>)
-> Either<(Option<A>, RecvPacketBuffered<B, Bb>),
(RecvPacketBuffered<A, Ab>, Option<B>)>
2012-07-09 15:53:55 -05:00
{
2012-07-10 18:46:16 -05:00
let i = wait_many([a.header(), b.header()]/_);
2012-07-09 15:53:55 -05:00
match i {
0 => Left((try_recv(move a), move b)),
1 => Right((move a, try_recv(move b))),
_ => fail ~"select2 return an invalid packet"
2012-07-09 15:53:55 -05:00
}
}
#[doc(hidden)]
2012-08-28 13:11:15 -05:00
trait Selectable {
pure fn header() -> *PacketHeader;
2012-07-13 17:39:31 -05:00
}
2012-08-28 13:11:15 -05:00
impl *PacketHeader: Selectable {
pure fn header() -> *PacketHeader { self }
}
/// Returns the index of an endpoint that is ready to receive.
2012-08-28 13:11:15 -05:00
fn selecti<T: Selectable>(endpoints: &[T]) -> uint {
wait_many(endpoints)
2012-07-10 18:46:16 -05:00
}
/// Returns 0 or 1 depending on which endpoint is ready to receive
2012-08-28 13:11:15 -05:00
fn select2i<A: Selectable, B: Selectable>(a: &A, b: &B) -> Either<(), ()> {
2012-08-06 14:34:08 -05:00
match wait_many([a.header(), b.header()]/_) {
2012-08-14 18:54:13 -05:00
0 => Left(()),
1 => Right(()),
2012-08-03 21:59:04 -05:00
_ => fail ~"wait returned unexpected index"
2012-07-13 17:39:31 -05:00
}
}
/** Waits on a set of endpoints. Returns a message, its index, and a
list of the remaining endpoints.
*/
fn select<T: Send, Tb: Send>(+endpoints: ~[RecvPacketBuffered<T, Tb>])
2012-08-28 13:11:15 -05:00
-> (uint, Option<T>, ~[RecvPacketBuffered<T, Tb>])
{
2012-07-10 18:46:16 -05:00
let ready = wait_many(endpoints.map(|p| p.header()));
let mut remaining <- endpoints;
let port = vec::swap_remove(remaining, ready);
let result = try_recv(move port);
(ready, move result, move remaining)
}
/** The sending end of a pipe. It can be used to send exactly one
message.
*/
type SendPacket<T: Send> = SendPacketBuffered<T, Packet<T>>;
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn SendPacket<T: Send>(p: *Packet<T>) -> SendPacket<T> {
2012-08-28 13:11:15 -05:00
SendPacketBuffered(p)
}
struct SendPacketBuffered<T: Send, Tbuffer: Send> {
2012-09-06 21:40:15 -05:00
mut p: Option<*Packet<T>>,
mut buffer: Option<BufferResource<Tbuffer>>,
drop {
//if self.p != none {
2012-08-22 19:24:52 -05:00
// debug!("drop send %?", option::get(self.p));
//}
2012-08-20 14:23:37 -05:00
if self.p != None {
let mut p = None;
p <-> self.p;
2012-09-11 19:17:54 -05:00
sender_terminate(option::unwrap(move p))
}
2012-08-22 19:24:52 -05:00
//unsafe { error!("send_drop: %?",
// if self.buffer == none {
// "none"
2012-08-22 19:24:52 -05:00
// } else { "some" }); }
}
}
fn SendPacketBuffered<T: Send, Tbuffer: Send>(p: *Packet<T>)
-> SendPacketBuffered<T, Tbuffer> {
//debug!("take send %?", p);
SendPacketBuffered {
p: Some(p),
buffer: unsafe {
Some(BufferResource(
get_buffer(ptr::addr_of((*p).header))))
}
}
}
impl<T: Send, Tbuffer: Send> SendPacketBuffered<T, Tbuffer> {
2012-08-28 13:11:15 -05:00
fn unwrap() -> *Packet<T> {
2012-08-20 14:23:37 -05:00
let mut p = None;
p <-> self.p;
2012-09-11 19:17:54 -05:00
option::unwrap(move p)
}
2012-08-28 13:11:15 -05:00
pure fn header() -> *PacketHeader {
2012-08-06 14:34:08 -05:00
match self.p {
2012-08-20 14:23:37 -05:00
Some(packet) => unsafe {
2012-08-03 21:59:04 -05:00
let packet = &*packet;
let header = ptr::addr_of(packet.header);
//forget(packet);
header
},
2012-08-20 14:23:37 -05:00
None => fail ~"packet already consumed"
}
}
2012-08-28 13:11:15 -05:00
fn reuse_buffer() -> BufferResource<Tbuffer> {
2012-08-22 19:24:52 -05:00
//error!("send reuse_buffer");
2012-08-20 14:23:37 -05:00
let mut tmp = None;
tmp <-> self.buffer;
2012-09-11 19:17:54 -05:00
option::unwrap(move tmp)
}
}
2012-08-01 13:56:46 -05:00
/// Represents the receive end of a pipe. It can receive exactly one
/// message.
type RecvPacket<T: Send> = RecvPacketBuffered<T, Packet<T>>;
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn RecvPacket<T: Send>(p: *Packet<T>) -> RecvPacket<T> {
2012-08-28 13:11:15 -05:00
RecvPacketBuffered(p)
}
struct RecvPacketBuffered<T: Send, Tbuffer: Send> {
2012-09-06 21:40:15 -05:00
mut p: Option<*Packet<T>>,
mut buffer: Option<BufferResource<Tbuffer>>,
drop {
//if self.p != none {
2012-08-22 19:24:52 -05:00
// debug!("drop recv %?", option::get(self.p));
//}
2012-08-20 14:23:37 -05:00
if self.p != None {
let mut p = None;
p <-> self.p;
2012-09-11 19:17:54 -05:00
receiver_terminate(option::unwrap(move p))
}
2012-08-22 19:24:52 -05:00
//unsafe { error!("recv_drop: %?",
// if self.buffer == none {
// "none"
2012-08-22 19:24:52 -05:00
// } else { "some" }); }
}
}
impl<T: Send, Tbuffer: Send> RecvPacketBuffered<T, Tbuffer> : Selectable {
2012-08-28 13:11:15 -05:00
fn unwrap() -> *Packet<T> {
2012-08-20 14:23:37 -05:00
let mut p = None;
p <-> self.p;
2012-09-11 19:17:54 -05:00
option::unwrap(move p)
}
2012-07-09 17:29:23 -05:00
2012-08-28 13:11:15 -05:00
pure fn header() -> *PacketHeader {
2012-08-06 14:34:08 -05:00
match self.p {
2012-08-20 14:23:37 -05:00
Some(packet) => unsafe {
2012-08-03 21:59:04 -05:00
let packet = &*packet;
let header = ptr::addr_of(packet.header);
//forget(packet);
header
},
2012-08-20 14:23:37 -05:00
None => fail ~"packet already consumed"
2012-07-09 17:29:23 -05:00
}
}
2012-08-28 13:11:15 -05:00
fn reuse_buffer() -> BufferResource<Tbuffer> {
2012-08-22 19:24:52 -05:00
//error!("recv reuse_buffer");
2012-08-20 14:23:37 -05:00
let mut tmp = None;
tmp <-> self.buffer;
2012-09-11 19:17:54 -05:00
option::unwrap(move tmp)
}
}
fn RecvPacketBuffered<T: Send, Tbuffer: Send>(p: *Packet<T>)
2012-09-04 17:23:28 -05:00
-> RecvPacketBuffered<T, Tbuffer> {
//debug!("take recv %?", p);
RecvPacketBuffered {
p: Some(p),
buffer: unsafe {
Some(BufferResource(
get_buffer(ptr::addr_of((*p).header))))
}
}
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
fn entangle<T: Send>() -> (SendPacket<T>, RecvPacket<T>) {
let p = packet();
2012-08-28 13:11:15 -05:00
(SendPacket(p), RecvPacket(p))
}
/** Spawn a task to provide a service.
It takes an initialization function that produces a send and receive
endpoint. The send endpoint is returned to the caller and the receive
endpoint is passed to the new task.
*/
fn spawn_service<T: Send, Tb: Send>(
2012-08-28 13:11:15 -05:00
init: extern fn() -> (SendPacketBuffered<T, Tb>,
RecvPacketBuffered<T, Tb>),
+service: fn~(+RecvPacketBuffered<T, Tb>))
-> SendPacketBuffered<T, Tb>
{
let (client, server) = init();
// This is some nasty gymnastics required to safely move the pipe
// into a new task.
let server = ~mut Some(move server);
do task::spawn |move service, move server| {
2012-08-20 14:23:37 -05:00
let mut server_ = None;
server_ <-> *server;
2012-09-11 19:17:54 -05:00
service(option::unwrap(move server_))
}
move client
}
/** Like `spawn_service_recv`, but for protocols that start in the
receive state.
*/
fn spawn_service_recv<T: Send, Tb: Send>(
2012-08-28 13:11:15 -05:00
init: extern fn() -> (RecvPacketBuffered<T, Tb>,
SendPacketBuffered<T, Tb>),
+service: fn~(+SendPacketBuffered<T, Tb>))
-> RecvPacketBuffered<T, Tb>
{
let (client, server) = init();
// This is some nasty gymnastics required to safely move the pipe
// into a new task.
let server = ~mut Some(move server);
do task::spawn |move service, move server| {
2012-08-20 14:23:37 -05:00
let mut server_ = None;
server_ <-> *server;
2012-09-11 19:17:54 -05:00
service(option::unwrap(move server_))
}
move client
}
2012-07-10 13:58:43 -05:00
// Streams - Make pipes a little easier in general.
proto! streamp (
Open:send<T: Send> {
2012-08-28 13:11:15 -05:00
data(T) -> Open<T>
2012-07-10 13:58:43 -05:00
}
)
2012-07-10 13:58:43 -05:00
/// A trait for things that can send multiple messages.
trait Channel<T: Send> {
// It'd be nice to call this send, but it'd conflict with the
// built in send kind.
/// Sends a message.
fn send(+x: T);
/// Sends a message, or report if the receiver has closed the connection.
fn try_send(+x: T) -> bool;
}
/// A trait for things that can receive multiple messages.
trait Recv<T: Send> {
/// Receives a message, or fails if the connection closes.
fn recv() -> T;
/** Receives a message if one is available, or returns `none` if
the connection is closed.
*/
2012-08-20 14:23:37 -05:00
fn try_recv() -> Option<T>;
/** Returns true if a message is available or the connection is
closed.
*/
pure fn peek() -> bool;
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
type Chan_<T:Send> = { mut endp: Option<streamp::client::Open<T>> };
/// An endpoint that can send many messages.
enum Chan<T:Send> {
2012-08-28 13:11:15 -05:00
Chan_(Chan_<T>)
}
2012-08-01 13:56:46 -05:00
#[doc(hidden)]
type Port_<T:Send> = { mut endp: Option<streamp::server::Open<T>> };
/// An endpoint that can receive many messages.
enum Port<T:Send> {
2012-08-28 13:11:15 -05:00
Port_(Port_<T>)
}
2012-07-10 13:58:43 -05:00
/** Creates a `(chan, port)` pair.
These allow sending or receiving an unlimited number of messages.
*/
fn stream<T:Send>() -> (Chan<T>, Port<T>) {
2012-07-10 13:58:43 -05:00
let (c, s) = streamp::init();
(Chan_({ mut endp: Some(move c) }), Port_({ mut endp: Some(move s) }))
2012-07-10 13:58:43 -05:00
}
impl<T: Send> Chan<T>: Channel<T> {
2012-07-10 13:58:43 -05:00
fn send(+x: T) {
2012-08-20 14:23:37 -05:00
let mut endp = None;
2012-07-10 13:58:43 -05:00
endp <-> self.endp;
2012-08-20 14:23:37 -05:00
self.endp = Some(
2012-09-11 19:17:54 -05:00
streamp::client::data(unwrap(move endp), move x))
2012-07-10 13:58:43 -05:00
}
fn try_send(+x: T) -> bool {
2012-08-20 14:23:37 -05:00
let mut endp = None;
endp <-> self.endp;
2012-09-11 19:17:54 -05:00
match move streamp::client::try_data(unwrap(move endp), move x) {
2012-08-20 14:23:37 -05:00
Some(move next) => {
self.endp = Some(move next);
true
}
2012-08-20 14:23:37 -05:00
None => false
}
}
2012-07-10 13:58:43 -05:00
}
impl<T: Send> Port<T>: Recv<T> {
2012-07-10 13:58:43 -05:00
fn recv() -> T {
2012-08-20 14:23:37 -05:00
let mut endp = None;
2012-07-10 13:58:43 -05:00
endp <-> self.endp;
2012-09-11 19:17:54 -05:00
let streamp::data(x, endp) = pipes::recv(unwrap(move endp));
self.endp = Some(move endp);
move x
2012-07-10 13:58:43 -05:00
}
2012-08-20 14:23:37 -05:00
fn try_recv() -> Option<T> {
let mut endp = None;
2012-07-10 13:58:43 -05:00
endp <-> self.endp;
2012-09-11 19:17:54 -05:00
match move pipes::try_recv(unwrap(move endp)) {
2012-08-20 14:23:37 -05:00
Some(streamp::data(move x, move endp)) => {
self.endp = Some(move endp);
Some(move x)
2012-07-10 13:58:43 -05:00
}
2012-08-20 14:23:37 -05:00
None => None
2012-07-10 13:58:43 -05:00
}
}
pure fn peek() -> bool unsafe {
2012-08-20 14:23:37 -05:00
let mut endp = None;
2012-07-10 13:58:43 -05:00
endp <-> self.endp;
2012-08-06 14:34:08 -05:00
let peek = match endp {
2012-08-20 14:23:37 -05:00
Some(endp) => pipes::peek(&endp),
None => fail ~"peeking empty stream"
2012-07-10 13:58:43 -05:00
};
self.endp <-> endp;
peek
}
}
impl<T: Send> Port<T>: Selectable {
pure fn header() -> *PacketHeader unsafe {
match self.endp {
Some(endp) => endp.header(),
None => fail ~"peeking empty stream"
}
}
}
/// Treat many ports as one.
struct PortSet<T: Send> {
2012-09-06 21:40:15 -05:00
mut ports: ~[pipes::Port<T>],
}
fn PortSet<T: Send>() -> PortSet<T>{
PortSet {
ports: ~[]
}
}
impl<T: Send> PortSet<T> : Recv<T> {
2012-08-28 13:11:15 -05:00
fn add(+port: pipes::Port<T>) {
vec::push(self.ports, move port)
}
2012-08-28 13:11:15 -05:00
fn chan() -> Chan<T> {
2012-07-25 16:05:06 -05:00
let (ch, po) = stream();
self.add(move po);
move ch
2012-07-25 16:05:06 -05:00
}
2012-08-20 14:23:37 -05:00
fn try_recv() -> Option<T> {
let mut result = None;
// we have to swap the ports array so we aren't borrowing
// aliasable mutable memory.
let mut ports = ~[];
ports <-> self.ports;
while result.is_none() && ports.len() > 0 {
let i = wait_many(ports);
2012-08-06 14:34:08 -05:00
match move ports[i].try_recv() {
2012-08-20 14:23:37 -05:00
Some(move m) => {
result = Some(move m);
}
2012-08-20 14:23:37 -05:00
None => {
// Remove this port.
let _ = vec::swap_remove(ports, i);
}
}
}
ports <-> self.ports;
move result
}
fn recv() -> T {
option::unwrap_expect(self.try_recv(), "port_set: endpoints closed")
}
pure fn peek() -> bool {
// It'd be nice to use self.port.each, but that version isn't
// pure.
for vec::each_ref(self.ports) |p| {
2012-08-01 19:30:05 -05:00
if p.peek() { return true }
}
false
}
}
/// A channel that can be shared between many senders.
type SharedChan<T: Send> = private::Exclusive<Chan<T>>;
impl<T: Send> SharedChan<T>: Channel<T> {
fn send(+x: T) {
let mut xx = Some(move x);
do self.with_imm |chan| {
2012-08-20 14:23:37 -05:00
let mut x = None;
x <-> xx;
2012-09-11 19:17:54 -05:00
chan.send(option::unwrap(move x))
}
}
fn try_send(+x: T) -> bool {
let mut xx = Some(move x);
do self.with_imm |chan| {
2012-08-20 14:23:37 -05:00
let mut x = None;
x <-> xx;
2012-09-11 19:17:54 -05:00
chan.try_send(option::unwrap(move x))
}
}
}
/// Converts a `chan` into a `shared_chan`.
fn SharedChan<T:Send>(+c: Chan<T>) -> SharedChan<T> {
private::exclusive(move c)
}
2012-07-25 16:46:15 -05:00
/// Receive a message from one of two endpoints.
trait Select2<T: Send, U: Send> {
/// Receive a message or return `none` if a connection closes.
2012-08-20 14:23:37 -05:00
fn try_select() -> Either<Option<T>, Option<U>>;
/// Receive a message or fail if a connection closes.
2012-08-14 18:54:13 -05:00
fn select() -> Either<T, U>;
2012-07-25 16:46:15 -05:00
}
impl<T: Send, U: Send, Left: Selectable Recv<T>, Right: Selectable Recv<U>>
2012-08-28 13:11:15 -05:00
(Left, Right): Select2<T, U> {
2012-07-25 16:46:15 -05:00
2012-08-14 18:54:13 -05:00
fn select() -> Either<T, U> {
2012-08-06 14:34:08 -05:00
match self {
2012-08-14 18:39:57 -05:00
(lp, rp) => match select2i(&lp, &rp) {
2012-08-14 18:54:13 -05:00
Left(()) => Left (lp.recv()),
Right(()) => Right(rp.recv())
2012-07-25 16:46:15 -05:00
}
}
}
2012-08-20 14:23:37 -05:00
fn try_select() -> Either<Option<T>, Option<U>> {
2012-08-06 14:34:08 -05:00
match self {
2012-08-14 18:39:57 -05:00
(lp, rp) => match select2i(&lp, &rp) {
2012-08-14 18:54:13 -05:00
Left(()) => Left (lp.try_recv()),
Right(()) => Right(rp.try_recv())
2012-07-25 16:46:15 -05:00
}
}
}
}
proto! oneshot (
Oneshot:send<T:Send> {
2012-08-09 13:54:56 -05:00
send(T) -> !
}
)
2012-08-09 13:54:56 -05:00
/// The send end of a oneshot pipe.
type ChanOne<T: Send> = oneshot::client::Oneshot<T>;
/// The receive end of a oneshot pipe.
type PortOne<T: Send> = oneshot::server::Oneshot<T>;
/// Initialiase a (send-endpoint, recv-endpoint) oneshot pipe pair.
fn oneshot<T: Send>() -> (ChanOne<T>, PortOne<T>) {
oneshot::init()
}
/**
* Receive a message from a oneshot pipe, failing if the connection was
* closed.
*/
fn recv_one<T: Send>(+port: PortOne<T>) -> T {
let oneshot::send(message) = recv(move port);
move message
2012-08-09 13:54:56 -05:00
}
/// Receive a message from a oneshot pipe unless the connection was closed.
fn try_recv_one<T: Send> (+port: PortOne<T>) -> Option<T> {
let message = try_recv(move port);
2012-08-09 13:54:56 -05:00
if message.is_none() { None }
2012-08-09 13:54:56 -05:00
else {
2012-09-11 19:17:54 -05:00
let oneshot::send(message) = option::unwrap(move message);
Some(move message)
2012-08-09 13:54:56 -05:00
}
}
/// Send a message on a oneshot pipe, failing if the connection was closed.
fn send_one<T: Send>(+chan: ChanOne<T>, +data: T) {
oneshot::client::send(move chan, move data);
}
/**
* Send a message on a oneshot pipe, or return false if the connection was
* closed.
*/
fn try_send_one<T: Send>(+chan: ChanOne<T>, +data: T)
-> bool {
oneshot::client::try_send(move chan, move data).is_some()
}
mod rt {
// These are used to hide the option constructors from the
// compiler because their names are changing
fn make_some<T>(+val: T) -> Option<T> { Some(move val) }
2012-08-20 14:23:37 -05:00
fn make_none<T>() -> Option<T> { None }
}
2012-07-25 16:46:15 -05:00
#[cfg(test)]
mod test {
#[test]
fn test_select2() {
let (c1, p1) = pipes::stream();
let (c2, p2) = pipes::stream();
2012-08-03 14:04:08 -05:00
c1.send(~"abc");
2012-07-25 16:46:15 -05:00
2012-08-06 14:34:08 -05:00
match (p1, p2).select() {
2012-08-14 18:54:13 -05:00
Right(_) => fail,
2012-08-03 21:59:04 -05:00
_ => ()
2012-07-25 16:46:15 -05:00
}
c2.send(123);
}
2012-08-09 13:54:56 -05:00
#[test]
fn test_oneshot() {
let (c, p) = oneshot::init();
oneshot::client::send(c, ());
recv_one(p)
}
2012-07-25 16:46:15 -05:00
}