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
//! A hierarchical timer wheel
//!
//! There are 3 wheels in the hierarchy, of resolution 10ms, 1s, and 1m. The max timeout length is 1
//! hour. Any timer scheduled over 1 hour will expire in 1 hour.
//!
//! There is no migration between wheels. A timer is assigned to a single wheel and is scheduled at
//! the max resolution of the wheel. E.g. If a timer is scheduled for 1.3s it will be scheduled to
//! fire 2 second ticks later. This is most useful for coarse grain timers and is more efficient
//! computationally and uses less memory than being more precise. The wheels don't have to keep
//! track of offsets for the next inner wheel so the timer can be rescheduled when the outer wheel
//! slot expires. And it doesn't have to actually do the reschedule, saving cpu, and potentially
//! extra allocations.

extern crate time;

mod alloc_wheel;
mod copy_wheel;

pub use alloc_wheel::AllocWheel;
pub use copy_wheel::CopyWheel;

use std::hash::Hash;
use std::fmt::Debug;
use time::Duration;

/// A resolution for a wheel in the hierarchy
///
/// The tick rate of the wheel must match the highest resolution of the wheel.
#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
pub enum Resolution {
    Ms,
    TenMs,
    HundredMs,
    Sec,
    Min,
    Hour
}

pub trait Wheel<T: Eq + Hash + Debug + Clone> {
    fn start(&mut self, key: T, time: Duration);
    fn stop(&mut self, key: T);
    fn expire(&mut self) -> Vec<T>;
}

/// An entry in a InnerWheel
#[derive(Debug, Clone)]
struct Slot<T: Debug + Clone> {
    pub entries: Vec<T>
}

impl<T: Debug + Clone> Slot<T> {
    pub fn new() -> Slot<T> {
        Slot {
            entries: Vec::new()
        }
    }
}

/// A wheel at a single resolution
struct InnerWheel<T: Debug + Clone> {
    pub slots: Vec<Slot<T>>
}

impl<T: Debug + Clone> InnerWheel<T> {
    pub fn new(size: usize) -> InnerWheel<T> {
        InnerWheel {
            slots: vec![Slot::new(); size]
        }
    }
}

/// Determine the wheel size for each resolution.
///
/// Wheel sizes less than one second are adjusted based on the next lowest resolution so that
/// resolutions don't overlap.
pub fn wheel_sizes(resolutions: &mut Vec<Resolution>) -> Vec<usize> {
    assert!(resolutions.len() > 0);
    resolutions.sort();
    resolutions.dedup();
    let end = resolutions.len() - 1;
    let mut sizes = Vec::with_capacity(resolutions.len());
    for i in 0..resolutions.len() {
        let wheel_size = match resolutions[i] {
            Resolution::Ms => {
                if i == end {
                    1000
                } else {
                    match resolutions[i+1] {
                        Resolution::TenMs => 10,
                        Resolution::HundredMs => 100,
                        _ => 1000
                    }
                }
            },
            Resolution::TenMs => {
                if i == end {
                    100
                } else {
                    match resolutions[i+1] {
                        Resolution::HundredMs => 10,
                        _ => 100
                    }
                }
            },
            Resolution::HundredMs => 10,
            Resolution::Sec => 60,
            Resolution::Min => 60,
            Resolution::Hour => 24
        };
        sizes.push(wheel_size);
    }
    sizes
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn resolutions_sorted_and_deduped() {
        let mut resolutions = vec![Resolution::Sec, Resolution::Min, Resolution::TenMs, Resolution::Min];
        let _ = wheel_sizes(&mut resolutions);
        assert_eq!(vec![Resolution::TenMs, Resolution::Sec, Resolution::Min], resolutions);
    }

    #[test]
    fn wheel_sizes_correct() {
        let mut resolutions = vec![
            vec![Resolution::Ms, Resolution::TenMs, Resolution::Sec],
            vec![Resolution::Ms, Resolution::HundredMs, Resolution::Sec, Resolution::Min],
            vec![Resolution::Ms, Resolution::Sec],
            vec![Resolution::TenMs, Resolution::HundredMs, Resolution::Sec]
        ];

        let expected = vec![
            vec![10, 100, 60],
            vec![100, 10, 60, 60],
            vec![1000, 60],
            vec![10, 10, 60]
        ];

        for (mut r, expected) in resolutions.iter_mut().zip(expected) {
            assert_eq!(expected, wheel_sizes(&mut r));
        }
    }
}