summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorCarl Lerche <me@carllerche.com>2019-10-21 16:45:13 -0700
committerGitHub <noreply@github.com>2019-10-21 16:45:13 -0700
commitb8cee1a60ad99ef28ec494ae4230e2ef4399fcf9 (patch)
tree5bde8f840d2450397beb3403141802f558ff1147
parentc9bcbe77b9fa36868cc94cc75426823c7ec205ac (diff)
timer: move `tokio-timer` into `tokio` crate (#1674)
A step towards collapsing Tokio sub crates into a single `tokio` crate (#1318). The `timer` implementation is now provided by the main `tokio` crate. The `timer` functionality may still be excluded from the build by skipping the `timer` feature flag.
-rw-r--r--Cargo.toml1
-rw-r--r--azure-pipelines.yml2
-rw-r--r--ci/patch.toml1
-rw-r--r--tokio-test/Cargo.toml1
-rw-r--r--tokio-test/src/clock.rs12
-rw-r--r--tokio-test/src/io.rs46
-rw-r--r--tokio-test/tests/block_on.rs5
-rw-r--r--tokio-test/tests/clock.rs34
-rw-r--r--tokio-timer/CHANGELOG.md102
-rw-r--r--tokio-timer/Cargo.toml46
-rw-r--r--tokio-timer/LICENSE25
-rw-r--r--tokio-timer/README.md13
-rw-r--r--tokio-timer/src/lib.rs105
-rw-r--r--tokio-timer/tests/support/mod.rs265
-rw-r--r--tokio/Cargo.toml7
-rw-r--r--tokio/src/clock.rs7
-rw-r--r--tokio/src/future.rs2
-rw-r--r--tokio/src/runtime/current_thread/builder.rs8
-rw-r--r--tokio/src/runtime/current_thread/runtime.rs4
-rw-r--r--tokio/src/runtime/mod.rs3
-rw-r--r--tokio/src/runtime/threadpool/builder.rs8
-rw-r--r--tokio/src/runtime/threadpool/mod.rs3
-rw-r--r--tokio/src/stream.rs2
-rw-r--r--tokio/src/timer/atomic.rs (renamed from tokio-timer/src/atomic.rs)0
-rw-r--r--tokio/src/timer/clock/mod.rs (renamed from tokio-timer/src/clock/mod.rs)10
-rw-r--r--tokio/src/timer/clock/now.rs (renamed from tokio-timer/src/clock/now.rs)0
-rw-r--r--tokio/src/timer/deadline.rs (renamed from tokio-timer/src/deadline.rs)0
-rw-r--r--tokio/src/timer/delay.rs (renamed from tokio-timer/src/delay.rs)5
-rw-r--r--tokio/src/timer/delay_queue.rs (renamed from tokio-timer/src/delay_queue.rs)30
-rw-r--r--tokio/src/timer/error.rs (renamed from tokio-timer/src/error.rs)0
-rw-r--r--tokio/src/timer/interval.rs (renamed from tokio-timer/src/interval.rs)7
-rw-r--r--tokio/src/timer/mod.rs (renamed from tokio/src/timer.rs)75
-rw-r--r--tokio/src/timer/throttle.rs (renamed from tokio-timer/src/throttle.rs)3
-rw-r--r--tokio/src/timer/timeout.rs (renamed from tokio-timer/src/timeout.rs)7
-rw-r--r--tokio/src/timer/timer/atomic_stack.rs (renamed from tokio-timer/src/timer/atomic_stack.rs)3
-rw-r--r--tokio/src/timer/timer/entry.rs (renamed from tokio-timer/src/timer/entry.rs)10
-rw-r--r--tokio/src/timer/timer/handle.rs (renamed from tokio-timer/src/timer/handle.rs)7
-rw-r--r--tokio/src/timer/timer/mod.rs (renamed from tokio-timer/src/timer/mod.rs)72
-rw-r--r--tokio/src/timer/timer/now.rs (renamed from tokio-timer/src/timer/now.rs)0
-rw-r--r--tokio/src/timer/timer/registration.rs (renamed from tokio-timer/src/timer/registration.rs)6
-rw-r--r--tokio/src/timer/timer/stack.rs (renamed from tokio-timer/src/timer/stack.rs)5
-rw-r--r--tokio/src/timer/wheel/level.rs (renamed from tokio-timer/src/wheel/level.rs)3
-rw-r--r--tokio/src/timer/wheel/mod.rs (renamed from tokio-timer/src/wheel/mod.rs)4
-rw-r--r--tokio/src/timer/wheel/stack.rs (renamed from tokio-timer/src/wheel/stack.rs)0
-rw-r--r--tokio/tests/clock.rs6
-rw-r--r--tokio/tests/timer_clock.rs (renamed from tokio-timer/tests/clock.rs)5
-rw-r--r--tokio/tests/timer_delay.rs (renamed from tokio-timer/tests/delay.rs)8
-rw-r--r--tokio/tests/timer_hammer.rs (renamed from tokio-timer/tests/hammer.rs)3
-rw-r--r--tokio/tests/timer_interval.rs (renamed from tokio-timer/tests/interval.rs)2
-rw-r--r--tokio/tests/timer_queue.rs (renamed from tokio-timer/tests/queue.rs)2
-rw-r--r--tokio/tests/timer_rt.rs (renamed from tokio/tests/timer.rs)1
-rw-r--r--tokio/tests/timer_throttle.rs (renamed from tokio-timer/tests/throttle.rs)5
-rw-r--r--tokio/tests/timer_timeout.rs (renamed from tokio-timer/tests/timeout.rs)4
53 files changed, 215 insertions, 770 deletions
diff --git a/Cargo.toml b/Cargo.toml
index 7333a8d5..5883131b 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -9,7 +9,6 @@ members = [
"tokio-net",
"tokio-sync",
"tokio-test",
- "tokio-timer",
"tokio-tls",
"build-tests",
]
diff --git a/azure-pipelines.yml b/azure-pipelines.yml
index 374df5f6..b943bfe6 100644
--- a/azure-pipelines.yml
+++ b/azure-pipelines.yml
@@ -70,8 +70,6 @@ jobs:
tokio-sync:
- async-traits
tokio-macros: []
- tokio-timer:
- - async-traits
tokio-test: []
# Test compilation failure
diff --git a/ci/patch.toml b/ci/patch.toml
index 49a7252f..e6dc9148 100644
--- a/ci/patch.toml
+++ b/ci/patch.toml
@@ -8,5 +8,4 @@ tokio-io = { path = "tokio-io" }
tokio-macros = { path = "tokio-macros" }
tokio-net = { path = "tokio-net" }
tokio-sync = { path = "tokio-sync" }
-tokio-timer = { path = "tokio-timer" }
tokio-tls = { path = "tokio-tls" }
diff --git a/tokio-test/Cargo.toml b/tokio-test/Cargo.toml
index 2c5fbf4b..ce9ece11 100644
--- a/tokio-test/Cargo.toml
+++ b/tokio-test/Cargo.toml
@@ -24,7 +24,6 @@ tokio = { version = "=0.2.0-alpha.6", path = "../tokio" }
tokio-executor = { version = "=0.2.0-alpha.6", path = "../tokio-executor" }
tokio-io = { version = "=0.2.0-alpha.6", path = "../tokio-io" }
tokio-sync = { version = "=0.2.0-alpha.6", path = "../tokio-sync" }
-tokio-timer = { version = "=0.3.0-alpha.6", path = "../tokio-timer" }
futures-core-preview = "=0.3.0-alpha.19"
pin-convert = "0.1.0"
diff --git a/tokio-test/src/clock.rs b/tokio-test/src/clock.rs
index ea4f0465..dd09a009 100644
--- a/tokio-test/src/clock.rs
+++ b/tokio-test/src/clock.rs
@@ -1,11 +1,11 @@
-//! A mocked clock for use with `tokio_timer` based futures.
+//! A mocked clock for use with `tokio::timer` based futures.
//!
//! # Example
//!
//! ```
//! use tokio::clock;
+//! use tokio::timer::delay;
//! use tokio_test::{assert_ready, assert_pending, task};
-//! use tokio_timer::delay;
//!
//! use std::time::Duration;
//!
@@ -22,9 +22,9 @@
//! });
//! ```
+use tokio::timer::clock::{Clock, Now};
+use tokio::timer::Timer;
use tokio_executor::park::{Park, Unpark};
-use tokio_timer::clock::{Clock, Now};
-use tokio_timer::Timer;
use std::marker::PhantomData;
use std::rc::Rc;
@@ -125,13 +125,13 @@ impl MockClock {
where
F: FnOnce(&mut Handle) -> R,
{
- ::tokio_timer::clock::with_default(&self.clock, || {
+ tokio::timer::clock::with_default(&self.clock, || {
let park = self.time.mock_park();
let timer = Timer::new(park);
let handle = timer.handle();
let time = self.time.clone();
- let _timer = ::tokio_timer::set_default(&handle);
+ let _timer = tokio::timer::set_default(&handle);
let mut handle = Handle::new(timer, time);
f(&mut handle)
// lazy(|| Ok::<_, ()>(f(&mut handle))).wait().unwrap()
diff --git a/tokio-test/src/io.rs b/tokio-test/src/io.rs
index ffbb07c5..6610c1db 100644
--- a/tokio-test/src/io.rs
+++ b/tokio-test/src/io.rs
@@ -16,6 +16,11 @@
//! [`AsyncRead`]: tokio_io::AsyncRead
//! [`AsyncWrite`]: tokio_io::AsyncWrite
+use tokio::timer::{clock, timer, Delay};
+use tokio_io::{AsyncRead, AsyncWrite, Buf};
+use tokio_sync::mpsc;
+
+use futures_core::ready;
use std::collections::VecDeque;
use std::future::Future;
use std::pin::Pin;
@@ -23,11 +28,6 @@ use std::task::{self, Poll, Waker};
use std::time::{Duration, Instant};
use std::{cmp, io};
-use futures_core::ready;
-use tokio_io::{AsyncRead, AsyncWrite, Buf};
-use tokio_sync::mpsc;
-use tokio_timer::{clock, timer, Delay};
-
/// An I/O object that follows a predefined script.
///
/// This value is created by `Builder` and implements `AsyncRead` + `AsyncWrite`. It
@@ -268,42 +268,6 @@ impl Inner {
}
}
-/*
-impl io::Read for Mock {
- fn read(&mut self, dst: &mut [u8]) -> io::Result<usize> {
- if self.is_async() {
- tokio::async_read(self, dst)
- } else {
- self.sync_read(dst)
- }
- }
-}
-
-impl io::Write for Mock {
- fn write(&mut self, src: &[u8]) -> io::Result<usize> {
- if self.is_async() {
- tokio::async_write(self, src)
- } else {
- self.sync_write(src)
- }
- }
-
- fn flush(&mut self) -> io::Result<()> {
- Ok(())
- }
-}
-*/
-
-/*
-use self::futures::{Future, Stream, Poll, Async};
-use self::futures::sync::mpsc;
-use self::futures::task::{self, Task};
-use self::tokio_io::{AsyncRead, AsyncWrite};
-use self::tokio_timer::{Timer, Sleep};
-
-use std::io;
-*/
-
// ===== impl Inner =====
impl Mock {
diff --git a/tokio-test/tests/block_on.rs b/tokio-test/tests/block_on.rs
index 9b4959e9..6d5f481a 100644
--- a/tokio-test/tests/block_on.rs
+++ b/tokio-test/tests/block_on.rs
@@ -1,8 +1,9 @@
#![warn(rust_2018_idioms)]
-use std::time::{Duration, Instant};
+use tokio::timer::delay;
use tokio_test::block_on;
-use tokio_timer::delay;
+
+use std::time::{Duration, Instant};
#[test]
fn async_block() {
diff --git a/tokio-test/tests/clock.rs b/tokio-test/tests/clock.rs
index 344c599b..abb61e23 100644
--- a/tokio-test/tests/clock.rs
+++ b/tokio-test/tests/clock.rs
@@ -1,12 +1,11 @@
-#![cfg(feature = "broken")]
#![warn(rust_2018_idioms)]
-use futures::Future;
-use std::time::{Duration, Instant};
+use tokio::timer::delay;
use tokio_test::clock::MockClock;
-use tokio_test::task::MockTask;
-use tokio_test::{assert_not_ready, assert_ready};
-use tokio_timer::delay;
+use tokio_test::task;
+use tokio_test::{assert_pending, assert_ready};
+
+use std::time::{Duration, Instant};
#[test]
fn clock() {
@@ -14,30 +13,13 @@ fn clock() {
mock.enter(|handle| {
let deadline = Instant::now() + Duration::from_secs(1);
- let mut delay = delay(deadline);
+ let mut delay = task::spawn(delay(deadline));
- assert_not_ready!(delay.poll());
+ assert_pending!(delay.poll());
handle.advance(Duration::from_secs(2));
- assert_ready!(delay.poll());
- });
-}
-
-#[test]
-fn notify() {
- let deadline = Instant::now() + Duration::from_secs(1);
- let mut mock = MockClock::new();
- let mut task = MockTask::new();
-
- mock.enter(|handle| {
- let mut delay = delay(deadline);
-
- task.enter(|| assert_not_ready!(delay.poll()));
-
- handle.advance(Duration::from_secs(1));
-
- assert!(task.is_notified());
+ assert!(delay.is_woken());
assert_ready!(delay.poll());
});
}
diff --git a/tokio-timer/CHANGELOG.md b/tokio-timer/CHANGELOG.md
deleted file mode 100644
index fecbcf5e..00000000
--- a/tokio-timer/CHANGELOG.md
+++ /dev/null
@@ -1,102 +0,0 @@
-# 0.3.0-alpha.6 (September 30, 2019)
-
-- Move to `futures-*-preview 0.3.0-alpha.19`
-- Move to `pin-project 0.4`
-
-# 0.3.0-alpha.5 (September 19, 2019)
-
-### Changed
-- rename `sleep` to `delay_for` (#1518).
-
-# 0.3.0-alpha.4 (August 29, 2019)
-
-- Track tokio release.
-
-# 0.3.0-alpha.3 (August 28, 2019)
-
-### Changed
-- `delay(...)` instead of `Delay::new(...)` (#1440).
-
-# 0.3.0-alpha.2 (August 17, 2019)
-
-### Changed
-- Update `futures` dependency to 0.3.0-alpha.18.
-- Switch `with_default(..., || )` to `set_default(...) -> Guard` (#1449).
-
-# 0.3.0-alpha.1 (August 8, 2019)
-
-### Changed
-- Switch to `async`, `await`, and `std::future`.
-
-# 0.2.11 (May 14, 2019)
-
-### Added
-- `Handle::timeout` API, replacing the deprecated `Handle::deadline` (#1074).
-
-# 0.2.10 (February 4, 2019)
-
-### Fixed
-- `DelayQueue` when multiple delays are reset (#871).
-
-# 0.2.9 (January 24, 2019)
-
-### Fixed
-- `DelayQueue` timing logic when inserting / resetting a delay (#851, #863).
-- Documentation links (#842, #844, #845)
-
-# 0.2.8 (November 21, 2018)
-
-* Implement throttle combinator (#736).
-* Derive `Clone` for `delay_queue::Key` (#730).
-* Bump internal dependencies (#753).
-
-# 0.2.7 (September 27, 2018)
-
-* Fix `Timeout` on error bug (#648).
-* Miscellaneous documentation improvements.
-
-# 0.2.6 (August 23, 2018)
-
-* Implement `Default` for `timer::Handle` (#553)
-* Provide `DelayQueue` utility (#550)
-* Reduce size of `Delay` struct (#554)
-* Introduce `Timeout`, deprecate `Deadline` (#558)
-
-# 0.2.5 (August 6, 2018)
-
-* Add `Interval::interval` shortcut (#492).
-
-# 0.2.4 (June 6, 2018)
-
-* Add `sleep` function for easy interval delays (#347).
-* Provide `clock::now()`, a configurable source of time (#381).
-
-# 0.2.3 (May 2, 2018)
-
-* Improve parking semantics (#327).
-
-# 0.2.2 (Skipped due to failure in counting module)
-
-# 0.2.1 (April 2, 2018)
-
-* Fix build on 32-bit systems (#274).
-
-# 0.2.0 (March 30, 2018)
-
-* Rewrite from scratch using a hierarchical wheel strategy (#249).
-
-# 0.1.2 (Jun 27, 2017)
-
-* Allow naming timer thread.
-* Track changes in dependencies.
-
-# 0.1.1 (Apr 6, 2017)
-
-* Set Rust v1.14 as the minimum supported version.
-* Fix bug related to intervals.
-* Impl `PartialEq + Eq` for TimerError.
-* Add `Debug` implementations.
-
-# 0.1.0 (Jan 11, 2017)
-
-* Initial Release
diff --git a/tokio-timer/Cargo.toml b/tokio-timer/Cargo.toml
deleted file mode 100644
index f6af121f..00000000
--- a/tokio-timer/Cargo.toml
+++ /dev/null
@@ -1,46 +0,0 @@
-[package]
-name = "tokio-timer"
-# When releasing to crates.io:
-# - Remove path dependencies
-# - Update html_root_url.
-# - Update doc url
-# - Cargo.toml
-# - README.md
-# - Update CHANGELOG.md.
-# - Create "v0.3.x" git tag.
-version = "0.3.0-alpha.6"
-edition = "2018"
-authors = ["Tokio Contributors <team@tokio.rs>"]
-license = "MIT"
-readme = "README.md"
-documentation = "https://docs.rs/tokio-timer/0.3.0-alpha.6/tokio_timer"
-repository = "https://github.com/tokio-rs/tokio"
-homepage = "https://github.com/tokio-rs/tokio"
-description = """
-Timer facilities for Tokio
-"""
-
-[features]
-async-traits = []
-
-[dependencies]
-tokio-executor = { version = "=0.2.0-alpha.6", path = "../tokio-executor" }
-tokio-sync = { version = "=0.2.0-alpha.6", path = "../tokio-sync" }
-
-futures-core-preview = "=0.3.0-alpha.19"
-futures-util-preview = "=0.3.0-alpha.19"
-
-crossbeam-utils = "0.6.0"
-# Backs `DelayQueue`
-slab = "0.4.1"
-# optionals
-
-[dev-dependencies]
-tokio = { version = "=0.2.0-alpha.6", path = "../tokio" }
-tokio-sync = { version = "=0.2.0-alpha.6", path = "../tokio-sync", features = ["async-traits"] }
-tokio-test = { version = "=0.2.0-alpha.6", path = "../tokio-test" }
-
-rand = "0.7"
-
-[package.metadata.docs.rs]
-all-features = true
diff --git a/tokio-timer/LICENSE b/tokio-timer/LICENSE
deleted file mode 100644
index cdb28b4b..00000000
--- a/tokio-timer/LICENSE
+++ /dev/null
@@ -1,25 +0,0 @@
-Copyright (c) 2019 Tokio Contributors
-
-Permission is hereby granted, free of charge, to any
-person obtaining a copy of this software and associated
-documentation files (the "Software"), to deal in the
-Software without restriction, including without
-limitation the rights to use, copy, modify, merge,
-publish, distribute, sublicense, and/or sell copies of
-the Software, and to permit persons to whom the Software
-is furnished to do so, subject to the following
-conditions:
-
-The above copyright notice and this permission notice
-shall be included in all copies or substantial portions
-of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
-ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
-TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
-PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
-SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
-CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
-OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
-IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
-DEALINGS IN THE SOFTWARE.
diff --git a/tokio-timer/README.md b/tokio-timer/README.md
deleted file mode 100644
index d3f07640..00000000
--- a/tokio-timer/README.md
+++ /dev/null
@@ -1,13 +0,0 @@
-# tokio-timer
-
-Timer facilities for Tokio
-
-## License
-
-This project is licensed under the [MIT license](LICENSE).
-
-### Contribution
-
-Unless you explicitly state otherwise, any contribution intentionally submitted
-for inclusion in Tokio by you, shall be licensed as MIT, without any additional
-terms or conditions.
diff --git a/tokio-timer/src/lib.rs b/tokio-timer/src/lib.rs
deleted file mode 100644
index b54f3b46..00000000
--- a/tokio-timer/src/lib.rs
+++ /dev/null
@@ -1,105 +0,0 @@
-#![doc(html_root_url = "https://docs.rs/tokio-timer/0.3.0-alpha.6")]
-#![warn(
- missing_debug_implementations,
- missing_docs,
- rust_2018_idioms,
- unreachable_pub
-)]
-#![deny(intra_doc_link_resolution_failure)]
-#![doc(test(
- no_crate_inject,
- attr(deny(warnings, rust_2018_idioms), allow(dead_code, unused_variables))
-))]
-
-//! Utilities for tracking time.
-//!
-//! This crate provides a number of utilities for working with periods of time:
-//!
-//! * [`Delay`]: A future that completes at a specified instant in time.
-//!
-//! * [`Interval`] A stream that yields at fixed time intervals.
-//!
-//! * [`Throttle`]: Throttle down a stream by enforcing a fixed delay between items.
-//!
-//! * [`Timeout`]: Wraps a future or stream, setting an upper bound to the
-//! amount of time it is allowed to execute. If the future or stream does not
-//! complete in time, then it is canceled and an error is returned.
-//!
-//! * [`DelayQueue`]: A queue where items are returned once the requested delay
-//! has expired.
-//!
-//! These three types are backed by a [`Timer`] instance. In order for
-//! [`Delay`], [`Interval`], and [`Timeout`] to function, the associated
-//! [`Timer`] instance must be running on some thread.
-//!
-//! [`Delay`]: struct.Delay.html
-//! [`DelayQueue`]: struct.DelayQueue.html
-//! [`Throttle`]: throttle::Throttle
-//! [`Timeout`]: struct.Timeout.html
-//! [`Interval`]: struct.Interval.html
-//! [`Timer`]: timer::Timer
-
-pub mod clock;
-pub mod delay_queue;
-#[cfg(feature = "async-traits")]
-pub mod throttle;
-pub mod timeout;
-pub mod timer;
-
-mod atomic;
-mod delay;
-mod error;
-mod interval;
-mod wheel;
-
-pub use delay::Delay;
-#[doc(inline)]
-pub use delay_queue::DelayQueue;
-pub use error::Error;
-pub use interval::Interval;
-#[doc(inline)]
-pub use timeout::Timeout;
-pub use timer::{set_default, Timer};
-
-use std::time::{Duration, Instant};
-
-/// Create a Future that completes at `deadline`.
-pub fn delay(deadline: Instant) -> Delay {
- Delay::new(deadline)
-}
-
-/// Create a Future that completes in `duration` from now.
-///
-/// Equivalent to `delay(tokio_timer::clock::now() + duration)`. Analogous to `std::thread::sleep`.
-pub fn delay_for(duration: Duration) -> Delay {
- delay(clock::now() + duration)
-}
-
-// ===== Internal utils =====
-
-enum Round {
- Up,
- Down,
-}
-
-/// Convert a `Duration` to milliseconds, rounding up and saturating at
-/// `u64::MAX`.
-///
-/// The saturating is fine because `u64::MAX` milliseconds are still many
-/// million years.
-#[inline]
-fn ms(duration: Duration, round: Round) -> u64 {
- const NANOS_PER_MILLI: u32 = 1_000_000;
- const MILLIS_PER_SEC: u64 = 1_000;
-
- // Round up.
- let millis = match round {
- Round::Up => (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI,
- Round::Down => duration.subsec_millis(),
- };
-
- duration
- .as_secs()
- .saturating_mul(MILLIS_PER_SEC)
- .saturating_add(u64::from(millis))
-}
diff --git a/tokio-timer/tests/support/mod.rs b/tokio-timer/tests/support/mod.rs
deleted file mode 100644
index f444a534..00000000
--- a/tokio-timer/tests/support/mod.rs
+++ /dev/null
@@ -1,265 +0,0 @@
-#![allow(unused_macros, unused_imports, dead_code, deprecated)]
-
-use tokio_executor::park::{Park, Unpark};
-use tokio_timer::clock::Now;
-use tokio_timer::timer::Timer;
-
-use futures::future::{lazy, Future};
-
-use std::marker::PhantomData;
-use std::rc::Rc;
-use std::sync::{Arc, Mutex};
-use std::time::{Duration, Instant};
-
-#[macro_export]
-macro_rules! assert_ready {
- ($f:expr) => {{
- use ::futures::Async::*;
-
- match $f.poll().unwrap() {
- Ready(v) => v,
- NotReady => panic!("NotReady"),
- }
- }};
- ($f:expr, $($msg:expr),+) => {{
- use ::futures::Async::*;
-
- match $f.poll().unwrap() {
- Ready(v) => v,
- NotReady => {
- let msg = format!($($msg),+);
- panic!("NotReady; {}", msg)
- }
- }
- }}
-}
-
-#[macro_export]
-macro_rules! assert_ready_eq {
- ($f:expr, $expect:expr) => {
- assert_eq!($f.poll().unwrap(), ::futures::Async::Ready($expect));
- };
-}
-
-#[macro_export]
-macro_rules! assert_not_ready {
- ($f:expr) => {{
- let res = $f.poll().unwrap();
- assert!(!res.is_ready(), "actual={:?}", res)
- }};
- ($f:expr, $($msg:expr),+) => {{
- let res = $f.poll().unwrap();
- if res.is_ready() {
- let msg = format!($($msg),+);
- panic!("actual={:?}; {}", res, msg);
- }
- }};
-}
-
-#[macro_export]
-macro_rules! assert_elapsed {
- ($f:expr) => {
- assert!($f.poll().unwrap_err().is_elapsed());
- };
-}
-
-#[derive(Debug)]
-pub struct MockTime {
- inner: Inner,
- _p: PhantomData<Rc<()>>,
-}
-
-#[derive(Debug)]
-pub struct MockNow {
- inner: Inner,
-}
-
-#[derive(Debug)]
-pub struct MockPark {
- inner: Inner,
- _p: PhantomData<Rc<()>>,
-}
-
-#[derive(Debug)]
-pub struct MockUnpark {
- inner: Inner,
-}
-
-type Inner = Arc<Mutex<State>>;
-
-#[derive(Debug)]
-struct State {
- base: Instant,
- advance: Duration,
- unparked: bool,
- park_for: Option<Duration>,
-}
-
-pub fn ms(num: u64) -> Duration {
- Duration::from_millis(num)
-}
-
-pub trait IntoTimeout {
- fn into_timeout(self) -> Option<Duration>;
-}
-
-impl IntoTimeout for Option<Duration> {
- fn into_timeout(self) -> Self {
- self
- }
-}
-
-impl IntoTimeout for Duration {
- fn into_timeout(self) -> Option<Duration> {
- Some(self)
- }
-}
-
-/// Turn the timer state once
-pub fn turn<T: IntoTimeout>(timer: &mut Timer<MockPark>, duration: T) {
- timer.turn(duration.into_timeout()).unwrap();
-}
-
-/// Advance the timer the specified amount
-pub fn advance(timer: &mut Timer<MockPark>, duration: Duration) {
- let inner = timer.get_park().inner.clone();
- let deadline = inner.lock().unwrap().now() + duration;
-
- while inner.lock().unwrap().now() < deadline {
- let dur = deadline - inner.lock().unwrap().now();
- turn(timer, dur);
- }
-}
-
-pub fn mocked<F, R>(f: F) -> R
-where
- F: FnOnce(&mut Timer<MockPark>, &mut MockTime) -> R,
-{
- mocked_with_now(Instant::now(), f)
-}
-
-pub fn mocked_with_now<F, R>(now: Instant, f: F) -> R
-where
- F: FnOnce(&mut Timer<MockPark>, &mut MockTime) -> R,
-{
- let mut time = MockTime::new(now);
- let park = time.mock_park();
- let now = ::tokio_timer::clock::Clock::new_with_now(time.mock_now());
-
- let mut enter = ::tokio_executor::enter().unwrap();
-
- ::tokio_timer::clock::with_default(&now, &mut enter, |enter| {
- let mut timer = Timer::new(park);
- let handle = timer.handle();
-
- ::tokio_timer::with_default(&handle, enter, |_| {
- lazy(|| Ok::<_, ()>(f(&mut timer, &mut time)))
- .wait()
- .unwrap()
- })
- })
-