Passed
Push — main ( 86d0d3...7f8afa )
by
unknown
02:04 queued 14s
created

SlidingWindow.__init__()   A

Complexity

Conditions 1

Size

Total Lines 7
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 6
dl 0
loc 7
rs 10
c 0
b 0
f 0
cc 1
nop 3
1
# -*- coding: utf-8 -*-
0 ignored issues
show
introduced by
Missing module docstring
Loading history...
2
# MIT License
3
#
4
# Copyright (c) 2021 Pincer
5
#
6
# Permission is hereby granted, free of charge, to any person obtaining
7
# a copy of this software and associated documentation files
8
# (the "Software"), to deal in the Software without restriction,
9
# including without limitation the rights to use, copy, modify, merge,
10
# publish, distribute, sublicense, and/or sell copies of the Software,
11
# and to permit persons to whom the Software is furnished to do so,
12
# subject to the following conditions:
13
#
14
# The above copyright notice and this permission notice shall be
15
# included in all copies or substantial portions of the Software.
16
#
17
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
18
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
20
# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
21
# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22
# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23
# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24
from time import time
25
26
27
class SlidingWindow:
0 ignored issues
show
introduced by
Missing class docstring
Loading history...
28
    def __init__(self, capacity: int, time_unit: float):
29
        self.capacity: int = capacity
30
        self.time_unit: float = time_unit
31
32
        self.__cur_time: float = time()
33
        self.__pre_count: int = capacity
34
        self.__cur_count: int = 0
35
36
    def allow(self) -> bool:
0 ignored issues
show
introduced by
Missing function or method docstring
Loading history...
37
        # Reset rate limit:
38
        if (time() - self.__cur_time) > self.time_unit:
39
            self.__cur_time = time()
40
            self.__pre_count = self.__cur_count
41
            self.__cur_count = 0
42
43
        # Calculate the estimated count
44
        est_cnt = (self.__pre_count * (
45
                self.time_unit - (time() - self.__cur_time)
0 ignored issues
show
Coding Style introduced by
Wrong hanging indentation (remove 4 spaces).
Loading history...
46
        ) / self.time_unit) + self.__cur_count
47
48
        # Request has passed the capacity
49
        if est_cnt > self.capacity:
50
            return False
51
52
        self.__cur_count += 1
53
        return True
54