Skip to content

Commit

Permalink
fix fmt.
Browse files Browse the repository at this point in the history
  • Loading branch information
fakeshadow committed Jan 19, 2024
1 parent f234432 commit 495a85f
Show file tree
Hide file tree
Showing 10 changed files with 34 additions and 108 deletions.
6 changes: 1 addition & 5 deletions http-rate/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,7 @@ pub struct InsufficientCapacity(pub u32);

impl fmt::Display for InsufficientCapacity {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"required number of cells {} exceeds bucket's capacity",
self.0
)
write!(f, "required number of cells {} exceeds bucket's capacity", self.0)
}
}

Expand Down
13 changes: 3 additions & 10 deletions http-rate/src/gcra.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,9 +70,7 @@ pub(crate) struct Gcra {

impl Gcra {
pub(crate) fn new(quota: Quota) -> Self {
let tau: Nanos = (cmp::max(quota.replenish_1_per, Duration::from_nanos(1))
* quota.max_burst.get())
.into();
let tau: Nanos = (cmp::max(quota.replenish_1_per, Duration::from_nanos(1)) * quota.max_burst.get()).into();
let t: Nanos = quota.replenish_1_per.into();
Gcra { t, tau }
}
Expand Down Expand Up @@ -187,20 +185,15 @@ mod test {
impl Arbitrary for Count {
type Parameters = ();
fn arbitrary_with(_args: ()) -> Self::Strategy {
(1..10000u32)
.prop_map(|x| Count(NonZeroU32::new(x).unwrap()))
.boxed()
(1..10000u32).prop_map(|x| Count(NonZeroU32::new(x).unwrap())).boxed()
}

type Strategy = BoxedStrategy<Count>;
}

#[test]
fn cover_count_derives() {
assert_eq!(
format!("{:?}", Count(NonZeroU32::new(1).unwrap())),
"Count(1)"
);
assert_eq!(format!("{:?}", Count(NonZeroU32::new(1).unwrap())), "Count(1)");
}

#[test]
Expand Down
21 changes: 4 additions & 17 deletions http-rate/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,7 @@ impl RateLimit {
/// all headers are absent or can't provide valid client address.
///
/// [Request]: http::Request
pub fn rate_limit(
&self,
headers: &HeaderMap,
addr: &SocketAddr,
) -> Result<RateSnapshot, TooManyRequests> {
pub fn rate_limit(&self, headers: &HeaderMap, addr: &SocketAddr) -> Result<RateSnapshot, TooManyRequests> {
let addr = maybe_x_forwarded_for(headers)
.or_else(|| maybe_x_real_ip(headers))
.or_else(|| maybe_forwarded(headers))
Expand Down Expand Up @@ -221,18 +217,9 @@ mod test {
let clock = FakeRelativeClock::default();
let lb = RateLimiter::direct_with_clock(Quota::per_second(5), &clock);

assert_eq!(
Err(InsufficientCapacity(5)),
lb.check_n(NonZeroU32::new(15).unwrap())
);
assert_eq!(
Err(InsufficientCapacity(5)),
lb.check_n(NonZeroU32::new(6).unwrap())
);
assert_eq!(
Err(InsufficientCapacity(5)),
lb.check_n(NonZeroU32::new(7).unwrap())
);
assert_eq!(Err(InsufficientCapacity(5)), lb.check_n(NonZeroU32::new(15).unwrap()));
assert_eq!(Err(InsufficientCapacity(5)), lb.check_n(NonZeroU32::new(6).unwrap()));
assert_eq!(Err(InsufficientCapacity(5)), lb.check_n(NonZeroU32::new(7).unwrap()));
}

#[test]
Expand Down
6 changes: 1 addition & 5 deletions http-rate/src/nanos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,11 +32,7 @@ impl Nanos {
impl From<Duration> for Nanos {
fn from(d: Duration) -> Self {
// This will panic:
Nanos(
d.as_nanos()
.try_into()
.expect("Duration is longer than 584 years"),
)
Nanos(d.as_nanos().try_into().expect("Duration is longer than 584 years"))
}
}

Expand Down
13 changes: 3 additions & 10 deletions http-rate/src/quota.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,8 +78,7 @@ impl Quota {
B::Error: fmt::Debug,
{
let max_burst = max_burst.try_into().unwrap();
let replenish_interval_ns =
Duration::from_secs(60 * 60).as_nanos() / (max_burst.get() as u128);
let replenish_interval_ns = Duration::from_secs(60 * 60).as_nanos() / (max_burst.get() as u128);
Self {
max_burst,
replenish_1_per: Duration::from_nanos(replenish_interval_ns as u64),
Expand Down Expand Up @@ -162,14 +161,8 @@ mod test {
let minutely = Quota::per_minute(1);
let secondly = Quota::per_second(1);

assert_eq!(
hourly.replenish_interval() / 60,
minutely.replenish_interval()
);
assert_eq!(
minutely.replenish_interval() / 60,
secondly.replenish_interval()
);
assert_eq!(hourly.replenish_interval() / 60, minutely.replenish_interval());
assert_eq!(minutely.replenish_interval() / 60, secondly.replenish_interval());
}

#[test]
Expand Down
29 changes: 5 additions & 24 deletions http-rate/src/snapshot.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ impl RateSnapshot {

fn remaining_burst_capacity(&self) -> u32 {
let t0 = self.time_of_measurement + self.t;
(cmp::min(
(t0 + self.tau).saturating_sub(self.tat).as_u64(),
self.tau.as_u64(),
) / self.t.as_u64()) as u32
(cmp::min((t0 + self.tau).saturating_sub(self.tat).as_u64(), self.tau.as_u64()) / self.t.as_u64()) as u32
}
}

Expand All @@ -68,26 +65,10 @@ mod test {
fn state_information() {
let clock = FakeRelativeClock::default();
let lim = RateLimiter::direct_with_clock(Quota::per_second(4), &clock);
assert_eq!(
Ok(3),
lim.check()
.map(|outcome| outcome.remaining_burst_capacity())
);
assert_eq!(
Ok(2),
lim.check()
.map(|outcome| outcome.remaining_burst_capacity())
);
assert_eq!(
Ok(1),
lim.check()
.map(|outcome| outcome.remaining_burst_capacity())
);
assert_eq!(
Ok(0),
lim.check()
.map(|outcome| outcome.remaining_burst_capacity())
);
assert_eq!(Ok(3), lim.check().map(|outcome| outcome.remaining_burst_capacity()));
assert_eq!(Ok(2), lim.check().map(|outcome| outcome.remaining_burst_capacity()));
assert_eq!(Ok(1), lim.check().map(|outcome| outcome.remaining_burst_capacity()));
assert_eq!(Ok(0), lim.check().map(|outcome| outcome.remaining_burst_capacity()));
assert!(lim.check().is_err());
}

Expand Down
4 changes: 2 additions & 2 deletions http-rate/src/state/direct.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use core::num::NonZeroU32;

use crate::{
error::InsufficientCapacity, gcra::NotUntil, quota::Quota, snapshot::RateSnapshot,
state::InMemoryState, timer, timer::DefaultTimer,
error::InsufficientCapacity, gcra::NotUntil, quota::Quota, snapshot::RateSnapshot, state::InMemoryState, timer,
timer::DefaultTimer,
};

/// The "this state store does not use keys" key type.
Expand Down
15 changes: 5 additions & 10 deletions http-rate/src/state/in_memory.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@ impl InMemoryState {
let mut prev = self.0.load(Ordering::Acquire);
let mut decision = f(NonZeroU64::new(prev).map(|n| n.get().into()));
while let Ok((result, new_data)) = decision {
match self.0.compare_exchange_weak(
prev,
new_data.into(),
Ordering::Release,
Ordering::Relaxed,
) {
match self
.0
.compare_exchange_weak(prev, new_data.into(), Ordering::Release, Ordering::Relaxed)
{
Ok(_) => return Ok(result),
Err(next_prev) => prev = next_prev,
}
Expand Down Expand Up @@ -91,10 +89,7 @@ mod test {
assert!(state
.measure_and_replace_one(|old| {
hits += 1;
Ok::<((), Nanos), ()>((
(),
Nanos::from(old.map(Nanos::as_u64).unwrap_or(0) + 1),
))
Ok::<((), Nanos), ()>(((), Nanos::from(old.map(Nanos::as_u64).unwrap_or(0) + 1)))
})
.is_ok());
}
Expand Down
20 changes: 5 additions & 15 deletions http-rate/src/state/keyed.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
use core::hash::Hash;

use crate::{
gcra::NotUntil, nanos::Nanos, quota::Quota, snapshot::RateSnapshot, state::RateLimiter,
state::StateStore, timer,
gcra::NotUntil, nanos::Nanos, quota::Quota, snapshot::RateSnapshot, state::RateLimiter, state::StateStore, timer,
};

#[cfg(test)]
Expand Down Expand Up @@ -59,12 +58,8 @@ where
/// If the rate limit is reached, `check_key` returns information about the earliest
/// time that a cell might be allowed through again under that key.
pub fn check_key(&self, key: &K) -> Result<RateSnapshot, NotUntil<C::Instant>> {
self.gcra.test_and_update::<K, C::Instant, S>(
self.start,
key,
&self.state,
self.clock.now(),
)
self.gcra
.test_and_update::<K, C::Instant, S>(self.start, key, &self.state, self.clock.now())
}

#[cfg(test)]
Expand All @@ -87,13 +82,8 @@ where
key: &K,
n: NonZeroU32,
) -> Result<Result<RateSnapshot, NotUntil<C::Instant>>, InsufficientCapacity> {
self.gcra.test_n_all_and_update::<K, C::Instant, S>(
self.start,
key,
n,
&self.state,
self.clock.now(),
)
self.gcra
.test_n_all_and_update::<K, C::Instant, S>(self.start, key, n, &self.state, self.clock.now())
}
}

Expand Down
15 changes: 5 additions & 10 deletions http-rate/src/timer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,7 @@ pub trait Timer: Clone {

impl Reference for Duration {
fn duration_since(&self, earlier: Self) -> Nanos {
self.checked_sub(earlier)
.unwrap_or_else(|| Duration::new(0, 0))
.into()
self.checked_sub(earlier).unwrap_or_else(|| Duration::new(0, 0)).into()
}

fn saturating_sub(&self, duration: Nanos) -> Self {
Expand Down Expand Up @@ -78,9 +76,9 @@ impl FakeRelativeClock {

let mut prev = self.now.load(Ordering::Acquire);
let mut next = prev + by;
while let Err(next_prev) =
self.now
.compare_exchange_weak(prev, next, Ordering::Release, Ordering::Relaxed)
while let Err(next_prev) = self
.now
.compare_exchange_weak(prev, next, Ordering::Release, Ordering::Relaxed)
{
prev = next_prev;
next = prev + by;
Expand Down Expand Up @@ -191,9 +189,6 @@ mod test {
assert_ne!(now + ns_dur, now, "{:?} + {:?}", ns_dur, now);
assert_eq!(one_ns, Reference::duration_since(&(now + one_ns), now));
assert_eq!(Nanos::new(0), Reference::duration_since(&now, now + one_ns));
assert_eq!(
Reference::saturating_sub(&(now + Duration::from_nanos(1)), one_ns),
now
);
assert_eq!(Reference::saturating_sub(&(now + Duration::from_nanos(1)), one_ns), now);
}
}

0 comments on commit 495a85f

Please sign in to comment.