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/// Returns the live default concurrency width for stream operations.
32///
33/// Startup tuning selects a value for the host, and later updates take effect
34/// immediately. Operations with an explicit width bypass this default.
35#[inline]
36pub fn automatic_width() -> usize {
37	let width = WIDTH.load(Ordering::Relaxed);
38	debug_assert!(width >= WIDTH_LIMIT.0, "WIDTH should not be zero");
39	debug_assert!(width <= WIDTH_LIMIT.1, "WIDTH is probably too large");
40	width
41}
42
43/// Used by stream operations where the amplification hasn't been manually
44/// supplied by the caller. Instead we provide a computed value.
45#[inline]
46pub fn automatic_amplification() -> usize {
47	let amplification = AMPLIFICATION.load(Ordering::Relaxed);
48	debug_assert!(amplification >= AMPLIFICATION_LIMIT.0, "amplification is too low");
49	debug_assert!(amplification <= AMPLIFICATION_LIMIT.1, "amplification is too high");
50	amplification
51}