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
use crate::Error as LimitationError;
use chrono::SubsecRound;
use std::{convert::TryInto, ops::Add, time::Duration};
#[derive(Clone, Debug)]
pub struct Status {
pub(crate) limit: usize,
pub(crate) remaining: usize,
pub(crate) reset_epoch_utc: usize,
}
impl Status {
pub fn limit(&self) -> usize {
self.limit
}
pub fn remaining(&self) -> usize {
self.remaining
}
pub fn reset_epoch_utc(&self) -> usize {
self.reset_epoch_utc
}
pub(crate) fn build_status(count: usize, limit: usize, reset_epoch_utc: usize) -> Self {
let remaining = if count >= limit { 0 } else { limit - count };
Status {
limit,
remaining,
reset_epoch_utc,
}
}
pub(crate) fn epoch_utc_plus(duration: Duration) -> Result<usize, LimitationError> {
match chrono::Duration::from_std(duration) {
Ok(value) => Ok(chrono::Utc::now()
.add(value)
.round_subsecs(0)
.timestamp()
.try_into()
.unwrap_or(0)),
Err(_) => Err(LimitationError::Other(
"Source duration value is out of range for the target type".to_string(),
)),
}
}
}
#[cfg(test)]
mod test;