Skip to main content

tuwunel_core/utils/stream/
band.rs

1use std::sync::atomic::{AtomicUsize, Ordering};
2
3/// Stream concurrency factor; this is a live value.
4static WIDTH: AtomicUsize = AtomicUsize::new(32);
5
6/// Stream throughput amplifier; this is a live value.
7static AMPLIFICATION: AtomicUsize = AtomicUsize::new(1024);
8
9/// Practicable limits on the stream width.
10pub const WIDTH_LIMIT: (usize, usize) = (1, 1024);
11
12/// Practicable limits on the stream amplifier.
13pub const AMPLIFICATION_LIMIT: (usize, usize) = (32, 32768);
14
15/// Sets the live concurrency factor. The first return value is the previous
16/// width which was replaced. The second return value is the value which was set
17/// after any applied limits.
18pub fn set_width(width: usize) -> (usize, usize) {
19	let width = width.clamp(WIDTH_LIMIT.0, WIDTH_LIMIT.1);
20	(WIDTH.swap(width, Ordering::Relaxed), width)
21}
22
23/// Sets the live concurrency amplification. The first return value is the
24/// previous width which was replaced. The second return value is the value
25/// which was set after any applied limits.
26pub fn set_amplification(width: usize) -> (usize, usize) {
27	let width = width.clamp(AMPLIFICATION_LIMIT.0, AMPLIFICATION_LIMIT.1);
28	(AMPLIFICATION.swap(width, Ordering::Relaxed), width)
29}
30
31/// Used by stream operations where the concurrency factor hasn't been manually
32/// supplied by the caller (most uses). Instead we provide a default value which
33/// is adjusted at startup for the specific system and also dynamically.
34#[inline]
35pub fn automatic_width() -> usize {
36	let width = WIDTH.load(Ordering::Relaxed);
37	debug_assert!(width >= WIDTH_LIMIT.0, "WIDTH should not be zero");
38	debug_assert!(width <= WIDTH_LIMIT.1, "WIDTH is probably too large");
39	width
40}
41
42/// Used by stream operations where the amplification hasn't been manually
43/// supplied by the caller. Instead we provide a computed value.
44#[inline]
45pub fn automatic_amplification() -> usize {
46	let amplification = AMPLIFICATION.load(Ordering::Relaxed);
47	debug_assert!(amplification >= AMPLIFICATION_LIMIT.0, "amplification is too low");
48	debug_assert!(amplification <= AMPLIFICATION_LIMIT.1, "amplification is too high");
49	amplification
50}