Skip to main content

torsh_data/
utils.rs

1//! Common utilities to reduce code duplication across modules
2
3use torsh_core::error::{Result, TorshError};
4
5/// Utility macros for common patterns
6///
7/// This module provides macros and functions to eliminate repetitive code
8/// patterns found throughout the torsh-data crate.
9/// Validate probability value is in [0, 1] range
10pub fn validate_probability(prob: f32, name: &str) -> Result<()> {
11    if !(0.0..=1.0).contains(&prob) {
12        return Err(TorshError::InvalidArgument(format!(
13            "{name} must be between 0 and 1, got {prob}"
14        )));
15    }
16    Ok(())
17}
18
19/// Validate that a range is valid (min <= max)
20pub fn validate_range<T: PartialOrd + std::fmt::Debug>(range: (T, T), name: &str) -> Result<()> {
21    if range.0 > range.1 {
22        return Err(TorshError::InvalidArgument(format!(
23            "Invalid {name} range: {range:?}"
24        )));
25    }
26    Ok(())
27}
28
29/// Validate that a value is positive
30pub fn validate_positive<T: PartialOrd + Default + std::fmt::Debug>(
31    value: T,
32    name: &str,
33) -> Result<()> {
34    if value <= T::default() {
35        return Err(TorshError::InvalidArgument(format!(
36            "{name} must be positive, got {value:?}"
37        )));
38    }
39    Ok(())
40}
41
42/// Validate that vectors have the same length
43pub fn validate_same_length<T, U>(vec1: &[T], vec2: &[U], name1: &str, name2: &str) -> Result<()> {
44    if vec1.len() != vec2.len() {
45        return Err(TorshError::InvalidArgument(format!(
46            "{} and {} must have the same length, got {} and {}",
47            name1,
48            name2,
49            vec1.len(),
50            vec2.len()
51        )));
52    }
53    Ok(())
54}
55
56/// Validate that a vector is not empty
57pub fn validate_not_empty<T>(vec: &[T], name: &str) -> Result<()> {
58    if vec.is_empty() {
59        return Err(TorshError::InvalidArgument(format!(
60            "{name} cannot be empty"
61        )));
62    }
63    Ok(())
64}
65
66/// Error utilities for common error patterns
67pub mod errors {
68    use torsh_core::error::TorshError;
69
70    /// Create an invalid index error
71    pub fn invalid_index(index: usize, size: usize) -> TorshError {
72        TorshError::IndexError { index, size }
73    }
74
75    /// Create an invalid argument error
76    pub fn invalid_argument(msg: impl Into<String>) -> TorshError {
77        TorshError::InvalidArgument(msg.into())
78    }
79
80    /// Create a configuration error
81    pub fn config_error(msg: impl Into<String>) -> TorshError {
82        TorshError::InvalidArgument(msg.into())
83    }
84
85    /// Create an empty batch error
86    pub fn empty_batch() -> TorshError {
87        TorshError::InvalidArgument("Cannot process empty batch".to_string())
88    }
89
90    /// Create a shape mismatch error
91    pub fn shape_mismatch(expected: &[usize], got: &[usize]) -> TorshError {
92        TorshError::ShapeMismatch {
93            expected: expected.to_vec(),
94            got: got.to_vec(),
95        }
96    }
97
98    /// Create a file not found error
99    pub fn file_not_found(path: &std::path::Path) -> TorshError {
100        TorshError::InvalidArgument(format!("File not found: {}", path.display()))
101    }
102
103    /// Create an invalid format error
104    pub fn invalid_format(expected: &str, got: &str) -> TorshError {
105        TorshError::InvalidArgument(format!("Expected {expected} format, got {got}"))
106    }
107}
108
109/// Macro to create a simple constructor with validation
110#[macro_export]
111macro_rules! validated_constructor {
112    // Constructor with single probability validation
113    ($name:ident, $field:ident: f32, probability) => {
114        impl $name {
115            /// Create a new instance
116            pub fn new($field: f32) -> Result<Self> {
117                $crate::utils::validate_probability($field, stringify!($field))?;
118                Ok(Self { $field })
119            }
120        }
121    };
122
123    // Constructor with range validation
124    ($name:ident, $field:ident: ($t1:ty, $t2:ty), range) => {
125        impl $name {
126            /// Create a new instance
127            pub fn new($field: ($t1, $t2)) -> Result<Self> {
128                $crate::utils::validate_range($field, stringify!($field))?;
129                Ok(Self { $field })
130            }
131        }
132    };
133
134    // Constructor with positive validation
135    ($name:ident, $field:ident: $t:ty, positive) => {
136        impl $name {
137            /// Create a new instance
138            pub fn new($field: $t) -> Result<Self> {
139                $crate::utils::validate_positive($field, stringify!($field))?;
140                Ok(Self { $field })
141            }
142        }
143    };
144
145    // Constructor with size tuple (for image operations)
146    ($name:ident, size: ($t1:ty, $t2:ty)) => {
147        impl $name {
148            /// Create a new instance
149            pub fn new(size: ($t1, $t2)) -> Self {
150                Self { size }
151            }
152        }
153    };
154
155    // Constructor with custom validation
156    ($name:ident, $($field:ident: $t:ty),+, validate = $validator:expr) => {
157        impl $name {
158            /// Create a new instance
159            pub fn new($($field: $t),+) -> Result<Self> {
160                $validator(&$($field),+)?;
161                Ok(Self { $($field),+ })
162            }
163        }
164    };
165}
166
167/// Macro to create builder patterns with fluent interface
168#[macro_export]
169macro_rules! builder_pattern {
170    ($name:ident, $($field:ident: $t:ty),+) => {
171        // Note: This macro would generate methods like with_field_name
172        // For now, users should implement builders manually for better control
173        // Example:
174        // impl MyStruct {
175        //     pub fn with_field(mut self, field: Type) -> Self {
176        //         self.field = field;
177        //         self
178        //     }
179        // }
180    };
181}
182
183/// Common transform implementation macro
184#[macro_export]
185macro_rules! simple_random_transform {
186    ($name:ident, $input:ty, $output:ty, $prob_field:ident, $transform_fn:expr) => {
187        impl $crate::transforms::Transform<$input> for $name {
188            type Output = $output;
189
190            fn transform(&self, input: $input) -> Result<Self::Output> {
191                // ✅ SciRS2 Policy Compliant - Using scirs2_core::random instead of direct rand
192                //
193                // NOTE: uses the thread-local entropy-seeded RNG rather than a
194                // fixed-literal `Random::seed(<n>)`, which would draw the
195                // identical value on every call and make the transform either
196                // always fire or never fire regardless of $prob_field (F007).
197                use scirs2_core::random::{thread_rng, Rng};
198                let mut rng = thread_rng();
199
200                if rng.random::<f32>() < self.$prob_field {
201                    $transform_fn(input, &mut rng)
202                } else {
203                    Ok(input)
204                }
205            }
206
207            fn is_deterministic(&self) -> bool {
208                false
209            }
210        }
211    };
212}
213
214/// Common dataset path validation
215pub fn validate_dataset_path(path: &std::path::Path, name: &str) -> Result<()> {
216    if !path.exists() {
217        return Err(TorshError::InvalidArgument(format!(
218            "{} path does not exist: {}",
219            name,
220            path.display()
221        )));
222    }
223    Ok(())
224}
225
226/// Common file extension validation
227pub fn validate_file_extension(path: &std::path::Path, extensions: &[&str]) -> Result<()> {
228    if let Some(ext) = path.extension() {
229        let ext_str = ext.to_string_lossy().to_lowercase();
230        if extensions.iter().any(|&e| e == ext_str) {
231            return Ok(());
232        }
233    }
234
235    Err(TorshError::InvalidArgument(format!(
236        "File must have one of these extensions: {:?}, got: {}",
237        extensions,
238        path.display()
239    )))
240}
241
242/// Common tensor shape validation
243pub fn validate_tensor_shape(shape: &[usize], expected_dims: usize, name: &str) -> Result<()> {
244    if shape.len() != expected_dims {
245        return Err(TorshError::InvalidArgument(format!(
246            "{} tensor must have {} dimensions, got {}",
247            name,
248            expected_dims,
249            shape.len()
250        )));
251    }
252    Ok(())
253}
254
255/// Helper for creating size tuples with validation
256pub fn create_size_tuple(width: usize, height: usize) -> Result<(usize, usize)> {
257    validate_positive(width, "width")?;
258    validate_positive(height, "height")?;
259    Ok((width, height))
260}
261
262/// Utility traits for common functionality
263pub trait Resettable {
264    /// Reset to initial state
265    fn reset(&mut self);
266}
267
268pub trait Configurable<T> {
269    /// Configure with settings
270    fn configure(&mut self, config: T) -> Result<()>;
271}
272
273pub trait Cacheable {
274    /// Clear any cached data
275    fn clear_cache(&mut self);
276
277    /// Get cache hit rate if applicable
278    fn cache_hit_rate(&self) -> Option<f32> {
279        None
280    }
281}
282
283/// Helper for progress tracking
284pub struct ProgressTracker {
285    current: usize,
286    total: usize,
287    last_reported: f32,
288    report_interval: f32,
289}
290
291impl ProgressTracker {
292    /// Create a new progress tracker
293    pub fn new(total: usize) -> Self {
294        Self {
295            current: 0,
296            total,
297            last_reported: 0.0,
298            report_interval: 0.1, // Report every 10%
299        }
300    }
301
302    /// Update progress and return true if should report
303    pub fn update(&mut self) -> bool {
304        self.current += 1;
305        let progress = self.current as f32 / self.total as f32;
306
307        if progress - self.last_reported >= self.report_interval {
308            self.last_reported = progress;
309            true
310        } else {
311            false
312        }
313    }
314
315    /// Get current progress as percentage
316    pub fn percentage(&self) -> f32 {
317        (self.current as f32 / self.total as f32) * 100.0
318    }
319
320    /// Check if completed
321    pub fn is_complete(&self) -> bool {
322        self.current >= self.total
323    }
324}
325
326/// Performance measurement utilities
327pub mod performance {
328    use std::collections::VecDeque;
329    use std::time::{Duration, Instant};
330
331    /// Simple performance timer
332    pub struct Timer {
333        start: Instant,
334        measurements: VecDeque<Duration>,
335        max_samples: usize,
336    }
337
338    impl Timer {
339        /// Create a new timer
340        pub fn new() -> Self {
341            Self {
342                start: Instant::now(),
343                measurements: VecDeque::new(),
344                max_samples: 100,
345            }
346        }
347
348        /// Start timing
349        pub fn start(&mut self) {
350            self.start = Instant::now();
351        }
352
353        /// Stop timing and record measurement
354        pub fn stop(&mut self) -> Duration {
355            let duration = self.start.elapsed();
356
357            if self.measurements.len() >= self.max_samples {
358                self.measurements.pop_front();
359            }
360            self.measurements.push_back(duration);
361
362            duration
363        }
364
365        /// Get average measurement
366        pub fn average(&self) -> Option<Duration> {
367            if self.measurements.is_empty() {
368                None
369            } else {
370                let total: Duration = self.measurements.iter().sum();
371                Some(total / self.measurements.len() as u32)
372            }
373        }
374
375        /// Get throughput in items per second
376        pub fn throughput(&self, items: usize) -> Option<f64> {
377            self.average().map(|avg| items as f64 / avg.as_secs_f64())
378        }
379    }
380
381    impl Default for Timer {
382        fn default() -> Self {
383            Self::new()
384        }
385    }
386}
387
388/// Memory management utilities
389pub mod memory {
390    use std::collections::HashMap;
391    use std::sync::{Arc, Mutex};
392
393    /// Simple memory pool for reusing allocations
394    pub struct MemoryPool<T> {
395        available: Vec<Vec<T>>,
396        capacity: usize,
397        default_size: usize,
398    }
399
400    impl<T: Clone + Default> MemoryPool<T> {
401        /// Create a new memory pool
402        pub fn new(capacity: usize, default_size: usize) -> Self {
403            Self {
404                available: Vec::with_capacity(capacity),
405                capacity,
406                default_size,
407            }
408        }
409
410        /// Get a buffer from the pool
411        pub fn get(&mut self) -> Vec<T> {
412            self.available
413                .pop()
414                .unwrap_or_else(|| Vec::with_capacity(self.default_size))
415        }
416
417        /// Return a buffer to the pool
418        pub fn put(&mut self, mut buffer: Vec<T>) {
419            if self.available.len() < self.capacity {
420                buffer.clear();
421                self.available.push(buffer);
422            }
423        }
424
425        /// Get current pool size
426        pub fn size(&self) -> usize {
427            self.available.len()
428        }
429    }
430
431    /// Thread-safe memory pool
432    pub type SharedMemoryPool<T> = Arc<Mutex<MemoryPool<T>>>;
433
434    /// Memory usage tracker
435    pub struct MemoryTracker {
436        allocations: HashMap<String, usize>,
437        peak_memory: usize,
438        current_memory: usize,
439    }
440
441    impl MemoryTracker {
442        /// Create a new memory tracker
443        pub fn new() -> Self {
444            Self {
445                allocations: HashMap::new(),
446                peak_memory: 0,
447                current_memory: 0,
448            }
449        }
450
451        /// Record an allocation
452        pub fn allocate(&mut self, name: &str, size: usize) {
453            self.current_memory += size;
454            self.peak_memory = self.peak_memory.max(self.current_memory);
455            *self.allocations.entry(name.to_string()).or_insert(0) += size;
456        }
457
458        /// Record a deallocation
459        pub fn deallocate(&mut self, name: &str, size: usize) {
460            self.current_memory = self.current_memory.saturating_sub(size);
461            if let Some(total) = self.allocations.get_mut(name) {
462                *total = total.saturating_sub(size);
463            }
464        }
465
466        /// Get current memory usage
467        pub fn current_usage(&self) -> usize {
468            self.current_memory
469        }
470
471        /// Get peak memory usage
472        pub fn peak_usage(&self) -> usize {
473            self.peak_memory
474        }
475
476        /// Get memory usage breakdown
477        pub fn breakdown(&self) -> &HashMap<String, usize> {
478            &self.allocations
479        }
480    }
481
482    impl Default for MemoryTracker {
483        fn default() -> Self {
484            Self::new()
485        }
486    }
487}
488
489/// Batch processing utilities
490pub mod batch {
491    // ✅ SciRS2 POLICY: Use scirs2_core::parallel_ops instead of rayon::prelude
492    use scirs2_core::parallel_ops::*;
493    use std::sync::mpsc;
494    use std::thread;
495
496    /// Process data in parallel batches
497    pub fn parallel_batch_process<T, R, F>(data: Vec<T>, batch_size: usize, processor: F) -> Vec<R>
498    where
499        T: Send + Sync,
500        R: Send,
501        F: Fn(&[T]) -> R + Send + Sync,
502    {
503        data.par_chunks(batch_size).map(processor).collect()
504    }
505
506    /// Async batch processor with channels
507    pub struct AsyncBatchProcessor<T, R> {
508        sender: mpsc::Sender<Vec<T>>,
509        receiver: mpsc::Receiver<R>,
510        _handle: thread::JoinHandle<()>,
511    }
512
513    impl<T, R> AsyncBatchProcessor<T, R>
514    where
515        T: Send + 'static,
516        R: Send + 'static,
517    {
518        /// Create a new async batch processor
519        pub fn new<F>(batch_size: usize, processor: F) -> Self
520        where
521            F: Fn(Vec<T>) -> R + Send + 'static,
522        {
523            let (input_sender, input_receiver) = mpsc::channel();
524            let (output_sender, output_receiver) = mpsc::channel();
525
526            let handle = thread::spawn(move || {
527                let mut buffer = Vec::with_capacity(batch_size);
528
529                while let Ok(mut data) = input_receiver.recv() {
530                    buffer.append(&mut data);
531
532                    while buffer.len() >= batch_size {
533                        let batch = buffer.drain(..batch_size).collect();
534                        let result = processor(batch);
535                        if output_sender.send(result).is_err() {
536                            break;
537                        }
538                    }
539                }
540
541                // Process remaining data
542                if !buffer.is_empty() {
543                    let result = processor(buffer);
544                    let _ = output_sender.send(result);
545                }
546            });
547
548            Self {
549                sender: input_sender,
550                receiver: output_receiver,
551                _handle: handle,
552            }
553        }
554
555        /// Send data for processing
556        pub fn send(&self, data: Vec<T>) -> Result<(), mpsc::SendError<Vec<T>>> {
557            self.sender.send(data)
558        }
559
560        /// Receive processed results
561        pub fn recv(&self) -> Result<R, mpsc::RecvError> {
562            self.receiver.recv()
563        }
564
565        /// Try to receive without blocking
566        pub fn try_recv(&self) -> Result<R, mpsc::TryRecvError> {
567            self.receiver.try_recv()
568        }
569    }
570}
571
572/// Concurrent utilities for thread-safe operations
573pub mod concurrent {
574    use parking_lot::{Mutex, RwLock};
575    use std::collections::HashMap;
576    use std::sync::Arc;
577
578    /// Thread-safe cache with concurrent access
579    pub struct ConcurrentCache<K, V>
580    where
581        K: Eq + std::hash::Hash,
582    {
583        data: Arc<RwLock<HashMap<K, V>>>,
584        max_size: usize,
585    }
586
587    impl<K, V> ConcurrentCache<K, V>
588    where
589        K: Eq + std::hash::Hash + Clone,
590        V: Clone,
591    {
592        /// Create a new concurrent cache
593        pub fn new(max_size: usize) -> Self {
594            Self {
595                data: Arc::new(RwLock::new(HashMap::new())),
596                max_size,
597            }
598        }
599
600        /// Get a value from the cache
601        pub fn get(&self, key: &K) -> Option<V> {
602            self.data.read().get(key).cloned()
603        }
604
605        /// Insert a value into the cache
606        pub fn insert(&self, key: K, value: V) {
607            let mut data = self.data.write();
608
609            // Simple eviction if at capacity
610            if data.len() >= self.max_size && !data.contains_key(&key) {
611                if let Some(first_key) = data.keys().next().cloned() {
612                    data.remove(&first_key);
613                }
614            }
615
616            data.insert(key, value);
617        }
618
619        /// Remove a value from the cache
620        pub fn remove(&self, key: &K) -> Option<V> {
621            self.data.write().remove(key)
622        }
623
624        /// Clear the cache
625        pub fn clear(&self) {
626            self.data.write().clear();
627        }
628
629        /// Get cache size
630        pub fn len(&self) -> usize {
631            self.data.read().len()
632        }
633
634        /// Check if cache is empty
635        pub fn is_empty(&self) -> bool {
636            self.data.read().is_empty()
637        }
638    }
639
640    /// Thread-safe statistics collector
641    pub struct StatisticsCollector {
642        data: Arc<Mutex<Vec<f64>>>,
643        max_samples: usize,
644    }
645
646    impl StatisticsCollector {
647        /// Create a new statistics collector
648        pub fn new(max_samples: usize) -> Self {
649            Self {
650                data: Arc::new(Mutex::new(Vec::new())),
651                max_samples,
652            }
653        }
654
655        /// Add a sample
656        pub fn add_sample(&self, value: f64) {
657            let mut data = self.data.lock();
658            if data.len() >= self.max_samples {
659                data.remove(0);
660            }
661            data.push(value);
662        }
663
664        /// Get mean
665        pub fn mean(&self) -> Option<f64> {
666            let data = self.data.lock();
667            if data.is_empty() {
668                None
669            } else {
670                Some(data.iter().sum::<f64>() / data.len() as f64)
671            }
672        }
673
674        /// Get standard deviation
675        pub fn std_dev(&self) -> Option<f64> {
676            let data = self.data.lock();
677            if data.len() < 2 {
678                None
679            } else {
680                let mean = data.iter().sum::<f64>() / data.len() as f64;
681                let variance =
682                    data.iter().map(|x| (x - mean).powi(2)).sum::<f64>() / (data.len() - 1) as f64;
683                Some(variance.sqrt())
684            }
685        }
686
687        /// Get min and max
688        pub fn min_max(&self) -> Option<(f64, f64)> {
689            let data = self.data.lock();
690            if data.is_empty() {
691                None
692            } else {
693                let min = data.iter().fold(f64::INFINITY, |a, &b| a.min(b));
694                let max = data.iter().fold(f64::NEG_INFINITY, |a, &b| a.max(b));
695                Some((min, max))
696            }
697        }
698
699        /// Get sample count
700        pub fn count(&self) -> usize {
701            self.data.lock().len()
702        }
703    }
704}
705
706/// Configuration management utilities
707pub mod config {
708    use std::collections::HashMap;
709    use std::env;
710    use std::path::Path;
711
712    #[cfg(feature = "serialize")]
713    use std::fs;
714    use torsh_core::error::{Result, TorshError};
715
716    #[cfg(feature = "serialize")]
717    use serde::{Deserialize, Serialize};
718
719    /// Configuration manager for handling settings from multiple sources
720    pub struct ConfigManager {
721        values: HashMap<String, ConfigValue>,
722        env_prefix: String,
723    }
724
725    /// Represents different types of configuration values
726    #[derive(Debug, Clone, PartialEq)]
727    #[cfg_attr(feature = "serialize", derive(Serialize, Deserialize))]
728    pub enum ConfigValue {
729        String(String),
730        Integer(i64),
731        Float(f64),
732        Boolean(bool),
733        Array(Vec<ConfigValue>),
734        Object(HashMap<String, ConfigValue>),
735    }
736
737    impl ConfigValue {
738        /// Convert to string if possible
739        pub fn as_string(&self) -> Option<&str> {
740            match self {
741                ConfigValue::String(s) => Some(s),
742                _ => None,
743            }
744        }
745
746        /// Convert to integer if possible
747        pub fn as_i64(&self) -> Option<i64> {
748            match self {
749                ConfigValue::Integer(i) => Some(*i),
750                _ => None,
751            }
752        }
753
754        /// Convert to float if possible
755        pub fn as_f64(&self) -> Option<f64> {
756            match self {
757                ConfigValue::Float(f) => Some(*f),
758                ConfigValue::Integer(i) => Some(*i as f64),
759                _ => None,
760            }
761        }
762
763        /// Convert to boolean if possible
764        pub fn as_bool(&self) -> Option<bool> {
765            match self {
766                ConfigValue::Boolean(b) => Some(*b),
767                _ => None,
768            }
769        }
770
771        /// Convert to array if possible
772        pub fn as_array(&self) -> Option<&Vec<ConfigValue>> {
773            match self {
774                ConfigValue::Array(arr) => Some(arr),
775                _ => None,
776            }
777        }
778
779        /// Convert to object if possible
780        pub fn as_object(&self) -> Option<&HashMap<String, ConfigValue>> {
781            match self {
782                ConfigValue::Object(obj) => Some(obj),
783                _ => None,
784            }
785        }
786    }
787
788    impl ConfigManager {
789        /// Create a new configuration manager
790        pub fn new() -> Self {
791            Self {
792                values: HashMap::new(),
793                env_prefix: "TORSH_".to_string(),
794            }
795        }
796
797        /// Create a new configuration manager with custom environment prefix
798        pub fn with_env_prefix(prefix: &str) -> Self {
799            Self {
800                values: HashMap::new(),
801                env_prefix: prefix.to_string(),
802            }
803        }
804
805        /// Load configuration from JSON file
806        #[cfg(feature = "serialize")]
807        pub fn load_from_file<P: AsRef<Path>>(&mut self, path: P) -> Result<()> {
808            let content = fs::read_to_string(path).map_err(|e| {
809                TorshError::InvalidArgument(format!("Failed to read config file: {}", e))
810            })?;
811
812            let json_value: serde_json::Value = serde_json::from_str(&content)
813                .map_err(|e| TorshError::InvalidArgument(format!("Failed to parse JSON: {}", e)))?;
814
815            self.load_from_json_value("", &json_value);
816            Ok(())
817        }
818
819        /// Load configuration from JSON file (feature-gated fallback)
820        #[cfg(not(feature = "serialize"))]
821        pub fn load_from_file<P: AsRef<Path>>(&mut self, _path: P) -> Result<()> {
822            Err(TorshError::InvalidArgument(
823                "JSON loading requires 'serialize' feature. Enable with --features serialize"
824                    .to_string(),
825            ))
826        }
827
828        /// Load configuration from environment variables
829        pub fn load_from_env(&mut self) {
830            for (key, value) in env::vars() {
831                if key.starts_with(&self.env_prefix) {
832                    let config_key = key
833                        .strip_prefix(&self.env_prefix)
834                        .expect("prefix exists as checked in starts_with")
835                        .to_lowercase();
836                    self.set_from_string(&config_key, &value);
837                }
838            }
839        }
840
841        /// Set a configuration value
842        pub fn set(&mut self, key: &str, value: ConfigValue) {
843            self.values.insert(key.to_string(), value);
844        }
845
846        /// Get a configuration value
847        pub fn get(&self, key: &str) -> Option<&ConfigValue> {
848            self.values.get(key)
849        }
850
851        /// Get a string value with default
852        pub fn get_string(&self, key: &str, default: &str) -> String {
853            self.get(key)
854                .and_then(|v| v.as_string())
855                .unwrap_or(default)
856                .to_string()
857        }
858
859        /// Get an integer value with default
860        pub fn get_i64(&self, key: &str, default: i64) -> i64 {
861            self.get(key).and_then(|v| v.as_i64()).unwrap_or(default)
862        }
863
864        /// Get a float value with default
865        pub fn get_f64(&self, key: &str, default: f64) -> f64 {
866            self.get(key).and_then(|v| v.as_f64()).unwrap_or(default)
867        }
868
869        /// Get a boolean value with default
870        pub fn get_bool(&self, key: &str, default: bool) -> bool {
871            self.get(key).and_then(|v| v.as_bool()).unwrap_or(default)
872        }
873
874        /// Check if a key exists
875        pub fn contains_key(&self, key: &str) -> bool {
876            self.values.contains_key(key)
877        }
878
879        /// Get all configuration keys
880        pub fn keys(&self) -> Vec<&String> {
881            self.values.keys().collect()
882        }
883
884        /// Clear all configuration
885        pub fn clear(&mut self) {
886            self.values.clear();
887        }
888
889        /// Merge configuration from another manager
890        pub fn merge(&mut self, other: &ConfigManager) {
891            for (key, value) in &other.values {
892                self.values.insert(key.clone(), value.clone());
893            }
894        }
895
896        /// Set value from string representation
897        fn set_from_string(&mut self, key: &str, value: &str) {
898            // Try to parse as different types
899            if let Ok(b) = value.parse::<bool>() {
900                self.set(key, ConfigValue::Boolean(b));
901            } else if let Ok(i) = value.parse::<i64>() {
902                self.set(key, ConfigValue::Integer(i));
903            } else if let Ok(f) = value.parse::<f64>() {
904                self.set(key, ConfigValue::Float(f));
905            } else {
906                self.set(key, ConfigValue::String(value.to_string()));
907            }
908        }
909
910        /// Load from JSON value recursively
911        #[cfg(feature = "serialize")]
912        fn load_from_json_value(&mut self, prefix: &str, value: &serde_json::Value) {
913            match value {
914                serde_json::Value::String(s) => {
915                    self.set(prefix, ConfigValue::String(s.clone()));
916                }
917                serde_json::Value::Number(n) => {
918                    if let Some(i) = n.as_i64() {
919                        self.set(prefix, ConfigValue::Integer(i));
920                    } else if let Some(f) = n.as_f64() {
921                        self.set(prefix, ConfigValue::Float(f));
922                    }
923                }
924                serde_json::Value::Bool(b) => {
925                    self.set(prefix, ConfigValue::Boolean(*b));
926                }
927                serde_json::Value::Array(arr) => {
928                    let config_arr: Vec<ConfigValue> = arr
929                        .iter()
930                        .map(|v| self.json_value_to_config_value(v))
931                        .collect();
932                    self.set(prefix, ConfigValue::Array(config_arr));
933                }
934                serde_json::Value::Object(obj) => {
935                    for (key, val) in obj {
936                        let new_key = if prefix.is_empty() {
937                            key.clone()
938                        } else {
939                            format!("{}.{}", prefix, key)
940                        };
941                        self.load_from_json_value(&new_key, val);
942                    }
943                }
944                serde_json::Value::Null => {}
945            }
946        }
947
948        /// Convert JSON value to ConfigValue
949        #[cfg(feature = "serialize")]
950        fn json_value_to_config_value(&self, value: &serde_json::Value) -> ConfigValue {
951            match value {
952                serde_json::Value::String(s) => ConfigValue::String(s.clone()),
953                serde_json::Value::Number(n) => {
954                    if let Some(i) = n.as_i64() {
955                        ConfigValue::Integer(i)
956                    } else if let Some(f) = n.as_f64() {
957                        ConfigValue::Float(f)
958                    } else {
959                        ConfigValue::String(n.to_string())
960                    }
961                }
962                serde_json::Value::Bool(b) => ConfigValue::Boolean(*b),
963                serde_json::Value::Array(arr) => {
964                    let config_arr: Vec<ConfigValue> = arr
965                        .iter()
966                        .map(|v| self.json_value_to_config_value(v))
967                        .collect();
968                    ConfigValue::Array(config_arr)
969                }
970                serde_json::Value::Object(obj) => {
971                    let mut config_obj = HashMap::new();
972                    for (key, val) in obj {
973                        config_obj.insert(key.clone(), self.json_value_to_config_value(val));
974                    }
975                    ConfigValue::Object(config_obj)
976                }
977                serde_json::Value::Null => ConfigValue::String("null".to_string()),
978            }
979        }
980    }
981
982    impl Default for ConfigManager {
983        fn default() -> Self {
984            Self::new()
985        }
986    }
987
988    /// Configuration builder for fluent API
989    pub struct ConfigBuilder {
990        manager: ConfigManager,
991    }
992
993    impl ConfigBuilder {
994        /// Create a new config builder
995        pub fn new() -> Self {
996            Self {
997                manager: ConfigManager::new(),
998            }
999        }
1000
1001        /// Set environment prefix
1002        pub fn env_prefix(mut self, prefix: &str) -> Self {
1003            self.manager.env_prefix = prefix.to_string();
1004            self
1005        }
1006
1007        /// Load from file
1008        #[cfg(feature = "serialize")]
1009        pub fn file<P: AsRef<Path>>(mut self, path: P) -> Result<Self> {
1010            self.manager.load_from_file(path)?;
1011            Ok(self)
1012        }
1013
1014        /// Load from file (feature-gated fallback)
1015        #[cfg(not(feature = "serialize"))]
1016        pub fn file<P: AsRef<Path>>(self, _path: P) -> Result<Self> {
1017            Err(TorshError::InvalidArgument(
1018                "JSON file loading requires 'serialize' feature. Enable with --features serialize"
1019                    .to_string(),
1020            ))
1021        }
1022
1023        /// Load from environment
1024        pub fn env(mut self) -> Self {
1025            self.manager.load_from_env();
1026            self
1027        }
1028
1029        /// Set a value
1030        pub fn set(mut self, key: &str, value: ConfigValue) -> Self {
1031            self.manager.set(key, value);
1032            self
1033        }
1034
1035        /// Set a string value
1036        pub fn set_string(mut self, key: &str, value: &str) -> Self {
1037            self.manager
1038                .set(key, ConfigValue::String(value.to_string()));
1039            self
1040        }
1041
1042        /// Set an integer value
1043        pub fn set_i64(mut self, key: &str, value: i64) -> Self {
1044            self.manager.set(key, ConfigValue::Integer(value));
1045            self
1046        }
1047
1048        /// Set a float value
1049        pub fn set_f64(mut self, key: &str, value: f64) -> Self {
1050            self.manager.set(key, ConfigValue::Float(value));
1051            self
1052        }
1053
1054        /// Set a boolean value
1055        pub fn set_bool(mut self, key: &str, value: bool) -> Self {
1056            self.manager.set(key, ConfigValue::Boolean(value));
1057            self
1058        }
1059
1060        /// Build the configuration manager
1061        pub fn build(self) -> ConfigManager {
1062            self.manager
1063        }
1064    }
1065
1066    impl Default for ConfigBuilder {
1067        fn default() -> Self {
1068            Self::new()
1069        }
1070    }
1071}
1072
1073// Re-export commonly used macros
1074pub use builder_pattern;
1075pub use simple_random_transform;
1076pub use validated_constructor;
1077
1078#[cfg(test)]
1079mod tests {
1080    use super::*;
1081    use std::thread;
1082    use std::time::Duration;
1083
1084    #[test]
1085    fn test_validate_probability() {
1086        assert!(validate_probability(0.5, "test").is_ok());
1087        assert!(validate_probability(0.0, "test").is_ok());
1088        assert!(validate_probability(1.0, "test").is_ok());
1089        assert!(validate_probability(-0.1, "test").is_err());
1090        assert!(validate_probability(1.1, "test").is_err());
1091    }
1092
1093    #[test]
1094    fn test_validate_range() {
1095        assert!(validate_range((0.0, 1.0), "test").is_ok());
1096        assert!(validate_range((1.0, 1.0), "test").is_ok());
1097        assert!(validate_range((1.0, 0.0), "test").is_err());
1098    }
1099
1100    #[test]
1101    fn test_validate_positive() {
1102        assert!(validate_positive(1, "test").is_ok());
1103        assert!(validate_positive(0, "test").is_err());
1104        assert!(validate_positive(-1, "test").is_err());
1105    }
1106
1107    #[test]
1108    fn test_progress_tracker() {
1109        let mut tracker = ProgressTracker::new(10);
1110        assert!(!tracker.is_complete());
1111
1112        // Should report at 10%, 20%, etc.
1113        assert!(tracker.update()); // 10% - should report
1114        assert!(tracker.update()); // 20% - should also report (10% interval)
1115
1116        for _ in 0..8 {
1117            tracker.update();
1118        }
1119        assert!(tracker.is_complete());
1120    }
1121
1122    #[test]
1123    fn test_performance_timer() {
1124        let mut timer = performance::Timer::new();
1125        timer.start();
1126        thread::sleep(Duration::from_millis(10));
1127        let duration = timer.stop();
1128
1129        assert!(duration >= Duration::from_millis(10));
1130        assert!(timer.average().is_some());
1131        assert!(timer.throughput(100).is_some());
1132    }
1133
1134    #[test]
1135    fn test_memory_pool() {
1136        let mut pool = memory::MemoryPool::<u8>::new(5, 1024);
1137        assert_eq!(pool.size(), 0);
1138
1139        let buffer1 = pool.get();
1140        assert_eq!(buffer1.capacity(), 1024);
1141
1142        pool.put(buffer1);
1143        assert_eq!(pool.size(), 1);
1144
1145        let buffer2 = pool.get();
1146        assert_eq!(pool.size(), 0);
1147        assert_eq!(buffer2.len(), 0); // Should be cleared
1148    }
1149
1150    #[test]
1151    fn test_memory_tracker() {
1152        let mut tracker = memory::MemoryTracker::new();
1153        assert_eq!(tracker.current_usage(), 0);
1154
1155        tracker.allocate("test", 1024);
1156        assert_eq!(tracker.current_usage(), 1024);
1157        assert_eq!(tracker.peak_usage(), 1024);
1158
1159        tracker.deallocate("test", 512);
1160        assert_eq!(tracker.current_usage(), 512);
1161        assert_eq!(tracker.peak_usage(), 1024); // Peak should remain
1162    }
1163
1164    #[test]
1165    fn test_parallel_batch_process() {
1166        let data = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
1167        let results = batch::parallel_batch_process(data, 3, |chunk| chunk.iter().sum::<i32>());
1168
1169        assert_eq!(results.len(), 4); // 4 batches: [1,2,3], [4,5,6], [7,8,9], [10]
1170        assert_eq!(results[0], 6); // 1+2+3
1171        assert_eq!(results[1], 15); // 4+5+6
1172        assert_eq!(results[2], 24); // 7+8+9
1173        assert_eq!(results[3], 10); // 10
1174    }
1175
1176    #[test]
1177    fn test_concurrent_cache() {
1178        let cache = concurrent::ConcurrentCache::new(2);
1179
1180        cache.insert("key1", "value1");
1181        cache.insert("key2", "value2");
1182        assert_eq!(cache.len(), 2);
1183
1184        assert_eq!(cache.get(&"key1"), Some("value1"));
1185        assert_eq!(cache.get(&"key2"), Some("value2"));
1186        assert_eq!(cache.get(&"key3"), None);
1187
1188        // Test eviction
1189        cache.insert("key3", "value3");
1190        assert_eq!(cache.len(), 2); // Should evict oldest
1191    }
1192
1193    #[test]
1194    fn test_statistics_collector() {
1195        let collector = concurrent::StatisticsCollector::new(100);
1196        assert_eq!(collector.count(), 0);
1197
1198        collector.add_sample(1.0);
1199        collector.add_sample(2.0);
1200        collector.add_sample(3.0);
1201
1202        assert_eq!(collector.count(), 3);
1203        assert_eq!(collector.mean(), Some(2.0));
1204        assert_eq!(collector.min_max(), Some((1.0, 3.0)));
1205        assert!(collector.std_dev().is_some());
1206    }
1207
1208    #[test]
1209    fn test_config_manager() {
1210        let mut config = config::ConfigManager::new();
1211
1212        // Test setting and getting different types
1213        config.set(
1214            "string_key",
1215            config::ConfigValue::String("test_value".to_string()),
1216        );
1217        config.set("int_key", config::ConfigValue::Integer(42));
1218        config.set("float_key", config::ConfigValue::Float(3.14));
1219        config.set("bool_key", config::ConfigValue::Boolean(true));
1220
1221        assert_eq!(config.get_string("string_key", "default"), "test_value");
1222        assert_eq!(config.get_i64("int_key", 0), 42);
1223        assert_eq!(config.get_f64("float_key", 0.0), 3.14);
1224        assert!(config.get_bool("bool_key", false));
1225
1226        // Test defaults
1227        assert_eq!(config.get_string("missing_key", "default"), "default");
1228        assert_eq!(config.get_i64("missing_key", 123), 123);
1229
1230        // Test contains_key
1231        assert!(config.contains_key("string_key"));
1232        assert!(!config.contains_key("missing_key"));
1233
1234        // Test keys
1235        let keys = config.keys();
1236        assert!(keys.len() >= 4);
1237
1238        // Test clear
1239        config.clear();
1240        assert_eq!(config.keys().len(), 0);
1241    }
1242
1243    #[test]
1244    fn test_config_value_conversions() {
1245        let string_val = config::ConfigValue::String("test".to_string());
1246        let int_val = config::ConfigValue::Integer(42);
1247        let float_val = config::ConfigValue::Float(3.14);
1248        let bool_val = config::ConfigValue::Boolean(true);
1249
1250        assert_eq!(string_val.as_string(), Some("test"));
1251        assert_eq!(int_val.as_i64(), Some(42));
1252        assert_eq!(float_val.as_f64(), Some(3.14));
1253        assert_eq!(bool_val.as_bool(), Some(true));
1254
1255        // Test type mismatches
1256        assert_eq!(string_val.as_i64(), None);
1257        assert_eq!(int_val.as_string(), None);
1258
1259        // Test integer to float conversion
1260        assert_eq!(int_val.as_f64(), Some(42.0));
1261    }
1262
1263    #[test]
1264    fn test_config_builder() {
1265        let config = config::ConfigBuilder::new()
1266            .env_prefix("TEST_")
1267            .set_string("app_name", "torsh-data")
1268            .set_i64("version", 1)
1269            .set_f64("threshold", 0.5)
1270            .set_bool("debug", true)
1271            .build();
1272
1273        assert_eq!(config.get_string("app_name", ""), "torsh-data");
1274        assert_eq!(config.get_i64("version", 0), 1);
1275        assert_eq!(config.get_f64("threshold", 0.0), 0.5);
1276        assert!(config.get_bool("debug", false));
1277    }
1278
1279    #[test]
1280    fn test_config_merge() {
1281        let mut config1 = config::ConfigManager::new();
1282        config1.set("key1", config::ConfigValue::String("value1".to_string()));
1283        config1.set("key2", config::ConfigValue::Integer(42));
1284
1285        let mut config2 = config::ConfigManager::new();
1286        config2.set("key2", config::ConfigValue::Integer(100)); // Override
1287        config2.set("key3", config::ConfigValue::Boolean(true)); // New key
1288
1289        config1.merge(&config2);
1290
1291        assert_eq!(config1.get_string("key1", ""), "value1");
1292        assert_eq!(config1.get_i64("key2", 0), 100); // Should be overridden
1293        assert!(config1.get_bool("key3", false));
1294    }
1295}