├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── examples └── test.rs └── src ├── delay.rs ├── interval.rs ├── lib.rs ├── sys ├── linux.rs ├── macos.rs └── windows.rs └── timeout.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | **/*.rs.bk 3 | Cargo.lock -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: rust 2 | rust: 3 | - nightly 4 | sudo: required 5 | cache: cargo 6 | 7 | script: 8 | - cargo test 9 | 10 | os: 11 | - macos 12 | - linux 13 | 14 | matrix: 15 | include: 16 | - name: "i686-unknown-linux-gnu" 17 | script: 18 | - rustup target install i686-unknown-linux-gnu 19 | - cargo build --target i686-unknown-linux-gnu 20 | 21 | notifications: 22 | email: 23 | on_success: never 24 | 25 | addons: 26 | apt: 27 | packages: 28 | - gcc-multilib 29 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "futures-native-timers" 3 | version = "0.1.0" 4 | authors = ["tinaun "] 5 | edition = "2018" 6 | 7 | [dependencies] 8 | futures-preview = "0.3.0-alpha.13" 9 | libc = "0.2" 10 | pin-utils = "0.1.0-alpha.4" 11 | 12 | [dependencies.winapi] 13 | version = "0.3" 14 | features = ["threadpoolapiset"] 15 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 tinaun 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2019 tinaun 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # futures-native-timers 2 | 3 | Native (read: os-backed) timers for `futures` 0.3. 4 | 5 | Based on discussions from https://github.com/withoutboats/romio/issues/62. 6 | 7 | -------------------------------------------------------------------------------- /examples/test.rs: -------------------------------------------------------------------------------- 1 | #![feature(futures_api, async_await, await_macro)] 2 | 3 | use futures_native_timers::{Delay, Interval}; 4 | use std::time::Duration; 5 | 6 | use futures::executor::block_on; 7 | use futures::prelude::*; 8 | use futures::select; 9 | 10 | fn main() { 11 | let mut timeout = Delay::new(Duration::from_secs(1)); 12 | let mut stream = Interval::new(Duration::from_millis(99)); 13 | 14 | println!("{:?}", timeout); 15 | 16 | let work = async { 17 | let mut total = 0; 18 | loop { 19 | select! { 20 | _ = stream.next() => { 21 | total += 1; 22 | println!("ping."); 23 | }, 24 | _ = timeout => break, 25 | } 26 | } 27 | 28 | total 29 | }; 30 | 31 | let res = block_on(work); 32 | dbg!(res); 33 | } 34 | -------------------------------------------------------------------------------- /src/delay.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | use std::time::Duration; 3 | 4 | use futures::future::FusedFuture; 5 | use futures::prelude::*; 6 | use futures::task::{Poll, Waker}; 7 | 8 | use super::Timer; 9 | 10 | #[derive(Debug)] 11 | #[must_use = "futures do nothing unless polled"] 12 | pub struct Delay { 13 | inner: Timer, 14 | delay: Duration, 15 | done: bool, 16 | } 17 | 18 | impl Delay { 19 | pub fn new(delay: Duration) -> Self { 20 | let inner = Timer::new(); 21 | 22 | Delay { 23 | inner, 24 | delay, 25 | done: false, 26 | } 27 | } 28 | } 29 | 30 | impl Future for Delay { 31 | type Output = (); 32 | 33 | fn poll(mut self: Pin<&mut Self>, lw: &Waker) -> Poll { 34 | if !self.inner.is_active() { 35 | let delay = self.delay; 36 | self.inner.handle.init_delay(delay); 37 | } 38 | 39 | self.inner.register_waker(lw); 40 | if self.inner.is_done() { 41 | self.done = true; 42 | Poll::Ready(()) 43 | } else { 44 | Poll::Pending 45 | } 46 | } 47 | } 48 | 49 | impl FusedFuture for Delay { 50 | fn is_terminated(&self) -> bool { 51 | self.done 52 | } 53 | } 54 | 55 | impl Unpin for Delay {} 56 | -------------------------------------------------------------------------------- /src/interval.rs: -------------------------------------------------------------------------------- 1 | use std::pin::Pin; 2 | use std::time::{Duration, Instant}; 3 | 4 | use futures::prelude::*; 5 | use futures::stream::FusedStream; 6 | use futures::task::{Poll, Waker}; 7 | 8 | use super::Timer; 9 | 10 | #[derive(Debug)] 11 | pub struct Interval { 12 | inner: Timer, 13 | interval: Duration, 14 | } 15 | 16 | impl Interval { 17 | pub fn new(interval: Duration) -> Self { 18 | let inner = Timer::new(); 19 | 20 | Interval { inner, interval } 21 | } 22 | } 23 | 24 | impl Stream for Interval { 25 | type Item = Instant; 26 | 27 | fn poll_next(mut self: Pin<&mut Self>, lw: &Waker) -> Poll> { 28 | if !self.inner.is_active() { 29 | let interval = self.interval; 30 | self.inner.handle.init_interval(interval); 31 | } 32 | 33 | self.inner.register_waker(lw); 34 | if self.inner.is_done() { 35 | self.inner.state.set_done(false); 36 | Poll::Ready(Some(Instant::now())) 37 | } else { 38 | Poll::Pending 39 | } 40 | } 41 | } 42 | 43 | impl FusedStream for Interval { 44 | fn is_terminated(&self) -> bool { 45 | false 46 | } 47 | } 48 | 49 | impl Unpin for Interval {} 50 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | #![feature(futures_api, async_await, await_macro)] 2 | 3 | use std::sync::atomic::AtomicBool; 4 | use std::sync::atomic::Ordering::SeqCst; 5 | use std::sync::Arc; 6 | 7 | use futures::task::{AtomicWaker, Waker}; 8 | 9 | #[macro_export] 10 | macro_rules! dbg_println { 11 | ($($t:tt)*) => { 12 | #[cfg(test)] 13 | { 14 | println!($($t)*); 15 | } 16 | }; 17 | } 18 | 19 | mod delay; 20 | mod interval; 21 | mod timeout; 22 | 23 | #[cfg(windows)] 24 | #[path = "sys/windows.rs"] 25 | mod imp; 26 | 27 | #[cfg(target_os = "linux")] 28 | #[path = "sys/linux.rs"] 29 | mod imp; 30 | 31 | #[cfg(target_os = "macos")] 32 | #[path = "sys/macos.rs"] 33 | mod imp; 34 | 35 | use imp::NativeTimer; 36 | 37 | pub use delay::Delay; 38 | pub use interval::Interval; 39 | pub use timeout::{FutureExt, Timeout, TimeoutError}; 40 | 41 | #[derive(Debug)] 42 | pub(crate) struct TimerState { 43 | wake: AtomicWaker, 44 | done: AtomicBool, 45 | } 46 | 47 | impl TimerState { 48 | fn new() -> Self { 49 | TimerState { 50 | wake: AtomicWaker::new(), 51 | done: false.into(), 52 | } 53 | } 54 | 55 | fn register_waker(&self, lw: &Waker) { 56 | self.wake.register(lw); 57 | } 58 | 59 | fn set_done(&self, done: bool) { 60 | self.done.store(done, SeqCst); 61 | } 62 | 63 | fn done(&self) -> bool { 64 | self.done.load(SeqCst) 65 | } 66 | } 67 | 68 | #[derive(Debug)] 69 | struct Timer { 70 | handle: NativeTimer, 71 | state: Arc, 72 | } 73 | 74 | impl Timer { 75 | pub fn new() -> Self { 76 | let state = Arc::new(TimerState::new()); 77 | 78 | unsafe { 79 | let ptr = Arc::into_raw(state); 80 | let handle = NativeTimer::new(ptr as *mut _); 81 | let state = Arc::from_raw(ptr); 82 | 83 | Timer { handle, state } 84 | } 85 | } 86 | 87 | fn register_waker(&self, lw: &Waker) { 88 | self.state.register_waker(lw); 89 | } 90 | 91 | fn is_active(&self) -> bool { 92 | self.handle.is_active() 93 | } 94 | 95 | fn is_done(&self) -> bool { 96 | self.state.done() 97 | } 98 | } 99 | 100 | #[cfg(test)] 101 | mod tests { 102 | use super::*; 103 | use futures::executor::block_on; 104 | use futures::prelude::*; 105 | use std::time::{Duration, Instant}; 106 | 107 | #[test] 108 | fn join_timers() { 109 | use futures::join; 110 | 111 | let short = Delay::new(Duration::from_secs(1)); 112 | let long = Delay::new(Duration::from_secs(3)); 113 | 114 | let work = async { 115 | let t = Instant::now(); 116 | let _ = join!(short, long); 117 | t.elapsed().as_secs() 118 | }; 119 | 120 | let res = block_on(work); 121 | assert!(res < 4); 122 | } 123 | 124 | #[test] 125 | fn select_timers() { 126 | use futures::select; 127 | 128 | let mut short = Delay::new(Duration::from_secs(1)); 129 | let mut long = Delay::new(Duration::from_secs(3)); 130 | 131 | let work = async { 132 | select! { 133 | _ = short => "short finished first", 134 | _ = long => "long finished first", 135 | } 136 | }; 137 | 138 | let res = block_on(work); 139 | assert_eq!(res, "short finished first"); 140 | } 141 | 142 | #[test] 143 | fn intervals() { 144 | use futures::select; 145 | 146 | let mut timeout = Delay::new(Duration::from_secs(1)); 147 | let mut stream = Interval::new(Duration::from_millis(99)); 148 | 149 | let work = async { 150 | let mut total = 0; 151 | loop { 152 | select! { 153 | _ = stream.next() => total += 1, 154 | _ = timeout => break, 155 | } 156 | } 157 | 158 | total 159 | }; 160 | 161 | let res = block_on(work); 162 | assert_eq!(res, 10); 163 | } 164 | 165 | #[test] 166 | fn send_timers() { 167 | const NUM_TIMERS: usize = 5; 168 | 169 | use futures::channel::mpsc; 170 | use futures::executor::ThreadPool; 171 | use futures::task::SpawnExt; 172 | let mut handle = ThreadPool::new().unwrap(); 173 | 174 | async fn delay(value: usize, millis: u64) -> usize { 175 | let _ = await!(Delay::new(Duration::from_millis(millis))); 176 | 177 | value 178 | } 179 | 180 | let mut pool = handle.clone(); 181 | let work = async move { 182 | let mut res: Vec = vec![]; 183 | let (send, mut recv) = mpsc::channel(NUM_TIMERS); 184 | 185 | for i in 1..=NUM_TIMERS { 186 | let mut send = send.clone(); 187 | let task = async move { 188 | let v = await!(delay(i, (i * 10) as u64)); 189 | dbg_println!("sending? {:?}", v); 190 | let res = await!(send.send(v)); 191 | dbg_println!("result? {:?}", res); 192 | }; 193 | pool.spawn(task).unwrap(); 194 | } 195 | 196 | drop(send); 197 | while let Some(v) = await!(recv.next()) { 198 | dbg_println!("recieved {}", v); 199 | res.push(v); 200 | } 201 | 202 | res 203 | }; 204 | 205 | let res = handle.run(work); 206 | assert_eq!(res, vec![1, 2, 3, 4, 5]); 207 | } 208 | 209 | #[test] 210 | fn send_then_drop() { 211 | use futures::select; 212 | use std::thread; 213 | 214 | let mut short = thread::spawn(move || Delay::new(Duration::from_millis(400))) 215 | .join() 216 | .unwrap(); 217 | let mut long = Delay::new(Duration::from_millis(800)); 218 | 219 | let work = async { 220 | select! { 221 | _ = short => "short finished first", 222 | _ = long => "long finished first", 223 | } 224 | }; 225 | 226 | let res = block_on(work); 227 | assert_eq!(res, "short finished first"); 228 | } 229 | 230 | #[test] 231 | fn timeout() { 232 | use futures::future::empty; 233 | 234 | // The empty future will always return Poll::Pending, so this will always timeout first 235 | let result: Result<(), TimeoutError> = block_on(empty().timeout(Duration::new(0, 0))); 236 | assert!(result.is_err()); 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /src/sys/linux.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types)] 2 | 3 | use super::TimerState; 4 | use std::mem; 5 | use std::ptr; 6 | use std::sync::Once; 7 | use std::time::Duration; 8 | 9 | use libc::{ 10 | c_int, c_void, clockid_t, itimerspec, sigaction, sigevent, siginfo_t, suseconds_t, time_t, 11 | timespec, CLOCK_MONOTONIC, 12 | }; 13 | 14 | // for some reason these aren't in the libc crate yet. 15 | 16 | type timer_t = usize; 17 | 18 | extern "C" { 19 | fn timer_create(clockid: clockid_t, sevp: *mut sigevent, timerid: *mut timer_t) -> c_int; 20 | fn timer_settime( 21 | timerid: timer_t, 22 | flags: c_int, 23 | new_value: *const itimerspec, 24 | old_value: *mut itimerspec, 25 | ) -> c_int; 26 | fn timer_delete(timerid: timer_t); 27 | } 28 | 29 | // set up the signal handler 30 | // FIXME: find a free real-time signal properly 31 | static HANDLER: Once = Once::new(); 32 | const MYSIG: c_int = 40; 33 | 34 | unsafe fn init_handler() { 35 | let mut sa: sigaction = mem::zeroed(); 36 | sa.sa_flags = libc::SA_SIGINFO; 37 | sa.sa_sigaction = handler as usize; 38 | libc::sigemptyset(&mut sa.sa_mask); 39 | 40 | if sigaction(MYSIG, &sa, ptr::null_mut()) == -1 { 41 | panic!("error creating timer sigal handler!"); 42 | } 43 | } 44 | 45 | unsafe extern "C" fn handler(_sig: c_int, si: *mut siginfo_t, _uc: *mut c_void) { 46 | // evil things are afoot - tread wisely. 47 | // 48 | // the `libc` crate exposes the union part of siginfo_t as a array of i32s, 49 | // so we have to manually track the offset to get the correct field. 50 | // 51 | let raw_bytes = (*si)._pad; 52 | let val: libc::sigval = ptr::read(raw_bytes[3..].as_ptr() as *const _); 53 | 54 | let state = val.sival_ptr as *mut TimerState; 55 | dbg_println!("handled - {:p}", state); 56 | 57 | (*state).set_done(true); 58 | (*state).wake.wake(); 59 | } 60 | 61 | #[derive(Debug)] 62 | pub struct NativeTimer { 63 | inner: timer_t, 64 | active: bool, 65 | } 66 | 67 | impl NativeTimer { 68 | pub(crate) unsafe fn new(state: *mut TimerState) -> Self { 69 | HANDLER.call_once(|| init_handler()); 70 | dbg_println!("{:p}", state); 71 | 72 | let sival_ptr = state as *mut _; 73 | let mut sev: sigevent = mem::zeroed(); 74 | sev.sigev_value = libc::sigval { sival_ptr }; 75 | sev.sigev_signo = MYSIG; 76 | 77 | // yes, this means that if you create a timer on a thread that later is dropped, 78 | // timer events won't fire. changing this to SIGEV_SIGNAL leads to complete 79 | // non-deterministic behavior when running tests, since any thread could be 80 | // interupted for any signal. 81 | // 82 | // this is unfortunate, but will do for now - generally futures executors don't 83 | // tend to kill and respawn threads often. 84 | // 85 | // a solution to this might have to involve a dedicated thread for signal handling. 86 | sev.sigev_notify = libc::SIGEV_THREAD_ID; 87 | let tid = libc::syscall(libc::SYS_gettid); 88 | sev.sigev_notify_thread_id = tid as i32; 89 | 90 | let mut timer = 0; 91 | let res = timer_create(CLOCK_MONOTONIC, &mut sev, &mut timer); 92 | assert_eq!(res, 0); 93 | 94 | NativeTimer { 95 | inner: timer, 96 | active: false, 97 | } 98 | } 99 | 100 | pub fn is_active(&self) -> bool { 101 | self.active 102 | } 103 | 104 | pub fn init_delay(&mut self, delay: Duration) { 105 | let ticks = timespec { 106 | tv_sec: delay.as_secs() as time_t, 107 | tv_nsec: delay.subsec_nanos() as suseconds_t, 108 | }; 109 | 110 | self.init(ticks, None); 111 | } 112 | 113 | pub fn init_interval(&mut self, interval: Duration) { 114 | let ticks = timespec { 115 | tv_sec: interval.as_secs() as time_t, 116 | tv_nsec: interval.subsec_nanos() as suseconds_t, 117 | }; 118 | 119 | self.init(ticks, Some(ticks)); 120 | } 121 | 122 | fn init(&mut self, start: timespec, repeat: Option) { 123 | dbg_println!("created timer!"); 124 | self.active = true; 125 | 126 | let repeat = repeat.unwrap_or(timespec { 127 | tv_sec: 0, 128 | tv_nsec: 0, 129 | }); 130 | 131 | let new_value = itimerspec { 132 | it_interval: repeat, 133 | it_value: start, 134 | }; 135 | 136 | unsafe { 137 | let res = timer_settime(self.inner, 0, &new_value, ptr::null_mut()); 138 | assert_eq!(res, 0); 139 | } 140 | } 141 | } 142 | 143 | impl Drop for NativeTimer { 144 | fn drop(&mut self) { 145 | unsafe { 146 | timer_delete(self.inner); 147 | } 148 | } 149 | } 150 | -------------------------------------------------------------------------------- /src/sys/macos.rs: -------------------------------------------------------------------------------- 1 | #![allow(non_camel_case_types)] 2 | 3 | use super::TimerState; 4 | use std::time::Duration; 5 | 6 | use libc::{c_long, c_ulong, c_void, int64_t, uint64_t, uintptr_t}; 7 | 8 | type dispatch_object_t = *const c_void; 9 | type dispatch_queue_t = *const c_void; 10 | type dispatch_source_t = *const c_void; 11 | type dispatch_source_type_t = *const c_void; 12 | type dispatch_time_t = uint64_t; 13 | 14 | const DISPATCH_TIME_NOW: dispatch_time_t = 0; 15 | const QOS_CLASS_DEFAULT: c_long = 0x15; 16 | 17 | extern "C" { 18 | static _dispatch_source_type_timer: c_long; 19 | 20 | fn dispatch_get_global_queue(identifier: c_long, flags: c_ulong) -> dispatch_queue_t; 21 | fn dispatch_source_create( 22 | type_: dispatch_source_type_t, 23 | handle: uintptr_t, 24 | mask: c_ulong, 25 | queue: dispatch_queue_t, 26 | ) -> dispatch_source_t; 27 | fn dispatch_source_set_timer( 28 | source: dispatch_source_t, 29 | start: dispatch_time_t, 30 | interval: uint64_t, 31 | leeway: uint64_t, 32 | ); 33 | fn dispatch_source_set_event_handler_f( 34 | source: dispatch_source_t, 35 | handler: unsafe extern "C" fn(*mut c_void), 36 | ); 37 | fn dispatch_set_context(object: dispatch_object_t, context: *mut c_void); 38 | fn dispatch_resume(object: dispatch_object_t); 39 | fn dispatch_release(object: dispatch_object_t); 40 | fn dispatch_time(when: dispatch_time_t, delta: int64_t) -> dispatch_time_t; 41 | } 42 | 43 | #[derive(Debug)] 44 | pub struct NativeTimer { 45 | timer: dispatch_source_t, 46 | active: bool, 47 | } 48 | 49 | unsafe impl Send for NativeTimer {} 50 | 51 | impl NativeTimer { 52 | pub(crate) unsafe fn new(state: *mut TimerState) -> Self { 53 | let timer = dispatch_source_create( 54 | &_dispatch_source_type_timer as *const _ as dispatch_source_type_t, 55 | 0, // handle (not used for timers) 56 | 0, // mask (ditto) 57 | dispatch_get_global_queue(QOS_CLASS_DEFAULT, 0), 58 | ); 59 | 60 | dispatch_source_set_event_handler_f(timer, handler); 61 | dispatch_set_context(timer, state as *mut _); 62 | 63 | NativeTimer { 64 | timer, 65 | active: false, 66 | } 67 | } 68 | 69 | pub fn is_active(&self) -> bool { 70 | self.active 71 | } 72 | 73 | pub fn init_delay(&mut self, delay: Duration) { 74 | unsafe { 75 | dispatch_source_set_timer( 76 | self.timer, 77 | dispatch_time(DISPATCH_TIME_NOW, delay.as_nanos() as int64_t), 78 | 0, // interval 79 | 0, // leeway 80 | ); 81 | dispatch_resume(self.timer); 82 | } 83 | 84 | self.active = true; 85 | } 86 | 87 | pub fn init_interval(&mut self, interval: Duration) { 88 | unsafe { 89 | dispatch_source_set_timer( 90 | self.timer, 91 | dispatch_time(DISPATCH_TIME_NOW, interval.as_nanos() as int64_t), 92 | interval.as_nanos() as uint64_t, 93 | 0, // leeway 94 | ); 95 | dispatch_resume(self.timer); 96 | } 97 | 98 | self.active = true; 99 | } 100 | } 101 | 102 | impl Drop for NativeTimer { 103 | fn drop(&mut self) { 104 | unsafe { 105 | // The timer starts in a suspended state, and: "It is important to balance 106 | // calls to dispatch_suspend and dispatch_resume so that the dispatch object 107 | // is fully resumed when the last reference is released. The behavior when 108 | // releasing the last reference to a dispatch object while in a suspended 109 | // state is undefined." 110 | if !self.active { 111 | dispatch_resume(self.timer); 112 | } 113 | 114 | dispatch_release(self.timer); 115 | } 116 | } 117 | } 118 | 119 | unsafe extern "C" fn handler(context: *mut c_void) { 120 | let state = context as *mut TimerState; 121 | 122 | (*state).set_done(true); 123 | (*state).wake.wake(); 124 | } 125 | -------------------------------------------------------------------------------- /src/sys/windows.rs: -------------------------------------------------------------------------------- 1 | use super::{dbg_println, TimerState}; 2 | use std::ptr; 3 | use std::time::Duration; 4 | 5 | use winapi::shared::minwindef::{FILETIME, TRUE}; 6 | use winapi::um::winnt::{PTP_CALLBACK_INSTANCE, PTP_TIMER, PVOID}; 7 | 8 | use winapi::um::threadpoolapiset::{ 9 | CloseThreadpoolTimer, 10 | CreateThreadpoolTimer, 11 | SetThreadpoolTimerEx, 12 | WaitForThreadpoolTimerCallbacks, 13 | }; 14 | 15 | unsafe extern "system" fn timer_callback(_: PTP_CALLBACK_INSTANCE, context: PVOID, _: PTP_TIMER) { 16 | let state = context as *mut TimerState; 17 | 18 | (*state).set_done(true); 19 | (*state).wake.wake(); 20 | } 21 | 22 | #[derive(Debug)] 23 | pub struct NativeTimer { 24 | inner: PTP_TIMER, 25 | active: bool, 26 | } 27 | 28 | impl NativeTimer { 29 | pub(crate) unsafe fn new(state: *mut TimerState) -> Self { 30 | let timer = CreateThreadpoolTimer(Some(timer_callback), state as *mut _, ptr::null_mut()); 31 | 32 | NativeTimer { 33 | inner: timer, 34 | active: false, 35 | } 36 | } 37 | 38 | pub fn is_active(&self) -> bool { 39 | self.active 40 | } 41 | 42 | pub fn init_delay(&mut self, delay: Duration) { 43 | let mut ticks = (delay.subsec_nanos() / 100) as i64; 44 | ticks += (delay.as_secs() * 10_000_000) as i64; 45 | let ticks = -ticks; 46 | 47 | self.init(ticks, 0); 48 | } 49 | 50 | pub fn init_interval(&mut self, interval: Duration) { 51 | let mut ticks = (interval.subsec_nanos() / 100) as i64; 52 | ticks += (interval.as_secs() * 10_000_000) as i64; 53 | let millis = (ticks / 10_000) as u32; 54 | let ticks = -ticks; 55 | 56 | self.init(ticks, millis); 57 | } 58 | 59 | fn init(&mut self, start: i64, repeat: u32) { 60 | self.active = true; 61 | dbg_println!("timer started!"); 62 | 63 | unsafe { 64 | // i need to find a better way to do this. :/ 65 | // probably byteorder? windows apis are super weird - where else would a i64 66 | // have to be represented as two u32s 67 | let mut time: FILETIME = std::mem::transmute(start); 68 | SetThreadpoolTimerEx(self.inner, &mut time, repeat, 0); 69 | } 70 | } 71 | } 72 | 73 | impl Drop for NativeTimer { 74 | fn drop(&mut self) { 75 | unsafe { 76 | SetThreadpoolTimerEx(self.inner, ptr::null_mut(), 0, 0); 77 | WaitForThreadpoolTimerCallbacks(self.inner, TRUE); 78 | CloseThreadpoolTimer(self.inner); 79 | } 80 | 81 | dbg_println!("timer closed."); 82 | } 83 | } 84 | 85 | unsafe impl Send for NativeTimer {} 86 | unsafe impl Sync for NativeTimer {} 87 | -------------------------------------------------------------------------------- /src/timeout.rs: -------------------------------------------------------------------------------- 1 | use crate::Delay; 2 | use futures::{ 3 | prelude::*, 4 | task::{Poll, Waker}, 5 | }; 6 | use pin_utils::unsafe_pinned; 7 | use std::{error, fmt, pin::Pin, time::Duration}; 8 | 9 | pub trait FutureExt { 10 | fn timeout(self, timeout: Duration) -> Timeout 11 | where 12 | Self: Sized, 13 | { 14 | let delay = Delay::new(timeout); 15 | Timeout { 16 | future: self, 17 | delay, 18 | } 19 | } 20 | } 21 | 22 | impl FutureExt for F where F: Future {} 23 | 24 | #[derive(Debug)] 25 | #[must_use = "futures do nothing unless polled"] 26 | pub struct Timeout { 27 | future: F, 28 | delay: Delay, 29 | } 30 | 31 | impl Timeout { 32 | unsafe_pinned!(future: F); 33 | 34 | unsafe_pinned!(delay: Delay); 35 | } 36 | 37 | impl Unpin for Timeout {} 38 | 39 | impl Future for Timeout 40 | where 41 | F: Future, 42 | { 43 | type Output = Result; 44 | 45 | fn poll(mut self: Pin<&mut Self>, w: &Waker) -> Poll { 46 | // Check if timed out 47 | if let Poll::Ready(_) = self.as_mut().delay().poll(w) { 48 | Poll::Ready(Err(TimeoutError)) 49 | } else { 50 | // Poll main future 51 | self.as_mut().future().poll(w).map(Ok) 52 | } 53 | } 54 | } 55 | 56 | #[derive(Copy, Clone, Debug)] 57 | pub struct TimeoutError; 58 | impl error::Error for TimeoutError {} 59 | impl fmt::Display for TimeoutError { 60 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 61 | write!(f, "future timed out") 62 | } 63 | } 64 | --------------------------------------------------------------------------------