about summary refs log tree commit diff
path: root/src/libstd/rt/rtio.rs
blob: b54231421e3969be21f725ab179998cc9b2a41e3 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use c_str::CString;
use cast;
use comm::{SharedChan, Port};
use libc::c_int;
use libc;
use ops::Drop;
use option::*;
use path::Path;
use result::*;

use ai = io::net::addrinfo;
use io::IoError;
use io::native::NATIVE_IO_FACTORY;
use io::native;
use io::net::ip::{IpAddr, SocketAddr};
use io::process::{ProcessConfig, ProcessExit};
use io::signal::Signum;
use io::{FileMode, FileAccess, FileStat, FilePermission};
use io::{SeekStyle};

pub trait Callback {
    fn call(&mut self);
}

pub trait EventLoop {
    fn run(&mut self);
    fn callback(&mut self, proc());
    fn pausable_idle_callback(&mut self, ~Callback) -> ~PausableIdleCallback;
    fn remote_callback(&mut self, ~Callback) -> ~RemoteCallback;

    /// The asynchronous I/O services. Not all event loops may provide one.
    fn io<'a>(&'a mut self) -> Option<&'a mut IoFactory>;
}

pub trait RemoteCallback {
    /// Trigger the remote callback. Note that the number of times the
    /// callback is run is not guaranteed. All that is guaranteed is
    /// that, after calling 'fire', the callback will be called at
    /// least once, but multiple callbacks may be coalesced and
    /// callbacks may be called more often requested. Destruction also
    /// triggers the callback.
    fn fire(&mut self);
}

/// Data needed to make a successful open(2) call
/// Using unix flag conventions for now, which happens to also be what's supported
/// libuv (it does translation to windows under the hood).
pub struct FileOpenConfig {
    /// Path to file to be opened
    path: Path,
    /// Flags for file access mode (as per open(2))
    flags: int,
    /// File creation mode, ignored unless O_CREAT is passed as part of flags
    priv mode: int
}

/// Description of what to do when a file handle is closed
pub enum CloseBehavior {
    /// Do not close this handle when the object is destroyed
    DontClose,
    /// Synchronously close the handle, meaning that the task will block when
    /// the handle is destroyed until it has been fully closed.
    CloseSynchronously,
    /// Asynchronously closes a handle, meaning that the task will *not* block
    /// when the handle is destroyed, but the handle will still get deallocated
    /// and cleaned up (but this will happen asynchronously on the local event
    /// loop).
    CloseAsynchronously,
}

pub struct LocalIo<'a> {
    priv factory: &'a mut IoFactory,
}

#[unsafe_destructor]
impl<'a> Drop for LocalIo<'a> {
    fn drop(&mut self) {
        // XXX(pcwalton): Do nothing here for now, but eventually we may want
        // something. For now this serves to make `LocalIo` noncopyable.
    }
}

impl<'a> LocalIo<'a> {
    /// Returns the local I/O: either the local scheduler's I/O services or
    /// the native I/O services.
    pub fn borrow() -> LocalIo {
        use rt::sched::Scheduler;
        use rt::local::Local;

        unsafe {
            // First, attempt to use the local scheduler's I/O services
            let sched: Option<*mut Scheduler> = Local::try_unsafe_borrow();
            match sched {
                Some(sched) => {
                    match (*sched).event_loop.io() {
                        Some(factory) => {
                            return LocalIo {
                                factory: factory,
                            }
                        }
                        None => {}
                    }
                }
                None => {}
            }
            // If we don't have a scheduler or the scheduler doesn't have I/O
            // services, then fall back to the native I/O services.
            let native_io: &'static mut native::IoFactory =
                &mut NATIVE_IO_FACTORY;
            LocalIo {
                factory: native_io as &mut IoFactory:'static
            }
        }
    }

    /// Returns the underlying I/O factory as a trait reference.
    #[inline]
    pub fn get<'a>(&'a mut self) -> &'a mut IoFactory {
        // XXX(pcwalton): I think this is actually sound? Could borrow check
        // allow this safely?
        unsafe {
            cast::transmute_copy(&self.factory)
        }
    }
}

pub trait IoFactory {
    // networking
    fn tcp_connect(&mut self, addr: SocketAddr) -> Result<~RtioTcpStream, IoError>;
    fn tcp_bind(&mut self, addr: SocketAddr) -> Result<~RtioTcpListener, IoError>;
    fn udp_bind(&mut self, addr: SocketAddr) -> Result<~RtioUdpSocket, IoError>;
    fn unix_bind(&mut self, path: &CString) ->
        Result<~RtioUnixListener, IoError>;
    fn unix_connect(&mut self, path: &CString) -> Result<~RtioPipe, IoError>;
    fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
                          hint: Option<ai::Hint>) -> Result<~[ai::Info], IoError>;

    // filesystem operations
    fn fs_from_raw_fd(&mut self, fd: c_int, close: CloseBehavior) -> ~RtioFileStream;
    fn fs_open(&mut self, path: &CString, fm: FileMode, fa: FileAccess)
        -> Result<~RtioFileStream, IoError>;
    fn fs_unlink(&mut self, path: &CString) -> Result<(), IoError>;
    fn fs_stat(&mut self, path: &CString) -> Result<FileStat, IoError>;
    fn fs_mkdir(&mut self, path: &CString,
                mode: FilePermission) -> Result<(), IoError>;
    fn fs_chmod(&mut self, path: &CString,
                mode: FilePermission) -> Result<(), IoError>;
    fn fs_rmdir(&mut self, path: &CString) -> Result<(), IoError>;
    fn fs_rename(&mut self, path: &CString, to: &CString) -> Result<(), IoError>;
    fn fs_readdir(&mut self, path: &CString, flags: c_int) ->
        Result<~[Path], IoError>;
    fn fs_lstat(&mut self, path: &CString) -> Result<FileStat, IoError>;
    fn fs_chown(&mut self, path: &CString, uid: int, gid: int) ->
        Result<(), IoError>;
    fn fs_readlink(&mut self, path: &CString) -> Result<Path, IoError>;
    fn fs_symlink(&mut self, src: &CString, dst: &CString) -> Result<(), IoError>;
    fn fs_link(&mut self, src: &CString, dst: &CString) -> Result<(), IoError>;
    fn fs_utime(&mut self, src: &CString, atime: u64, mtime: u64) ->
        Result<(), IoError>;

    // misc
    fn timer_init(&mut self) -> Result<~RtioTimer, IoError>;
    fn spawn(&mut self, config: ProcessConfig)
            -> Result<(~RtioProcess, ~[Option<~RtioPipe>]), IoError>;
    fn pipe_open(&mut self, fd: c_int) -> Result<~RtioPipe, IoError>;
    fn tty_open(&mut self, fd: c_int, readable: bool)
            -> Result<~RtioTTY, IoError>;
    fn signal(&mut self, signal: Signum, channel: SharedChan<Signum>)
        -> Result<~RtioSignal, IoError>;
}

