scirs2-core 0.1.0-alpha.3

Core utilities and common functionality for SciRS2
Documentation
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
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//! Configuration system for SciRS2
//!
//! This module provides a centralized configuration system for SciRS2, allowing
//! users to customize the behavior of various algorithms and functions.

use once_cell::sync::Lazy;
use std::collections::HashMap;
use std::env;
use std::fmt;
use std::sync::{Arc, Mutex, RwLock};

use crate::error::{CoreError, CoreResult, ErrorContext, ErrorLocation};

/// Default precision for floating-point comparisons
pub const DEFAULT_FLOAT_EPS: f64 = 1e-10;

/// Default number of threads to use for parallel operations
pub const DEFAULT_NUM_THREADS: usize = 4;

/// Default maximum iterations for iterative algorithms
pub const DEFAULT_MAX_ITERATIONS: usize = 1000;

/// Default memory limit for operations (in bytes)
pub const DEFAULT_MEMORY_LIMIT: usize = 1_073_741_824; // 1 GB

/// Global configuration for SciRS2
///
/// This struct is not intended to be instantiated directly.
/// Instead, use the `get_config` and `set_config` functions to access and modify the configuration.
#[derive(Debug, Clone)]
pub struct Config {
    /// Configuration values
    values: HashMap<String, ConfigValue>,
    /// Environment prefix for SciRS2 environment variables
    env_prefix: String,
}

/// Configuration value types
#[derive(Debug, Clone)]
pub enum ConfigValue {
    /// Boolean value
    Bool(bool),
    /// Integer value
    Int(i64),
    /// Unsigned integer value
    UInt(u64),
    /// Floating-point value
    Float(f64),
    /// String value
    String(String),
}

impl fmt::Display for ConfigValue {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            ConfigValue::Bool(b) => write!(f, "{}", b),
            ConfigValue::Int(i) => write!(f, "{}", i),
            ConfigValue::UInt(u) => write!(f, "{}", u),
            ConfigValue::Float(fl) => write!(f, "{}", fl),
            ConfigValue::String(s) => write!(f, "{}", s),
        }
    }
}

impl Default for Config {
    fn default() -> Self {
        let mut config = Self {
            values: HashMap::new(),
            env_prefix: "SCIRS_".to_string(),
        };

        // Set default values
        config.set_default("float_eps", ConfigValue::Float(DEFAULT_FLOAT_EPS));
        config.set_default("num_threads", ConfigValue::UInt(DEFAULT_NUM_THREADS as u64));
        config.set_default(
            "max_iterations",
            ConfigValue::UInt(DEFAULT_MAX_ITERATIONS as u64),
        );
        config.set_default(
            "memory_limit",
            ConfigValue::UInt(DEFAULT_MEMORY_LIMIT as u64),
        );
        config.set_default("parallel_enabled", ConfigValue::Bool(true));
        config.set_default("debug_mode", ConfigValue::Bool(false));
        config.set_default("suppress_warnings", ConfigValue::Bool(false));

        // Load values from environment variables
        config.load_from_env();

        config
    }
}

impl Config {
    /// Create a new configuration with default values
    pub fn new() -> Self {
        Self::default()
    }

    /// Get a configuration value
    pub fn get(&self, key: &str) -> Option<&ConfigValue> {
        self.values.get(key)
    }

    /// Set a configuration value
    pub fn set(&mut self, key: &str, value: ConfigValue) {
        self.values.insert(key.to_string(), value);
    }

    /// Set a default configuration value (only if the key doesn't exist)
    fn set_default(&mut self, key: &str, value: ConfigValue) {
        self.values.entry(key.to_string()).or_insert(value);
    }

