mod entry;
mod handle;
mod level;
mod now;
mod registration;
use self::entry::Entry;
use self::level::{Level, Expiration};
pub use self::handle::{Handle, with_default};
pub use self::now::{Now, SystemNow};
pub(crate) use self::registration::Registration;
use Error;
use atomic::AtomicU64;
use tokio_executor::park::{Park, Unpark, ParkThread};
use std::{cmp, fmt};
use std::time::{Duration, Instant};
use std::sync::Arc;
use std::sync::atomic::AtomicUsize;
use std::sync::atomic::Ordering::SeqCst;
use std::usize;
#[derive(Debug)]
pub struct Timer<T, N = SystemNow> {
inner: Arc<Inner>,
elapsed: u64,
levels: Vec<Level>,
park: T,
now: N,
}
#[derive(Debug)]
pub struct Turn(());
pub(crate) struct Inner {
start: Instant,
elapsed: AtomicU64,
num: AtomicUsize,
process: entry::AtomicStack,
unpark: Box<Unpark>,
}
const NUM_LEVELS: usize = 6;
const MAX_DURATION: u64 = 1 << (6 * NUM_LEVELS);
const MAX_TIMEOUTS: usize = usize::MAX >> 1;
impl<T> Timer<T>
where T: Park
{
pub fn new(park: T) -> Self {
Timer::new_with_now(park, SystemNow::new())
}
}
impl<T, N> Timer<T, N> {
pub fn get_park(&self) -> &T {
&self.park
}
pub fn get_park_mut(&mut self) -> &mut T {
&mut self.park
}
}
impl<T, N> Timer<T, N>
where T: Park,
N: Now,
{
pub fn new_with_now(park: T, mut now: N) -> Self {
let unpark = Box::new(park.unpark());
let levels = (0..NUM_LEVELS)
.map(Level::new)
.collect();
Timer {
inner: Arc::new(Inner::new(now.now(), unpark)),
elapsed: 0,
levels,
park,
now,
}
}
pub fn handle(&self) -> Handle {
Handle::new(Arc::downgrade(&self.inner))
}
pub fn turn(&mut self, max_wait: Option<Duration>) -> Result<Turn, T::Error> {
match max_wait {
Some(timeout) => self.park_timeout(timeout)?,
None => self.park()?,
}
Ok(Turn(()))
}
fn next_expiration(&self) -> Option<Expiration> {
for level in 0..NUM_LEVELS {
if let Some(expiration) = self.levels[level].next_expiration(self.elapsed) {
debug_assert!({
let mut res = true;
for l2 in (level+1)..NUM_LEVELS {
if let Some(e2) = self.levels[l2].next_expiration(self.elapsed) {
if e2.deadline < expiration.deadline {
res = false;
}
}
}
res
});
return Some(expiration);
}
}
None
}
fn expiration_instant(&self, expiration: &Expiration) -> Instant {
self.inner.start + Duration::from_millis(expiration.deadline)
}
fn process(&mut self) {
let now = ms(self.now.now() - self.inner.start, Round::Down);
loop {
let expiration = match self.next_expiration() {
Some(expiration) => expiration,
None => break,
};
if expiration.deadline > now {
break;
}
self.process_expiration(&expiration);
self.set_elapsed(expiration.deadline);
}
self.set_elapsed(now);
}
fn set_elapsed(&mut self, when: u64) {
assert!(self.elapsed <= when, "elapsed={:?}; when={:?}", self.elapsed, when);
if when > self.elapsed {
self.elapsed = when;
self.inner.elapsed.store(when, SeqCst);
} else {
assert_eq!(self.elapsed, when);
}
}
fn process_expiration(&mut self, expiration: &Expiration) {
while let Some(entry) = self.pop_entry(expiration) {
if expiration.level == 0 {
let when = entry.when_internal()
.expect("invalid internal entry state");
debug_assert_eq!(when, expiration.deadline);
entry.fire(when);
entry.set_when_internal(None);
} else {
let when = entry.when_internal()
.expect("entry not tracked");
let next_level = expiration.level - 1;
self.levels[next_level]
.add_entry(entry, when);
}
}
}
fn pop_entry(&mut self, expiration: &Expiration) -> Option<Arc<Entry>> {
self.levels[expiration.level].pop_entry_slot(expiration.slot)
}
fn process_queue(&mut self) {
for entry in self.inner.process.take() {
match (entry.when_internal(), entry.load_state()) {
(None, None) => {
}
(Some(when), None) => {
self.clear_entry(&entry, when);
}
(None, Some(when)) => {
self.add_entry(entry, when);
}
(Some(curr), Some(next)) => {
self.clear_entry(&entry, curr);
self.add_entry(entry, next);
}
}
}
}
fn clear_entry(&mut self, entry: &Arc<Entry>, when: u64) {
let level = self.level_for(when);
self.levels[level].remove_entry(entry, when);
entry.set_when_internal(None);
}
fn add_entry(&mut self, entry: Arc<Entry>, when: u64) {
if when <= self.elapsed {
entry.set_when_internal(None);
entry.fire(when);
return;
} else if when - self.elapsed > MAX_DURATION {
entry.set_when_internal(None);
entry.error();
return;
}
let level = self.level_for(when);
entry.set_when_internal(Some(when));
self.levels[level].add_entry(entry, when);
debug_assert!({
self.levels[level].next_expiration(self.elapsed)
.map(|e| e.deadline >= self.elapsed)
.unwrap_or(true)
});
}
fn level_for(&self, when: u64) -> usize {
level_for(self.elapsed, when)
}
}
fn level_for(elapsed: u64, when: u64) -> usize {
let masked = elapsed ^ when;
assert!(masked != 0, "elapsed={}; when={}", elapsed, when);
let leading_zeros = masked.leading_zeros() as usize;
let significant = 63 - leading_zeros;
significant / 6
}
impl Default for Timer<ParkThread, SystemNow> {
fn default() -> Self {
Timer::new(ParkThread::new())
}
}
impl<T, N> Park for Timer<T, N>
where T: Park,
N: Now,
{
type Unpark = T::Unpark;
type Error = T::Error;
fn unpark(&self) -> Self::Unpark {
self.park.unpark()
}
fn park(&mut self) -> Result<(), Self::Error> {
self.process_queue();
match self.next_expiration() {
Some(expiration) => {
let now = self.now.now();
let deadline = self.expiration_instant(&expiration);
if deadline > now {
self.park.park_timeout(deadline - now)?;
} else {
self.park.park_timeout(Duration::from_secs(0))?;
}
}
None => {
self.park.park()?;
}
}
self.process();
Ok(())
}
fn park_timeout(&mut self, duration: Duration) -> Result<(), Self::Error> {
self.process_queue();
match self.next_expiration() {
Some(expiration) => {
let now = self.now.now();
let deadline = self.expiration_instant(&expiration);
if deadline > now {
self.park.park_timeout(cmp::min(deadline - now, duration))?;
} else {
self.park.park_timeout(Duration::from_secs(0))?;
}
}
None => {
self.park.park_timeout(duration)?;
}
}
self.process();
Ok(())
}
}
impl<T, N> Drop for Timer<T, N> {
fn drop(&mut self) {
self.inner.process.shutdown();
}
}
impl Inner {
fn new(start: Instant, unpark: Box<Unpark>) -> Inner {
Inner {
num: AtomicUsize::new(0),
elapsed: AtomicU64::new(0),
process: entry::AtomicStack::new(),
start,
unpark,
}
}
fn elapsed(&self) -> u64 {
self.elapsed.load(SeqCst)
}
fn increment(&self) -> Result<(), Error> {
let mut curr = self.num.load(SeqCst);
loop {
if curr == MAX_TIMEOUTS {
return Err(Error::at_capacity());
}
let actual = self.num.compare_and_swap(curr, curr + 1, SeqCst);
if curr == actual {
return Ok(());
}
curr = actual;
}
}
fn decrement(&self) {
let prev = self.num.fetch_sub(1, SeqCst);
debug_assert!(prev <= MAX_TIMEOUTS);
}
fn queue(&self, entry: &Arc<Entry>) -> Result<(), Error> {
if self.process.push(entry)? {
self.unpark.unpark();
}
Ok(())
}
fn normalize_deadline(&self, deadline: Instant) -> u64 {
if deadline < self.start {
return 0;
}
ms(deadline - self.start, Round::Up)
}
}
impl fmt::Debug for Inner {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Inner")
.finish()
}
}
enum Round {
Up,
Down,
}
#[inline]
fn ms(duration: Duration, round: Round) -> u64 {
const NANOS_PER_MILLI: u32 = 1_000_000;
const MILLIS_PER_SEC: u64 = 1_000;
let millis = match round {
Round::Up => (duration.subsec_nanos() + NANOS_PER_MILLI - 1) / NANOS_PER_MILLI,
Round::Down => duration.subsec_nanos() / NANOS_PER_MILLI,
};
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_level_for() {
for pos in 1..64 {
assert_eq!(0, level_for(0, pos), "level_for({}) -- binary = {:b}", pos, pos);
}
for level in 1..5 {
for pos in level..64 {
let a = pos * 64_usize.pow(level as u32);
assert_eq!(level, level_for(0, a as u64),
"level_for({}) -- binary = {:b}", a, a);
if pos > level {
let a = a - 1;
assert_eq!(level, level_for(0, a as u64),
"level_for({}) -- binary = {:b}", a, a);
}
if pos < 64 {
let a = a + 1;
assert_eq!(level, level_for(0, a as u64),
"level_for({}) -- binary = {:b}", a, a);
}
}
}
}
}