pub trait RtioTcpListener : RtioSocket {
    fn listen(~self) -> Result<~RtioTcpAcceptor, IoError>;
}

pub trait RtioTcpAcceptor : RtioSocket {
    fn accept(&mut self) -> Result<~RtioTcpStream, IoError>;
    fn accept_simultaneously(&mut self) -> Result<(), IoError>;
    fn dont_accept_simultaneously(&mut self) -> Result<(), IoError>;
}

pub trait RtioTcpStream : RtioSocket {
    fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError>;
    fn write(&mut self, buf: &[u8]) -> Result<(), IoError>;
    fn peer_name(&mut self) -> Result<SocketAddr, IoError>;
    fn control_congestion(&mut self) -> Result<(), IoError>;
    fn nodelay(&mut self) -> Result<(), IoError>;
    fn keepalive(&mut self, delay_in_seconds: uint) -> Result<(), IoError>;
    fn letdie(&mut self) -> Result<(), IoError>;
}

pub trait RtioSocket {
    fn socket_name(&mut self) -> Result<SocketAddr, IoError>;
}

pub trait RtioUdpSocket : RtioSocket {
    fn recvfrom(&mut self, buf: &mut [u8]) -> Result<(uint, SocketAddr), IoError>;
    fn sendto(&mut self, buf: &[u8], dst: SocketAddr) -> Result<(), IoError>;

    fn join_multicast(&mut self, multi: IpAddr) -> Result<(), IoError>;
    fn leave_multicast(&mut self, multi: IpAddr) -> Result<(), IoError>;

    fn loop_multicast_locally(&mut self) -> Result<(), IoError>;
    fn dont_loop_multicast_locally(&mut self) -> Result<(), IoError>;

    fn multicast_time_to_live(&mut self, ttl: int) -> Result<(), IoError>;
    fn time_to_live(&mut self, ttl: int) -> Result<(), IoError>;

    fn hear_broadcasts(&mut self) -> Result<(), IoError>;
    fn ignore_broadcasts(&mut self) -> Result<(), IoError>;
}

pub trait RtioTimer {
    fn sleep(&mut self, msecs: u64);
    fn oneshot(&mut self, msecs: u64) -> Port<()>;
    fn period(&mut self, msecs: u64) -> Port<()>;
}

pub trait RtioFileStream {
    fn read(&mut self, buf: &mut [u8]) -> Result<int, IoError>;
    fn write(&mut self, buf: &[u8]) -> Result<(), IoError>;
    fn pread(&mut self, buf: &mut [u8], offset: u64) -> Result<int, IoError>;
    fn pwrite(&mut self, buf: &[u8], offset: u64) -> Result<(), IoError>;
    fn seek(&mut self, pos: i64, whence: SeekStyle) -> Result<u64, IoError>;
    fn tell(&self) -> Result<u64, IoError>;
    fn fsync(&mut self) -> Result<(), IoError>;
    fn datasync(&mut self) -> Result<(), IoError>;
    fn truncate(&mut self, offset: i64) -> Result<(), IoError>;
}

pub trait RtioProcess {
    fn id(&self) -> libc::pid_t;
    fn kill(&mut self, signal: int) -> Result<(), IoError>;
    fn wait(&mut self) -> ProcessExit;
}

pub trait RtioPipe {
    fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError>;
    fn write(&mut self, buf: &[u8]) -> Result<(), IoError>;
}

pub trait RtioUnixListener {
    fn listen(~self) -> Result<~RtioUnixAcceptor, IoError>;
}

pub trait RtioUnixAcceptor {
    fn accept(&mut self) -> Result<~RtioPipe, IoError>;
}

pub trait RtioTTY {
    fn read(&mut self, buf: &mut [u8]) -> Result<uint, IoError>;
    fn write(&mut self, buf: &[u8]) -> Result<(), IoError>;
    fn set_raw(&mut self, raw: bool) -> Result<(), IoError>;
    fn get_winsize(&mut self) -> Result<(int, int), IoError>;
    fn isatty(&self) -> bool;
}

pub trait PausableIdleCallback {
    fn pause(&mut self);
    fn resume(&mut self);
}

pub trait RtioSignal {}