]> git.lizzy.rs Git - rust.git/blob - src/libnative/io/mod.rs
auto merge of #15284 : apoelstra/rust/bitv-methods, r=cmr
[rust.git] / src / libnative / io / mod.rs
1 // Copyright 2013-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 //! Native thread-blocking I/O implementation
12 //!
13 //! This module contains the implementation of native thread-blocking
14 //! implementations of I/O on all platforms. This module is not intended to be
15 //! used directly, but rather the rust runtime will fall back to using it if
16 //! necessary.
17 //!
18 //! Rust code normally runs inside of green tasks with a local scheduler using
19 //! asynchronous I/O to cooperate among tasks. This model is not always
20 //! available, however, and that's where these native implementations come into
21 //! play. The only dependencies of these modules are the normal system libraries
22 //! that you would find on the respective platform.
23
24 #![allow(non_snake_case_functions)]
25
26 use libc::c_int;
27 use libc;
28 use std::c_str::CString;
29 use std::os;
30 use std::rt::rtio;
31 use std::rt::rtio::{IoResult, IoError};
32
33 // Local re-exports
34 pub use self::file::FileDesc;
35 pub use self::process::Process;
36
37 mod helper_thread;
38
39 // Native I/O implementations
40 pub mod addrinfo;
41 pub mod net;
42 pub mod process;
43 mod util;
44
45 #[cfg(unix)]
46 #[path = "file_unix.rs"]
47 pub mod file;
48 #[cfg(windows)]
49 #[path = "file_win32.rs"]
50 pub mod file;
51
52 #[cfg(target_os = "macos")]
53 #[cfg(target_os = "ios")]
54 #[cfg(target_os = "freebsd")]
55 #[cfg(target_os = "android")]
56 #[cfg(target_os = "linux")]
57 #[path = "timer_unix.rs"]
58 pub mod timer;
59
60 #[cfg(target_os = "win32")]
61 #[path = "timer_win32.rs"]
62 pub mod timer;
63
64 #[cfg(unix)]
65 #[path = "pipe_unix.rs"]
66 pub mod pipe;
67
68 #[cfg(windows)]
69 #[path = "pipe_win32.rs"]
70 pub mod pipe;
71
72 #[cfg(windows)]
73 #[path = "tty_win32.rs"]
74 mod tty;
75
76 #[cfg(unix)]    #[path = "c_unix.rs"]  mod c;
77 #[cfg(windows)] #[path = "c_win32.rs"] mod c;
78
79 fn unimpl() -> IoError {
80     #[cfg(unix)] use ERROR = libc::ENOSYS;
81     #[cfg(windows)] use ERROR = libc::ERROR_CALL_NOT_IMPLEMENTED;
82     IoError {
83         code: ERROR as uint,
84         extra: 0,
85         detail: Some("not yet supported by the `native` runtime, maybe try `green`.".to_string()),
86     }
87 }
88
89 fn last_error() -> IoError {
90     let errno = os::errno() as uint;
91     IoError {
92         code: os::errno() as uint,
93         extra: 0,
94         detail: Some(os::error_string(errno)),
95     }
96 }
97
98 // unix has nonzero values as errors
99 fn mkerr_libc(ret: libc::c_int) -> IoResult<()> {
100     if ret != 0 {
101         Err(last_error())
102     } else {
103         Ok(())
104     }
105 }
106
107 // windows has zero values as errors
108 #[cfg(windows)]
109 fn mkerr_winbool(ret: libc::c_int) -> IoResult<()> {
110     if ret == 0 {
111         Err(last_error())
112     } else {
113         Ok(())
114     }
115 }
116
117 #[cfg(windows)]
118 #[inline]
119 fn retry(f: || -> libc::c_int) -> libc::c_int {
120     loop {
121         match f() {
122             -1 if os::errno() as int == libc::WSAEINTR as int => {}
123             n => return n,
124         }
125     }
126 }
127
128 #[cfg(unix)]
129 #[inline]
130 fn retry(f: || -> libc::c_int) -> libc::c_int {
131     loop {
132         match f() {
133             -1 if os::errno() as int == libc::EINTR as int => {}
134             n => return n,
135         }
136     }
137 }
138
139 fn keep_going(data: &[u8], f: |*const u8, uint| -> i64) -> i64 {
140     let origamt = data.len();
141     let mut data = data.as_ptr();
142     let mut amt = origamt;
143     while amt > 0 {
144         let ret = retry(|| f(data, amt) as libc::c_int);
145         if ret == 0 {
146             break
147         } else if ret != -1 {
148             amt -= ret as uint;
149             data = unsafe { data.offset(ret as int) };
150         } else {
151             return ret as i64;
152         }
153     }
154     return (origamt - amt) as i64;
155 }
156
157 /// Implementation of rt::rtio's IoFactory trait to generate handles to the
158 /// native I/O functionality.
159 pub struct IoFactory {
160     _cannot_construct_outside_of_this_module: ()
161 }
162
163 impl IoFactory {
164     pub fn new() -> IoFactory {
165         net::init();
166         IoFactory { _cannot_construct_outside_of_this_module: () }
167     }
168 }
169
170 impl rtio::IoFactory for IoFactory {
171     // networking
172     fn tcp_connect(&mut self, addr: rtio::SocketAddr,
173                    timeout: Option<u64>)
174         -> IoResult<Box<rtio::RtioTcpStream + Send>>
175     {
176         net::TcpStream::connect(addr, timeout).map(|s| {
177             box s as Box<rtio::RtioTcpStream + Send>
178         })
179     }
180     fn tcp_bind(&mut self, addr: rtio::SocketAddr)
181                 -> IoResult<Box<rtio::RtioTcpListener + Send>> {
182         net::TcpListener::bind(addr).map(|s| {
183             box s as Box<rtio::RtioTcpListener + Send>
184         })
185     }
186     fn udp_bind(&mut self, addr: rtio::SocketAddr)
187                 -> IoResult<Box<rtio::RtioUdpSocket + Send>> {
188         net::UdpSocket::bind(addr).map(|u| {
189             box u as Box<rtio::RtioUdpSocket + Send>
190         })
191     }
192     fn unix_bind(&mut self, path: &CString)
193                  -> IoResult<Box<rtio::RtioUnixListener + Send>> {
194         pipe::UnixListener::bind(path).map(|s| {
195             box s as Box<rtio::RtioUnixListener + Send>
196         })
197     }
198     fn unix_connect(&mut self, path: &CString,
199                     timeout: Option<u64>) -> IoResult<Box<rtio::RtioPipe + Send>> {
200         pipe::UnixStream::connect(path, timeout).map(|s| {
201             box s as Box<rtio::RtioPipe + Send>
202         })
203     }
204     fn get_host_addresses(&mut self, host: Option<&str>, servname: Option<&str>,
205                           hint: Option<rtio::AddrinfoHint>)
206         -> IoResult<Vec<rtio::AddrinfoInfo>>
207     {
208         addrinfo::GetAddrInfoRequest::run(host, servname, hint)
209     }
210
211     // filesystem operations
212     fn fs_from_raw_fd(&mut self, fd: c_int, close: rtio::CloseBehavior)
213                       -> Box<rtio::RtioFileStream + Send> {
214         let close = match close {
215             rtio::CloseSynchronously | rtio::CloseAsynchronously => true,
216             rtio::DontClose => false
217         };
218         box file::FileDesc::new(fd, close) as Box<rtio::RtioFileStream + Send>
219     }
220     fn fs_open(&mut self, path: &CString, fm: rtio::FileMode,
221                fa: rtio::FileAccess)
222         -> IoResult<Box<rtio::RtioFileStream + Send>>
223     {
224         file::open(path, fm, fa).map(|fd| box fd as Box<rtio::RtioFileStream + Send>)
225     }
226     fn fs_unlink(&mut self, path: &CString) -> IoResult<()> {
227         file::unlink(path)
228     }
229     fn fs_stat(&mut self, path: &CString) -> IoResult<rtio::FileStat> {
230         file::stat(path)
231     }
232     fn fs_mkdir(&mut self, path: &CString, mode: uint) -> IoResult<()> {
233         file::mkdir(path, mode)
234     }
235     fn fs_chmod(&mut self, path: &CString, mode: uint) -> IoResult<()> {
236         file::chmod(path, mode)
237     }
238     fn fs_rmdir(&mut self, path: &CString) -> IoResult<()> {
239         file::rmdir(path)
240     }
241     fn fs_rename(&mut self, path: &CString, to: &CString) -> IoResult<()> {
242         file::rename(path, to)
243     }
244     fn fs_readdir(&mut self, path: &CString, _flags: c_int) -> IoResult<Vec<CString>> {
245         file::readdir(path)
246     }
247     fn fs_lstat(&mut self, path: &CString) -> IoResult<rtio::FileStat> {
248         file::lstat(path)
249     }
250     fn fs_chown(&mut self, path: &CString, uid: int, gid: int) -> IoResult<()> {
251         file::chown(path, uid, gid)
252     }
253     fn fs_readlink(&mut self, path: &CString) -> IoResult<CString> {
254         file::readlink(path)
255     }
256     fn fs_symlink(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
257         file::symlink(src, dst)
258     }
259     fn fs_link(&mut self, src: &CString, dst: &CString) -> IoResult<()> {
260         file::link(src, dst)
261     }
262     fn fs_utime(&mut self, src: &CString, atime: u64,
263                 mtime: u64) -> IoResult<()> {
264         file::utime(src, atime, mtime)
265     }
266
267     // misc
268     fn timer_init(&mut self) -> IoResult<Box<rtio::RtioTimer + Send>> {
269         timer::Timer::new().map(|t| box t as Box<rtio::RtioTimer + Send>)
270     }
271     fn spawn(&mut self, cfg: rtio::ProcessConfig)
272             -> IoResult<(Box<rtio::RtioProcess + Send>,
273                          Vec<Option<Box<rtio::RtioPipe + Send>>>)> {
274         process::Process::spawn(cfg).map(|(p, io)| {
275             (box p as Box<rtio::RtioProcess + Send>,
276              io.move_iter().map(|p| p.map(|p| {
277                  box p as Box<rtio::RtioPipe + Send>
278              })).collect())
279         })
280     }
281     fn kill(&mut self, pid: libc::pid_t, signum: int) -> IoResult<()> {
282         process::Process::kill(pid, signum)
283     }
284     fn pipe_open(&mut self, fd: c_int) -> IoResult<Box<rtio::RtioPipe + Send>> {
285         Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioPipe + Send>)
286     }
287     #[cfg(unix)]
288     fn tty_open(&mut self, fd: c_int, _readable: bool)
289                 -> IoResult<Box<rtio::RtioTTY + Send>> {
290         if unsafe { libc::isatty(fd) } != 0 {
291             Ok(box file::FileDesc::new(fd, true) as Box<rtio::RtioTTY + Send>)
292         } else {
293             Err(IoError {
294                 code: libc::ENOTTY as uint,
295                 extra: 0,
296                 detail: None,
297             })
298         }
299     }
300     #[cfg(windows)]
301     fn tty_open(&mut self, fd: c_int, _readable: bool)
302                 -> IoResult<Box<rtio::RtioTTY + Send>> {
303         if tty::is_tty(fd) {
304             Ok(box tty::WindowsTTY::new(fd) as Box<rtio::RtioTTY + Send>)
305         } else {
306             Err(IoError {
307                 code: libc::ERROR_INVALID_HANDLE as uint,
308                 extra: 0,
309                 detail: None,
310             })
311         }
312     }
313     fn signal(&mut self, _signal: int, _cb: Box<rtio::Callback>)
314               -> IoResult<Box<rtio::RtioSignal + Send>> {
315         Err(unimpl())
316     }
317 }