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
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
//! # `rate-guard-core`
//! A comprehensive rate limiting library for Rust applications with multiple thread-safe algorithms.
//!
//! ## Features
//! - **4 Rate Limiting Algorithms**: Token Bucket, Fixed Window Counter, Sliding Window Counter, and Approximate Sliding Window
//! - **Thread-Safe**: All algorithms use non-blocking locks
//! - **Zero Dependencies**: Lightweight with no external dependencies
//! - **Flexible Time**: Works with any time unit via abstract "ticks"
//! - **Configurable Tick Precision**: Compile-time feature flags allow choosing `u64` (default) or `u128` for tick units
//! - **Rust 1.60+**: Compatible with older Rust versions
//!
//! ---
//!
//! ## Quick Start
//!
//! ### from crate.io
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! rate-guard-core = { version = "0.7.2" }
//! ```
//!
//! ### from Github
//! Add to your `Cargo.toml`:
//! ```toml
//! [dependencies]
//! rate-guard-core = { git = "https://github.com/Kuanlin/rate-guard-core", tag = "v0.7.2" }
//! ```
//!
//! ---
//!
//! ## Tick Precision (u64 / u128)
//! By default, the crate uses `u64` as the tick unit, allowing up to ~584 years of nanosecond-resolution time.
//! If your application needs ultra-long durations or ultra-high precision, you can enable `u128` support via feature flags:
//!
//! ### from crate.io
//! ```toml
//! [dependencies]
//! rate-guard-core = { version = "0.7.2", default-features = false, features = ["tick-u128"] }
//! ```
//!
//! ### from Github
//! ```toml
//! [dependencies]
//! rate-guard-core = { git = "https://github.com/Kuanlin/rate-guard-core", tag = "v0.7.2", default-features = false, features = ["tick-u128"] }
//! ```
//!
//! ---
//!
//! ## Usage Examples
//!
//! ### Token Bucket
//! Perfect for APIs that allow occasional bursts while maintaining average rate:
//!
//! ```rust
//! use rate_guard_core::cores::{TokenBucketCore, TokenBucketCoreConfig};
//!
//! let config = TokenBucketCoreConfig {
//! capacity: 100,
//! refill_interval: 5,
//! refill_amount: 10,
//! };
//!
//! let limiter: TokenBucketCore = config.into();
//!
//! ```
//!
//! ---
//!
//! ### Fixed Window Counter
//!
//! ```rust
//! use rate_guard_core::cores::{FixedWindowCounterCore, FixedWindowCounterCoreConfig};
//!
//! let config = FixedWindowCounterCoreConfig {
//! capacity: 100,
//! window_size: 60,
//! };
//!
//! let limiter: FixedWindowCounterCore = config.into();
//! ```
//!
//! ---
//!
//! ### Sliding Window Counter
//!
//! ```rust
//! use rate_guard_core::cores::{SlidingWindowCounterCore, SlidingWindowCounterCoreConfig};
//!
//! let config = SlidingWindowCounterCoreConfig {
//! capacity: 100,
//! bucket_ticks: 10,
//! bucket_count: 6,
//! };
//!
//! let limiter: SlidingWindowCounterCore = config.into();
//! ```
//!
//! ---
//!
//! ### Approximate Sliding Window
//! A memory-optimized version of sliding window counter.
//! Formula:
//! `Used = (1 - X%) * lastWindow + currentWindow` where X is the proportion of request time within the current window.
//!
//! ```rust
//! use rate_guard_core::cores::{ApproximateSlidingWindowCore, ApproximateSlidingWindowCoreConfig};
//!
//! let config = ApproximateSlidingWindowCoreConfig {
//! capacity: 100,
//! window_ticks: 60,
//! };
//!
//! let limiter: ApproximateSlidingWindowCore = config.into();
//! ```
//!
//! > Both `into()` and `from()` are functionally equivalent in Rust.
//! > `into()` is shorter and idiomatic; `from()` is more explicit and beginner-friendly.
//! > These examples are duplicated to help both Rust newcomers and non-Rust readers understand the conversion logic.
//!
//!
//! ---
//!
//! ## Error Handling
//! All limiters' try_acquire_at returns `SimpleRateLimitResult`:
//! ```Rust
//! use rate_guard_core::{SimpleRateLimitError, SimpleRateLimitResult};
//! match limiter.try_acquire_at(tick, 1) {
//! Ok(()) => {
//! // Request allowed
//! },
//! Err(SimpleRateLimitError::InsufficientCapacity) => {
//! // Rate limit exceeded
//! },
//! Err(SimpleRateLimitError::BeyondCapacity) => {
//! // Acquiring too much
//! },
//! Err(SimpleRateLimitError::ExpiredTick) => {
//! // Time went backwards
//! },
//! Err(SimpleRateLimitError::ContentionFailure) => {
//! // Lock contention, you can do sleep and retry here.
//! },
//! }
//! ```
//!
//! ---
//!
//! ## Verbose Error Reporting
//!
//! Each limiter also supports `try_acquire_verbose_at(tick, tokens)`, which returns a `VerboseRateLimitError` with richer diagnostics:
//!
//! - `ContentionFailure`: Lock was unavailable
//! - `ExpiredTick { min_acceptable_tick }`: Time went backwards
//! - `BeyondCapacity { acquiring, capacity }`: Requested tokens exceed max
//! - `InsufficientCapacity { acquiring, available, retry_after_ticks }`: Not enough tokens now, but suggests how long to wait before retrying
//!
//! ```Rust
//! use rate_guard_core::{VerboseRateLimitError, VerboseRateLimitResult};
//!
//! match limiter.try_acquire_verbose_at(tick, 5) {
//! Ok(()) => {
//! // Request allowed
//! }
//! Err(VerboseRateLimitError::InsufficientCapacity { retry_after_ticks, .. }) => {
//! println!("Retry after {} ticks", retry_after_ticks);
//! }
//! Err(e) => {
//! println!("Rate limit error: {:?}", e);
//! }
//! }
//! ```
//!
//! > `try_acquire_verbose_at` is useful for retry logic, logging, or adaptive throttling.
//!
//! ---
//!
//! ## Time Management
//! The library uses abstract "ticks" for time. You can map any time source:
//! ```Rust
//! // Seconds
//! let tick = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_secs();
//! // Milliseconds
//! let tick = SystemTime::now().duration_since(UNIX_EPOCH).unwrap().as_millis() as u64;
//! // Custom time
//! let tick = my_monotonic_timer.elapsed_ticks();
//! ```
//!
//! ---
//!
//! ## Thread Safety
//! ```Rust
//! use std::sync::Arc;
//! use std::thread;
//! use rate_guard_core::cores::TokenBucketCore;
//! let limiter = Arc::new(TokenBucketCore::new(100, 1, 10));
//! for _ in 0..10 {
//! let limiter = limiter.clone();
//! thread::spawn(move || {
//! match limiter.try_acquire_at(get_current_tick(), 1) {
//! Ok(()) => println!("Request processed"),
//! Err(e) => println!("Rate limited: {}", e),
//! }
//! });
//! }
//! ```
//!
//! ---
//!
//! ## License
//! Licensed under either of Apache License, Version 2.0 or MIT license at your option.
//!
//! ---
//!
//! ## Contributing
//! Contributions are welcome! Please feel free to submit a Pull Request.
pub use Uint;
pub use ;