chore: apply rustfmt to all crates (#917)

This commit is contained in:
Carl Lerche
2019-02-21 11:56:15 -08:00
committed by GitHub
parent ab595d0825
commit 80162306e7
253 changed files with 3710 additions and 3407 deletions
+3 -3
View File
@@ -35,16 +35,16 @@ mod imp {
}
pub fn compare_and_swap(&self, old: u64, new: u64, ordering: Ordering) -> u64 {
self.inner.compare_and_swap(
old as usize, new as usize, ordering) as u64
self.inner
.compare_and_swap(old as usize, new as usize, ordering) as u64
}
}
}
#[cfg(not(target_pointer_width = "64"))]
mod imp {
use std::sync::Mutex;
use std::sync::atomic::Ordering;
use std::sync::Mutex;
#[derive(Debug)]
pub struct AtomicU64 {
+16 -22
View File
@@ -12,7 +12,7 @@ use std::time::Instant;
///
/// `Clock` instances return [`Instant`] values corresponding to "now". The source
/// of these values is configurable. The default source is [`Instant::now`].
///
///
/// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html
/// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now
#[derive(Default, Clone)]
@@ -20,7 +20,7 @@ pub struct Clock {
now: Option<Arc<Now>>,
}
thread_local!{
thread_local! {
/// Thread-local tracking the current clock
static CLOCK: Cell<Option<*const Clock>> = Cell::new(None)
}
@@ -43,13 +43,9 @@ thread_local!{
/// let now = clock::now();
/// ```
pub fn now() -> Instant {
CLOCK.with(|current| {
match current.get() {
Some(ptr) => {
unsafe { (*ptr).now() }
}
None => Instant::now(),
}
CLOCK.with(|current| match current.get() {
Some(ptr) => unsafe { (*ptr).now() },
None => Instant::now(),
})
}
@@ -57,13 +53,9 @@ impl Clock {
/// Return a new `Clock` instance that uses the current execution context's
/// source of time.
pub fn new() -> Clock {
CLOCK.with(|current| {
match current.get() {
Some(ptr) => {
unsafe { (*ptr).clone() }
}
None => Clock::system(),
}
CLOCK.with(|current| match current.get() {
Some(ptr) => unsafe { (*ptr).clone() },
None => Clock::system(),
})
}
@@ -76,12 +68,10 @@ impl Clock {
/// Return a new `Clock` instance that uses [`Instant::now`] as the source
/// of time.
///
///
/// [`Instant::now`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now
pub fn system() -> Clock {
Clock {
now: None,
}
Clock { now: None }
}
/// Returns an instant corresponding to "now" by using the instance's source
@@ -121,10 +111,14 @@ impl fmt::Debug for Clock {
///
/// This function panics if there already is a default clock set.
pub fn with_default<F, R>(clock: &Clock, enter: &mut Enter, f: F) -> R
where F: FnOnce(&mut Enter) -> R
where
F: FnOnce(&mut Enter) -> R,
{
CLOCK.with(|cell| {
assert!(cell.get().is_none(), "default clock already set for execution context");
assert!(
cell.get().is_none(),
"default clock already set for execution context"
);
// Ensure that the clock is removed from the thread-local context
// when leaving the scope. This handles cases that involve panicking.
+1 -1
View File
@@ -19,5 +19,5 @@
mod clock;
mod now;
pub use self::clock::{Clock, now, with_default};
pub use self::clock::{now, with_default, Clock};
pub use self::now::Now;
+1 -1
View File
@@ -7,7 +7,7 @@ use std::time::Instant;
///
/// Implementations must ensure that calls to `now` return monotonically
/// increasing [`Instant`] values.
///
///
/// [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html
pub trait Now: Send + Sync + 'static {
/// Returns an instant corresponding to "now".
+5 -9
View File
@@ -2,7 +2,7 @@
use Delay;
use futures::{Future, Poll, Async};
use futures::{Async, Future, Poll};
use std::error;
use std::fmt;
@@ -42,10 +42,7 @@ impl<T> Deadline<T> {
}
pub(crate) fn new_with_delay(future: T, delay: Delay) -> Deadline<T> {
Deadline {
future,
delay,
}
Deadline { future, delay }
}
/// Gets a reference to the underlying future in this deadline.
@@ -65,7 +62,8 @@ impl<T> Deadline<T> {
}
impl<T> Future for Deadline<T>
where T: Future,
where
T: Future,
{
type Item = T::Item;
type Error = DeadlineError<T::Error>;
@@ -81,9 +79,7 @@ where T: Future,
// Now check the timer
match self.delay.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => {
Err(DeadlineError::elapsed())
},
Ok(Async::Ready(_)) => Err(DeadlineError::elapsed()),
Err(e) => Err(DeadlineError::timer(e)),
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
use timer::{HandlePriv, Registration};
use Error;
use timer::{Registration, HandlePriv};
use futures::{Future, Poll};
use std::time::{Instant, Duration};
use std::time::{Duration, Instant};
/// A future that completes at a specified instant in time.
///
+24 -24
View File
@@ -4,12 +4,12 @@
//!
//! [`DelayQueue`]: struct.DelayQueue.html
use {Error, Delay};
use clock::now;
use wheel::{self, Wheel};
use timer::Handle;
use wheel::{self, Wheel};
use {Delay, Error};
use futures::{Future, Stream, Poll};
use futures::{Future, Poll, Stream};
use slab::Slab;
use std::cmp;
@@ -339,10 +339,12 @@ impl<T> DelayQueue<T> {
self.insert_idx(when, key);
// Set a new delay if the current's deadline is later than the one of the new item
let should_set_delay = if let Some(ref delay) = self.delay {
let should_set_delay = if let Some(ref delay) = self.delay {
let current_exp = self.normalize_deadline(delay.deadline());
current_exp > when
} else { true };
} else {
true
};
if should_set_delay {
self.delay = Some(self.handle.delay(self.start + Duration::from_millis(when)));
@@ -414,9 +416,7 @@ impl<T> DelayQueue<T> {
// The delay is already expired, store it in the expired queue
self.expired.push(key, &mut self.slab);
}
Err((_, err)) => {
panic!("invalid deadline; err={:?}", err)
}
Err((_, err)) => panic!("invalid deadline; err={:?}", err),
}
}
@@ -510,15 +510,17 @@ impl<T> DelayQueue<T> {
self.slab[key.index].when = when;
self.insert_idx(when, key.index);
let next_deadline = self.next_deadline();
let next_deadline = self.next_deadline();
if let (Some(ref mut delay), Some(deadline)) = (&mut self.delay, next_deadline) {
delay.reset(deadline);
delay.reset(deadline);
}
}
/// Returns the next time poll as determined by the wheel
fn next_deadline(&mut self) -> Option<Instant> {
self.wheel.poll_at().map(|poll_at| self.start + Duration::from_millis(poll_at))
self.wheel
.poll_at()
.map(|poll_at| self.start + Duration::from_millis(poll_at))
}
/// Sets the delay of the item associated with `key` to expire after
@@ -691,9 +693,8 @@ impl<T> DelayQueue<T> {
if let Some(deadline) = self.next_deadline() {
self.delay = Some(self.handle.delay(deadline));
} else {
return Ok(None.into())
return Ok(None.into());
}
}
}
@@ -713,18 +714,17 @@ impl<T> Stream for DelayQueue<T> {
type Error = Error;
fn poll(&mut self) -> Poll<Option<Self::Item>, Error> {
let item = try_ready!(self.poll_idx())
.map(|idx| {
let data = self.slab.remove(idx);
debug_assert!(data.next.is_none());
debug_assert!(data.prev.is_none());
let item = try_ready!(self.poll_idx()).map(|idx| {
let data = self.slab.remove(idx);
debug_assert!(data.next.is_none());
debug_assert!(data.prev.is_none());
Expired {
key: Key::new(idx),
data: data.inner,
deadline: self.start + Duration::from_millis(data.when),
}
});
Expired {
key: Key::new(idx),
data: data.inner,
deadline: self.start + Duration::from_millis(data.when),
}
});
Ok(item.into())
}
+7 -7
View File
@@ -2,9 +2,9 @@ use Delay;
use clock;
use futures::{Future, Stream, Poll};
use futures::{Future, Poll, Stream};
use std::time::{Instant, Duration};
use std::time::{Duration, Instant};
/// A stream representing notifications at fixed interval
#[derive(Debug)]
@@ -28,7 +28,10 @@ impl Interval {
///
/// This function panics if `duration` is zero.
pub fn new(at: Instant, duration: Duration) -> Interval {
assert!(duration > Duration::new(0, 0), "`duration` must be non-zero.");
assert!(
duration > Duration::new(0, 0),
"`duration` must be non-zero."
);
Interval::new_with_delay(Delay::new(at), duration)
}
@@ -47,10 +50,7 @@ impl Interval {
}
pub(crate) fn new_with_delay(delay: Delay, duration: Duration) -> Interval {
Interval {
delay,
duration,
}
Interval { delay, duration }
}
}
+5 -2
View File
@@ -53,9 +53,9 @@ mod wheel;
#[doc(hidden)]
#[allow(deprecated)]
pub use self::deadline::{Deadline, DeadlineError};
pub use self::delay::Delay;
#[doc(inline)]
pub use self::delay_queue::DelayQueue;
pub use self::delay::Delay;
pub use self::error::Error;
pub use self::interval::Interval;
#[doc(inline)]
@@ -92,5 +92,8 @@ fn ms(duration: Duration, round: Round) -> u64 {
Round::Down => duration.subsec_nanos() / NANOS_PER_MILLI,
};
duration.as_secs().saturating_mul(MILLIS_PER_SEC).saturating_add(millis as u64)
duration
.as_secs()
.saturating_mul(MILLIS_PER_SEC)
.saturating_add(millis as u64)
}
+3 -9
View File
@@ -2,8 +2,8 @@
use {clock, Delay, Error};
use futures::{Async, Future, Poll, Stream};
use futures::future::Either;
use futures::{Async, Future, Poll, Stream};
use std::{
error::Error as StdError,
@@ -65,17 +65,11 @@ impl<T: Stream> Stream for Throttle<T> {
fn poll(&mut self) -> Poll<Option<Self::Item>, Self::Error> {
if let Some(ref mut delay) = self.delay {
try_ready!({
delay.poll()
.map_err(ThrottleError::from_timer_err)
});
try_ready!({ delay.poll().map_err(ThrottleError::from_timer_err) });
}
self.delay = None;
let value = try_ready!({
self.stream.poll()
.map_err(ThrottleError::from_stream_err)
});
let value = try_ready!({ self.stream.poll().map_err(ThrottleError::from_stream_err) });
if value.is_some() {
self.delay = Some(Delay::new(clock::now() + self.duration));
+11 -14
View File
@@ -4,14 +4,14 @@
//!
//! [`Timeout`]: struct.Timeout.html
use Delay;
use clock::now;
use Delay;
use futures::{Future, Stream, Poll, Async};
use futures::{Async, Future, Poll, Stream};
use std::error;
use std::fmt;
use std::time::{Instant, Duration};
use std::time::{Duration, Instant};
/// Allows a `Future` or `Stream` to execute for a limited amount of time.
///
@@ -127,10 +127,7 @@ impl<T> Timeout<T> {
pub fn new(value: T, timeout: Duration) -> Timeout<T> {
let delay = Delay::new_timeout(now() + timeout, timeout);
Timeout {
value,
delay,
}
Timeout { value, delay }
}
/// Gets a reference to the underlying value in this timeout.
@@ -168,7 +165,8 @@ impl<T: Future> Timeout<T> {
}
impl<T> Future for Timeout<T>
where T: Future,
where
T: Future,
{
type Item = T::Item;
type Error = Error<T::Error>;
@@ -184,16 +182,15 @@ where T: Future,
// Now check the timer
match self.delay.poll() {
Ok(Async::NotReady) => Ok(Async::NotReady),
Ok(Async::Ready(_)) => {
Err(Error::elapsed())
},
Ok(Async::Ready(_)) => Err(Error::elapsed()),
Err(e) => Err(Error::timer(e)),
}
}
}
impl<T> Stream for Timeout<T>
where T: Stream,
where
T: Stream,
{
type Item = T::Item;
type Error = Error<T::Error>;
@@ -205,7 +202,7 @@ where T: Stream,
if v.is_some() {
self.delay.reset_timeout();
}
return Ok(Async::Ready(v))
return Ok(Async::Ready(v));
}
Ok(Async::NotReady) => {}
Err(e) => return Err(Error::inner(e)),
@@ -217,7 +214,7 @@ where T: Stream,
Ok(Async::Ready(_)) => {
self.delay.reset_timeout();
Err(Error::elapsed())
},
}
Err(e) => Err(Error::timer(e)),
}
}
+5 -3
View File
@@ -1,10 +1,10 @@
use Error;
use super::Entry;
use Error;
use std::ptr;
use std::sync::Arc;
use std::sync::atomic::AtomicPtr;
use std::sync::atomic::Ordering::SeqCst;
use std::sync::Arc;
/// A stack of `Entry` nodes
#[derive(Debug)]
@@ -24,7 +24,9 @@ const SHUTDOWN: *mut Entry = 1 as *mut _;
impl AtomicStack {
pub fn new() -> AtomicStack {
AtomicStack { head: AtomicPtr::new(ptr::null_mut()) }
AtomicStack {
head: AtomicPtr::new(ptr::null_mut()),
}
}
/// Push an entry onto the stack.
+15 -22
View File
@@ -1,17 +1,17 @@
use Error;
use atomic::AtomicU64;
use timer::{HandlePriv, Inner};
use Error;
use crossbeam_utils::CachePadded;
use futures::Poll;
use futures::task::AtomicTask;
use futures::Poll;
use std::cell::UnsafeCell;
use std::ptr;
use std::sync::{Arc, Weak};
use std::sync::atomic::AtomicBool;
use std::sync::atomic::Ordering::{SeqCst, Relaxed};
use std::time::{Instant, Duration};
use std::sync::atomic::Ordering::{Relaxed, SeqCst};
use std::sync::{Arc, Weak};
use std::time::{Duration, Instant};
use std::u64;
/// Internal state shared between a `Delay` instance and the timer.
@@ -109,10 +109,7 @@ const ERROR: u64 = u64::MAX;
impl Entry {
pub fn new(deadline: Instant, duration: Duration) -> Entry {
Entry {
time: CachePadded::new(UnsafeCell::new(Time {
deadline,
duration,
})),
time: CachePadded::new(UnsafeCell::new(Time { deadline, duration })),
inner: None,
task: AtomicTask::new(),
state: AtomicU64::new(0),
@@ -147,8 +144,7 @@ impl Entry {
Err(_) => {
// Could not associate the entry with a timer, transition the
// state to error
Arc::get_mut(me).unwrap()
.transition_to_error();
Arc::get_mut(me).unwrap().transition_to_error();
return;
}
@@ -168,8 +164,7 @@ impl Entry {
None => {
// Could not associate the entry with a timer, transition the
// state to error
Arc::get_mut(me).unwrap()
.transition_to_error();
Arc::get_mut(me).unwrap().transition_to_error();
return;
}
@@ -177,15 +172,13 @@ impl Entry {
// Increment the number of active timeouts
if inner.increment().is_err() {
Arc::get_mut(me).unwrap()
.transition_to_error();
Arc::get_mut(me).unwrap().transition_to_error();
return;
}
// Associate the entry with the timer
Arc::get_mut(me).unwrap()
.inner = Some(handle.into_inner());
Arc::get_mut(me).unwrap().inner = Some(handle.into_inner());
let when = inner.normalize_deadline(deadline);
@@ -216,7 +209,9 @@ impl Entry {
}
pub fn set_when_internal(&self, when: Option<u64>) {
unsafe { (*self.when.get()) = when; }
unsafe {
(*self.when.get()) = when;
}
}
/// Called by `Timer` to load the current value of `state` for processing
@@ -361,8 +356,7 @@ impl Entry {
notify = true;
}
let actual = entry.state.compare_and_swap(
curr, next, SeqCst);
let actual = entry.state.compare_and_swap(curr, next, SeqCst);
if curr == actual {
break;
@@ -377,8 +371,7 @@ impl Entry {
}
fn upgrade_inner(&self) -> Option<Arc<Inner>> {
self.inner.as_ref()
.and_then(|inner| inner.upgrade())
self.inner.as_ref().and_then(|inner| inner.upgrade())
}
}
+21 -22
View File
@@ -1,5 +1,5 @@
use {Error, Delay, Deadline, Interval};
use timer::Inner;
use {Deadline, Delay, Error, Interval};
use tokio_executor::Enter;
@@ -44,7 +44,7 @@ pub(crate) struct HandlePriv {
inner: Weak<Inner>,
}
thread_local!{
thread_local! {
/// Tracks the timer for the current execution context.
static CURRENT_TIMER: RefCell<Option<HandlePriv>> = RefCell::new(None)
}
@@ -61,7 +61,8 @@ thread_local!{
/// [`Delay`]: ../struct.Delay.html
/// [`Delay::new`]: ../struct.Delay.html#method.new
pub fn with_default<F, R>(handle: &Handle, enter: &mut Enter, f: F) -> R
where F: FnOnce(&mut Enter) -> R
where
F: FnOnce(&mut Enter) -> R,
{
// Ensure that the timer is removed from the thread-local context
// when leaving the scope. This handles cases that involve panicking.
@@ -84,10 +85,14 @@ where F: FnOnce(&mut Enter) -> R
{
let mut current = current.borrow_mut();
assert!(current.is_none(), "default Tokio timer already set \
for execution context");
assert!(
current.is_none(),
"default Tokio timer already set \
for execution context"
);
let handle = handle.as_priv()
let handle = handle
.as_priv()
.unwrap_or_else(|| panic!("`handle` does not reference a timer"));
*current = Some(handle.clone());
@@ -118,23 +123,19 @@ impl Handle {
/// [`with_default`]: ../fn.with_default.html
/// [type]: #
pub fn current() -> Handle {
let private = HandlePriv::try_current()
.unwrap_or_else(|_| {
HandlePriv { inner: Weak::new() }
});
let private =
HandlePriv::try_current().unwrap_or_else(|_| HandlePriv { inner: Weak::new() });
Handle { inner: Some(private) }
Handle {
inner: Some(private),
}
}
/// Create a `Delay` driven by this handle's associated `Timer`.
pub fn delay(&self, deadline: Instant) -> Delay {
match self.inner {
Some(ref handle_priv) => {
Delay::new_with_handle(deadline, handle_priv.clone())
}
None => {
Delay::new(deadline)
}
Some(ref handle_priv) => Delay::new_with_handle(deadline, handle_priv.clone()),
None => Delay::new(deadline),
}
}
@@ -165,11 +166,9 @@ impl HandlePriv {
///
/// Returns `Err` if no handle is found.
pub(crate) fn try_current() -> Result<HandlePriv, Error> {
CURRENT_TIMER.with(|current| {
match *current.borrow() {
Some(ref handle) => Ok(handle.clone()),
None => Err(Error::shutdown()),
}
CURRENT_TIMER.with(|current| match *current.borrow() {
Some(ref handle) => Ok(handle.clone()),
None => Err(Error::shutdown()),
})
}
+16 -15
View File
@@ -44,23 +44,23 @@ use self::atomic_stack::AtomicStack;
use self::entry::Entry;
use self::stack::Stack;
pub use self::handle::{Handle, with_default};
pub(crate) use self::handle::HandlePriv;
pub use self::handle::{with_default, Handle};
pub use self::now::{Now, SystemNow};
pub(crate) use self::registration::Registration;
use Error;
use atomic::AtomicU64;
use wheel;
use Error;
use tokio_executor::park::{Park, Unpark, ParkThread};
use tokio_executor::park::{Park, ParkThread, Unpark};
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::sync::Arc;
use std::time::{Duration, Instant};
use std::usize;
use std::{cmp, fmt};
/// Timer implementation that drives [`Delay`], [`Interval`], and [`Timeout`].
///
@@ -171,7 +171,8 @@ const MAX_TIMEOUTS: usize = usize::MAX >> 1;
// ===== impl Timer =====
impl<T> Timer<T>
where T: Park
where
T: Park,
{
/// Create a new `Timer` instance that uses `park` to block the current
/// thread.
@@ -201,8 +202,9 @@ impl<T, N> Timer<T, N> {
}
impl<T, N> Timer<T, N>
where T: Park,
N: Now,
where
T: Park,
N: Now,
{
/// Create a new `Timer` instance that uses `park` to block the current
/// thread and `now` to get the current `Instant`.
@@ -268,8 +270,7 @@ where T: Park,
let mut poll = wheel::Poll::new(now);
while let Some(entry) = self.wheel.poll(&mut poll, &mut ()) {
let when = entry.when_internal()
.expect("invalid internal entry state");
let when = entry.when_internal().expect("invalid internal entry state");
// Fire the entry
entry.fire(when);
@@ -345,8 +346,9 @@ impl Default for Timer<ParkThread, SystemNow> {
}
impl<T, N> Park for Timer<T, N>
where T: Park,
N: Now,
where
T: Park,
N: Now,
{
type Unpark = T::Unpark;
type Error = T::Error;
@@ -483,7 +485,6 @@ impl Inner {
impl fmt::Debug for Inner {
fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
fmt.debug_struct("Inner")
.finish()
fmt.debug_struct("Inner").finish()
}
}
+1 -1
View File
@@ -7,4 +7,4 @@ pub trait Now {
fn now(&mut self) -> Instant;
}
pub use ::clock::Clock as SystemNow;
pub use clock::Clock as SystemNow;
+6 -4
View File
@@ -1,11 +1,11 @@
use Error;
use clock::now;
use timer::{HandlePriv, Entry};
use timer::{Entry, HandlePriv};
use Error;
use futures::Poll;
use std::sync::Arc;
use std::time::{Instant, Duration};
use std::time::{Duration, Instant};
/// Registration with a timer.
///
@@ -21,7 +21,9 @@ impl Registration {
fn is_send<T: Send + Sync>() {}
is_send::<Registration>();
Registration { entry: Arc::new(Entry::new(deadline, duration)) }
Registration {
entry: Arc::new(Entry::new(deadline, duration)),
}
}
pub fn deadline(&self) -> Instant {
+1 -3
View File
@@ -49,7 +49,6 @@ impl wheel::Stack for Stack {
// Set this entry's next pointer
*entry.next_stack.get() = old;
}
// Update the head pointer
@@ -117,7 +116,6 @@ impl wheel::Stack for Stack {
}
fn when(item: &Entry, _: &()) -> u64 {
item.when_internal()
.expect("invalid internal state")
item.when_internal().expect("invalid internal state")
}
}
+76 -11
View File
@@ -43,7 +43,9 @@ impl<T: Stack> Level<T> {
// contained by the array be `Copy`. So, here we have to manually
// initialize every single slot.
macro_rules! s {
() => { T::default() };
() => {
T::default()
};
};
Level {
@@ -52,14 +54,70 @@ impl<T: Stack> Level<T> {
slot: [
// It does not look like the necessary traits are
// derived for [T; 64].
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(), s!(), s!(), s!(), s!(), s!(), s!(), s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
s!(),
],
}
}
@@ -84,8 +142,15 @@ impl<T: Stack> Level<T> {
let level_start = now - (now % level_range);
let deadline = level_start + slot as u64 * slot_range;
debug_assert!(deadline >= now, "deadline={}; now={}; level={}; slot={}; occupied={:b}",
deadline, now, self.level, slot, self.occupied);
debug_assert!(
deadline >= now,
"deadline={}; now={}; level={}; slot={}; occupied={:b}",
deadline,
now,
self.level,
slot,
self.occupied
);
Some(Expiration {
level: self.level,
+61 -39
View File
@@ -1,9 +1,9 @@
mod level;
mod stack;
pub(crate) use self::stack::Stack;
pub(crate) use self::level::Expiration;
use self::level::Level;
pub(crate) use self::stack::Stack;
use std::borrow::Borrow;
use std::usize;
@@ -64,14 +64,9 @@ where
{
/// Create a new timing wheel
pub fn new() -> Wheel<T> {
let levels = (0..NUM_LEVELS)
.map(Level::new)
.collect();
let levels = (0..NUM_LEVELS).map(Level::new).collect();
Wheel {
elapsed: 0,
levels,
}
Wheel { elapsed: 0, levels }
}
/// Return the number of milliseconds that have elapsed since the timing
@@ -101,9 +96,12 @@ where
/// immediately.
///
/// `Err(Invalid)` indicates an invalid `when` argument as been supplied.
pub fn insert(&mut self, when: u64, item: T::Owned, store: &mut T::Store)
-> Result<(), (T::Owned, InsertError)>
{
pub fn insert(
&mut self,
when: u64,
item: T::Owned,
store: &mut T::Store,
) -> Result<(), (T::Owned, InsertError)> {
if when <= self.elapsed {
return Err((item, InsertError::Elapsed));
} else if when - self.elapsed > MAX_DURATION {
@@ -116,7 +114,8 @@ where
self.levels[level].add_entry(when, item, store);
debug_assert!({
self.levels[level].next_expiration(self.elapsed)
self.levels[level]
.next_expiration(self.elapsed)
.map(|e| e.deadline >= self.elapsed)
.unwrap_or(true)
});
@@ -134,23 +133,19 @@ where
/// Instant at which to poll
pub fn poll_at(&self) -> Option<u64> {
self.next_expiration()
.map(|expiration| expiration.deadline)
self.next_expiration().map(|expiration| expiration.deadline)
}
pub fn poll(&mut self, poll: &mut Poll, store: &mut T::Store)
-> Option<T::Owned>
{
pub fn poll(&mut self, poll: &mut Poll, store: &mut T::Store) -> Option<T::Owned> {
loop {
if poll.expiration.is_none() {
poll.expiration = self.next_expiration()
.and_then(|expiration| {
if expiration.deadline > poll.now {
None
} else {
Some(expiration)
}
});
poll.expiration = self.next_expiration().and_then(|expiration| {
if expiration.deadline > poll.now {
None
} else {
Some(expiration)
}
});
}
match poll.expiration {
@@ -181,7 +176,7 @@ where
debug_assert!({
let mut res = true;
for l2 in (level+1)..NUM_LEVELS {
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;
@@ -199,9 +194,11 @@ where
None
}
pub fn poll_expiration(&mut self, expiration: &Expiration, store: &mut T::Store)
-> Option<T::Owned>
{
pub fn poll_expiration(
&mut self,
expiration: &Expiration,
store: &mut T::Store,
) -> Option<T::Owned> {
while let Some(item) = self.pop_entry(expiration, store) {
if expiration.level == 0 {
debug_assert_eq!(T::when(item.borrow(), store), expiration.deadline);
@@ -212,8 +209,7 @@ where
let next_level = expiration.level - 1;
self.levels[next_level]
.add_entry(when, item, store);
self.levels[next_level].add_entry(when, item, store);
}
}
@@ -221,7 +217,12 @@ where
}
fn set_elapsed(&mut self, when: u64) {
assert!(self.elapsed <= when, "elapsed={:?}; when={:?}", self.elapsed, when);
assert!(
self.elapsed <= when,
"elapsed={:?}; when={:?}",
self.elapsed,
when
);
if when > self.elapsed {
self.elapsed = when;
@@ -263,25 +264,46 @@ mod test {
#[test]
fn test_level_for() {
for pos in 1..64 {
assert_eq!(0, level_for(0, pos), "level_for({}) -- binary = {:b}", pos, pos);
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);
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);
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);
assert_eq!(
level,
level_for(0, a as u64),
"level_for({}) -- binary = {:b}",
a,
a
);
}
}
}