use std::sync::OnceLock;
#[derive(Debug, Clone)]
pub struct StreamConfig {
pub channel_buffer_size: usize,
pub string_capacity: usize,
pub adaptive_buffering: bool,
pub min_buffer_size: usize,
pub max_buffer_size: usize,
}
impl Default for StreamConfig {
fn default() -> Self {
Self {
channel_buffer_size: 100, string_capacity: 4096, adaptive_buffering: false, min_buffer_size: 50,
max_buffer_size: 500,
}
}
}
impl StreamConfig {
pub fn performance() -> Self {
Self {
channel_buffer_size: 200,
string_capacity: 8192,
adaptive_buffering: true,
min_buffer_size: 100,
max_buffer_size: 1000,
}
}
pub fn memory_optimized() -> Self {
Self {
channel_buffer_size: 50,
string_capacity: 2048,
adaptive_buffering: false,
min_buffer_size: 25,
max_buffer_size: 100,
}
}
pub fn builder() -> StreamConfigBuilder {
StreamConfigBuilder::new()
}
}
static STREAM_CONFIG: OnceLock<StreamConfig> = OnceLock::new();
pub fn get_stream_config() -> &'static StreamConfig {
STREAM_CONFIG.get_or_init(StreamConfig::default)
}
pub fn set_stream_config(config: StreamConfig) -> Result<(), StreamConfig> {
STREAM_CONFIG.set(config)
}
pub struct StreamConfigBuilder {
config: StreamConfig,
}
impl StreamConfigBuilder {
pub fn new() -> Self {
Self {
config: StreamConfig::default(),
}
}
pub fn channel_buffer_size(mut self, size: usize) -> Self {
self.config.channel_buffer_size = size;
self
}
pub fn string_capacity(mut self, capacity: usize) -> Self {
self.config.string_capacity = capacity;
self
}
pub fn adaptive_buffering(mut self, enabled: bool) -> Self {
self.config.adaptive_buffering = enabled;
self
}
pub fn buffer_size_range(mut self, min: usize, max: usize) -> Self {
self.config.min_buffer_size = min;
self.config.max_buffer_size = max;
self
}
pub fn build(self) -> StreamConfig {
self.config
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_default_config() {
let config = StreamConfig::default();
assert_eq!(config.channel_buffer_size, 100);
assert_eq!(config.string_capacity, 4096);
assert!(!config.adaptive_buffering);
}
#[test]
fn test_performance_config() {
let config = StreamConfig::performance();
assert_eq!(config.channel_buffer_size, 200);
assert_eq!(config.string_capacity, 8192);
assert!(config.adaptive_buffering);
}
#[test]
fn test_builder() {
let config = StreamConfigBuilder::new()
.channel_buffer_size(150)
.string_capacity(6144)
.adaptive_buffering(true)
.buffer_size_range(75, 750)
.build();
assert_eq!(config.channel_buffer_size, 150);
assert_eq!(config.string_capacity, 6144);
assert!(config.adaptive_buffering);
assert_eq!(config.min_buffer_size, 75);
assert_eq!(config.max_buffer_size, 750);
}
}