tuwunel_core/utils/mod.rs
1//! Reusable helpers and extension traits for core services.
2//!
3//! The module groups compile-time assertions, closure-producing macros, and
4//! common utilities shared across workspace crates. Frequently used helpers are
5//! re-exported through a single import path.
6
7pub mod arrayvec;
8pub mod bool;
9pub mod budget;
10pub mod bytes;
11pub mod content_disposition;
12pub mod debug;
13pub mod defer;
14pub mod future;
15pub mod hash;
16pub mod html;
17pub mod json;
18pub mod math;
19pub mod mutex;
20pub mod mutex_map;
21pub mod option;
22pub mod rand;
23pub mod result;
24pub mod secret;
25pub mod set;
26pub mod stream;
27pub mod string;
28pub mod sys;
29#[cfg(test)]
30mod tests;
31pub mod time;
32pub mod two_phase_counter;
33pub mod unhandled;
34pub mod url;
35
36pub use ::ctor::ctor;
37pub use ::dtor::dtor;
38pub use ::tuwunel_macros::{async_noinline, implement};
39
40pub use self::{
41 arrayvec::ArrayVecExt,
42 bool::BoolExt,
43 budget::budget,
44 bytes::{increment, u64_from_bytes, u64_from_u8},
45 debug::slice_truncated as debug_slice_truncated,
46 future::{BoolExt as FutureBoolExt, OptionStream, TryExtExt as TryFutureExtExt},
47 hash::sha256::delimited as calculate_hash,
48 json::{deserialize_from_str, deserialize_lenient_bool, serialized_len, to_canonical_object},
49 mutex::MutexExt,
50 mutex_map::{Guard as MutexMapGuard, MutexMap},
51 option::OptionExt,
52 rand::{shuffle, string as random_string, string_from as random_string_from},
53 secret::{Secret, is_set as is_secret_set, resolve as resolve_secret},
54 stream::{IterStream, ReadyExt, Tools as StreamTools, TryReadyExt},
55 string::{str_from_bytes, string_from_bytes},
56 sys::compute::available_parallelism,
57 time::{
58 deadline_has_passed,
59 exponential_backoff::{
60 continue_exponential_backoff, continue_exponential_backoff_secs,
61 exponential_backoff_remaining, exponential_backoff_remaining_secs,
62 exponential_backoff_streak_cap,
63 },
64 now_millis as millis_since_unix_epoch, timepoint_ago, timepoint_from_now,
65 timepoint_has_passed,
66 },
67 url::SanitizedUri,
68};
69
70/// Asserts at compile time that `T` implements `Send`.
71///
72/// The generic bound supplies the assertion, and the function performs no
73/// runtime work.
74pub const fn assert_send<T: Send>() {}
75
76/// Asserts at compile time that `T` implements `Sync`.
77///
78/// The generic bound supplies the assertion, and the function performs no
79/// runtime work.
80pub const fn assert_sync<T: Sync>() {}
81
82/// Accepts any type, including an unsized type, without performing work.
83///
84/// The `?Sized` bound removes the implicit `Sized` requirement. The const
85/// signature permits use from const contexts.
86pub const fn assert_dst<T: ?Sized>() {}
87
88/// Asserts at compile time that `T` implements `Sized`.
89///
90/// The generic bound supplies the assertion, and the function performs no
91/// runtime work.
92pub const fn assert_sized<T: Sized>() {}
93
94/// Asserts at compile time that `T` implements `Unpin`.
95///
96/// The generic bound supplies the assertion, and the function performs no
97/// runtime work.
98pub const fn assert_unpin<T: Unpin>() {}
99
100/// Asserts at compile time that `T` implements `UnwindSafe`.
101///
102/// The generic bound supplies the assertion, and the function performs no
103/// runtime work.
104pub const fn assert_unwind_safe<T: std::panic::UnwindSafe>() {}
105
106/// Asserts at compile time that `T` implements `RefUnwindSafe`.
107///
108/// The generic bound supplies the assertion, and the function performs no
109/// runtime work.
110pub const fn assert_ref_unwind_safe<T: std::panic::RefUnwindSafe>() {}
111
112/// Extracts the payload from any listed tuple variant into an `Option`.
113///
114/// The expression is matched once, and a listed variant returns
115/// `Some(payload)`. Every other variant returns `None`.
116#[macro_export]
117macro_rules! extract_variant {
118 ( $e:expr_2021, $( $variant:path )|* ) => {
119 match $e {
120 $( $variant(value) => Some(value), )*
121 _ => None,
122 }
123 };
124}
125
126/// Extracts a pattern-bound value into an `Option`.
127///
128/// The expression is matched once against the supplied pattern. A match returns
129/// the named binding in `Some`, while every other value returns `None`.
130#[macro_export]
131macro_rules! extract {
132 ($e:expr_2021, $out:ident in $variant:pat) => {
133 match $e {
134 | $variant => Some($out),
135 | _ => None,
136 }
137 };
138}
139
140/// Creates a closure that reports whether its input is nonempty.
141///
142/// The generated closure delegates to `is_empty` and negates the result.
143#[macro_export]
144macro_rules! is_not_empty {
145 () => {
146 |x| !x.is_empty()
147 };
148}
149
150/// Creates a closure that applies one callable to every field of a tuple.
151///
152/// Tuple arities from one through five are supported. The callable tokens are
153/// expanded once for each field and therefore may be evaluated more than once.
154#[macro_export]
155macro_rules! apply {
156 (1, $($idx:tt)+) => {
157 |t| (($($idx)+)(t.0),)
158 };
159
160 (2, $($idx:tt)+) => {
161 |t| (($($idx)+)(t.0), ($($idx)+)(t.1),)
162 };
163
164 (3, $($idx:tt)+) => {
165 |t| (($($idx)+)(t.0), ($($idx)+)(t.1), ($($idx)+)(t.2),)
166 };
167
168 (4, $($idx:tt)+) => {
169 |t| (($($idx)+)(t.0), ($($idx)+)(t.1), ($($idx)+)(t.2), ($($idx)+)(t.3),)
170 };
171
172 (5, $($idx:tt)+) => {
173 |t| (($($idx)+)(t.0), ($($idx)+)(t.1), ($($idx)+)(t.2), ($($idx)+)(t.3), ($($idx)+)(t.4),)
174 };
175}
176
177/// Expands a type or expression into a two-element tuple with identical
178/// entries.
179///
180/// The type form produces `(T, T)`. The expression form evaluates the supplied
181/// expression separately for each tuple element.
182#[macro_export]
183macro_rules! pair_of {
184 ($decl:ty) => {
185 ($decl, $decl)
186 };
187
188 ($init:expr_2021) => {
189 ($init, $init)
190 };
191}
192
193/// Creates a Boolean identity closure.
194///
195/// The generated closure applies logical negation twice, making it usable where
196/// a predicate function is required.
197#[macro_export]
198macro_rules! is_true {
199 () => {
200 |x| !!x
201 };
202}
203
204/// Creates a closure that negates a Boolean input.
205///
206/// The generated closure returns `!x` and can be passed directly to predicate
207/// combinators.
208#[macro_export]
209macro_rules! is_false {
210 () => {
211 |x| !x
212 };
213}
214
215/// Creates a closure that reports whether its input differs from zero.
216///
217/// The generated closure compares each input with the integer literal `0`.
218#[macro_export]
219macro_rules! is_nonzero {
220 () => {
221 |x| x != 0
222 };
223}
224
225/// Creates a closure that reports whether its input matches zero.
226///
227/// The generated closure uses a literal pattern through `is_matching!`.
228#[macro_export]
229macro_rules! is_zero {
230 () => {
231 $crate::is_matching!(0)
232 };
233}
234
235/// Creates a closure that compares each input with a supplied value for
236/// equality.
237///
238/// The comparison target remains inside the closure body and is evaluated on
239/// every call.
240#[macro_export]
241macro_rules! is_equal_to {
242 ($val:ident) => {
243 |x| x == $val
244 };
245
246 ($val:expr_2021) => {
247 |x| x == $val
248 };
249}
250
251/// Creates a closure that compares each input with a supplied value for
252/// inequality.
253///
254/// The comparison target remains inside the closure body and is evaluated on
255/// every call.
256#[macro_export]
257macro_rules! is_not_equal_to {
258 ($val:ident) => {
259 |x| x != $val
260 };
261
262 ($val:expr_2021) => {
263 |x| x != $val
264 };
265}
266
267/// Creates a closure that reports whether each input is less than a supplied
268/// value.
269///
270/// The comparison target remains inside the closure body and is evaluated on
271/// every call.
272#[macro_export]
273macro_rules! is_less_than {
274 ($val:ident) => {
275 |x| x < $val
276 };
277
278 ($val:expr_2021) => {
279 |x| x < $val
280 };
281}
282
283/// Creates a closure that tests its input with a `matches!` pattern.
284///
285/// The supplied tokens can contain any pattern form accepted by `matches!`. The
286/// closure returns false when the input does not match.
287#[macro_export]
288macro_rules! is_matching {
289 ($val:ident) => {
290 |x| matches!(x, $val)
291 };
292
293 ($($val:tt)+) => {
294 |x| matches!(x, $($val)+)
295 };
296}
297
298/// Creates a two-argument closure that compares its inputs for equality.
299///
300/// The generated closure returns the result of `a == b`.
301#[macro_export]
302macro_rules! is_equal {
303 () => {
304 |a, b| a == b
305 };
306}
307
308/// Creates a closure that dereferences an indexed tuple field.
309///
310/// The tuple argument is received by value, and the selected field is returned
311/// through unary dereference.
312#[macro_export]
313macro_rules! deref_at {
314 ($idx:tt) => {
315 |t| *t.$idx
316 };
317}
318
319/// Creates a closure that borrows an indexed tuple field.
320///
321/// The generated `ref` pattern borrows the tuple argument before returning a
322/// reference to the selected field.
323#[macro_export]
324macro_rules! ref_at {
325 ($idx:tt) => {
326 |ref t| &t.$idx
327 };
328}
329
330/// Creates a closure that returns an indexed field from a referenced tuple by
331/// value.
332///
333/// The generated pattern destructures the shared reference before selecting the
334/// field. Moving the tuple from that reference therefore requires a copyable
335/// value.
336#[macro_export]
337macro_rules! val_at {
338 ($idx:tt) => {
339 |&t| t.$idx
340 };
341}
342
343/// Creates a closure that selects an indexed tuple field by value.
344///
345/// The generated closure consumes its tuple argument and returns the selected
346/// field.
347#[macro_export]
348macro_rules! at {
349 ($idx:tt) => {
350 |t| t.$idx
351 };
352}