    /// Get a boolean configuration value
    pub fn get_bool(&self, key: &str) -> CoreResult<bool> {
        match self.get(key) {
            Some(ConfigValue::Bool(b)) => Ok(*b),
            Some(value) => Err(CoreError::ConfigError(
                ErrorContext::new(format!(
                    "Expected boolean value for key '{}', got: {}",
                    key, value
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            )),
            None => Err(CoreError::ConfigError(
                ErrorContext::new(format!("Configuration key '{}' not found", key))
                    .with_location(ErrorLocation::new(file!(), line!())),
            )),
        }
    }

    /// Get an integer configuration value
    pub fn get_int(&self, key: &str) -> CoreResult<i64> {
        match self.get(key) {
            Some(ConfigValue::Int(i)) => Ok(*i),
            Some(ConfigValue::UInt(u)) if *u <= i64::MAX as u64 => Ok(*u as i64),
            Some(value) => Err(CoreError::ConfigError(
                ErrorContext::new(format!(
                    "Expected integer value for key '{}', got: {}",
                    key, value
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            )),
            None => Err(CoreError::ConfigError(
                ErrorContext::new(format!("Configuration key '{}' not found", key))
                    .with_location(ErrorLocation::new(file!(), line!())),
            )),
        }
    }

    /// Get an unsigned integer configuration value
    pub fn get_uint(&self, key: &str) -> CoreResult<u64> {
        match self.get(key) {
            Some(ConfigValue::UInt(u)) => Ok(*u),
            Some(ConfigValue::Int(i)) if *i >= 0 => Ok(*i as u64),
            Some(value) => Err(CoreError::ConfigError(
                ErrorContext::new(format!(
                    "Expected unsigned integer value for key '{}', got: {}",
                    key, value
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            )),
            None => Err(CoreError::ConfigError(
                ErrorContext::new(format!("Configuration key '{}' not found", key))
                    .with_location(ErrorLocation::new(file!(), line!())),
            )),
        }
    }

    /// Get a floating-point configuration value
    pub fn get_float(&self, key: &str) -> CoreResult<f64> {
        match self.get(key) {
            Some(ConfigValue::Float(f)) => Ok(*f),
            Some(ConfigValue::Int(i)) => Ok(*i as f64),
            Some(ConfigValue::UInt(u)) => Ok(*u as f64),
            Some(value) => Err(CoreError::ConfigError(
                ErrorContext::new(format!(
                    "Expected float value for key '{}', got: {}",
                    key, value
                ))
                .with_location(ErrorLocation::new(file!(), line!())),
            )),
            None => Err(CoreError::ConfigError(
                ErrorContext::new(format!("Configuration key '{}' not found", key))
                    .with_location(ErrorLocation::new(file!(), line!())),
            )),
        }
    }

    /// Get a string configuration value
    pub fn get_string(&self, key: &str) -> CoreResult<String> {
        match self.get(key) {
            Some(ConfigValue::String(s)) => Ok(s.clone()),
            Some(value) => Ok(value.to_string()),
            None => Err(CoreError::ConfigError(
                ErrorContext::new(format!("Configuration key '{}' not found", key))
                    .with_location(ErrorLocation::new(file!(), line!())),
            )),
        }
    }

    /// Load configuration values from environment variables
    fn load_from_env(&mut self) {
        // Find all environment variables with the configured prefix
        for (key, value) in env::vars() {
            if key.starts_with(&self.env_prefix) {
                let config_key = key[self.env_prefix.len()..].to_lowercase();

                // Try to parse the value as different types
                if let Ok(bool_val) = value.parse::<bool>() {
                    self.set(&config_key, ConfigValue::Bool(bool_val));
                } else if let Ok(int_val) = value.parse::<i64>() {
                    self.set(&config_key, ConfigValue::Int(int_val));
                } else if let Ok(uint_val) = value.parse::<u64>() {
                    self.set(&config_key, ConfigValue::UInt(uint_val));
                } else if let Ok(float_val) = value.parse::<f64>() {
                    self.set(&config_key, ConfigValue::Float(float_val));
                } else {
                    self.set(&config_key, ConfigValue::String(value));
                }
            }
        }
    }
}

static GLOBAL_CONFIG: Lazy<RwLock<Config>> = Lazy::new(|| RwLock::new(Config::default()));

thread_local! {
    static THREAD_LOCAL_CONFIG: Arc<Mutex<Option<Config>>> = Arc::new(Mutex::new(None));
}

/// Get the current configuration
///
/// This function first checks for a thread-local configuration, and falls back to the global configuration.
pub fn get_config() -> Config {
    // Try to get thread-local config first
    let thread_local = THREAD_LOCAL_CONFIG.with(|config| {
        let config_lock = config.lock().unwrap();
        config_lock.clone()
    });

    // If thread-local config exists, use it, otherwise use global config
    match thread_local {
        Some(config) => config,
        None => GLOBAL_CONFIG.read().unwrap().clone(),
    }
}

/// Set the global configuration
pub fn set_global_config(config: Config) {
    let mut global_config = GLOBAL_CONFIG.write().unwrap();
    *global_config = config;
}

/// Set a thread-local configuration
pub fn set_thread_local_config(config: Config) {
    THREAD_LOCAL_CONFIG.with(|thread_config| {
        let mut config_lock = thread_config.lock().unwrap();
        *config_lock = Some(config);
    });
}

/// Clear the thread-local configuration
pub fn clear_thread_local_config() {
    THREAD_LOCAL_CONFIG.with(|thread_config| {
        let mut config_lock = thread_config.lock().unwrap();
        *config_lock = None;
    });
}

/// Set a global configuration value
pub fn set_config_value(key: &str, value: ConfigValue) {
    let mut global_config = GLOBAL_CONFIG.write().unwrap();
    global_config.set(key, value);
}

/// Get a global configuration value
pub fn get_config_value(key: &str) -> Option<ConfigValue> {
    let config = get_config();
    config.get(key).cloned()
}

/// Set a thread-local configuration value
pub fn set_thread_local_config_value(key: &str, value: ConfigValue) {
    THREAD_LOCAL_CONFIG.with(|thread_config| {
        let mut config_lock = thread_config.lock().unwrap();

        // Create a new config from global if it doesn't exist
        if config_lock.is_none() {
            let global_config = GLOBAL_CONFIG.read().unwrap().clone();
            *config_lock = Some(global_config);
        }

        // Now set the value
        if let Some(config) = config_lock.as_mut() {
            config.set(key, value);
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_default_config() {
        let config = Config::default();

        assert!(matches!(
            config.get("float_eps"),
            Some(ConfigValue::Float(_))
        ));
        assert!(matches!(
            config.get("num_threads"),
            Some(ConfigValue::UInt(_))
        ));
        assert!(matches!(
            config.get("max_iterations"),
            Some(ConfigValue::UInt(_))
        ));
        assert!(matches!(
            config.get("memory_limit"),
            Some(ConfigValue::UInt(_))
        ));
    }

    #[test]
    fn test_config_get_methods() {
        let mut config = Config::default();

        config.set("test_bool", ConfigValue::Bool(true));
        config.set("test_int", ConfigValue::Int(42));
        config.set("test_uint", ConfigValue::UInt(100));
        config.set("test_float", ConfigValue::Float(3.5));
        config.set("test_string", ConfigValue::String("hello".to_string()));

        assert!(config.get_bool("test_bool").unwrap());
        assert_eq!(config.get_int("test_int").unwrap(), 42);
        assert_eq!(config.get_uint("test_uint").unwrap(), 100);
        assert_eq!(config.get_float("test_float").unwrap(), 3.5);
        assert_eq!(config.get_string("test_string").unwrap(), "hello");

        // Test type conversions
        assert_eq!(config.get_float("test_int").unwrap(), 42.0);
        assert_eq!(config.get_int("test_uint").unwrap(), 100);

        // Test error cases
        assert!(config.get_bool("nonexistent").is_err());
        assert!(config.get_bool("test_int").is_err());
    }

    #[test]
    fn test_global_config() {
        let original = get_config();
        let mut new_config = Config::default();
        new_config.set("test_value", ConfigValue::String("global".to_string()));

        set_global_config(new_config);

        let config = get_config();
        assert_eq!(config.get_string("test_value").unwrap(), "global");

        // Restore original config
        set_global_config(original);

        // Clean up by removing the test key
        let mut final_config = GLOBAL_CONFIG.write().unwrap();
        final_config.values.remove("test_value");
    }

    #[test]
    fn test_thread_local_config() {
        let test_key = "test_thread_key";
        let original = get_config();

        {
            // First set a global value
            let mut global_config = GLOBAL_CONFIG.write().unwrap();
            global_config.set(test_key, ConfigValue::String("global".to_string()));
        }

        // Set a thread-local value
        let mut thread_config = Config::default();
        thread_config.set(test_key, ConfigValue::String("thread-local".to_string()));
        set_thread_local_config(thread_config);

        // Thread-local should take precedence
        let config = get_config();
        assert_eq!(config.get_string(test_key).unwrap(), "thread-local");

        // Clear thread-local config
        clear_thread_local_config();

        // Need to verify thread-local is gone
        let thread_result = THREAD_LOCAL_CONFIG.with(|config| {
            let locked = config.lock().unwrap();
            locked.is_none()
        });
        assert!(thread_result, "Thread-local config should be cleared");

        // Restore original config
        set_global_config(original);

        // Clean up by removing the test key
        let mut final_config = GLOBAL_CONFIG.write().unwrap();
        final_config.values.remove(test_key);
    }
}