Skip to main content

config_lib/
value.rs

1//! Value types and operations for the config library.
2//!
3//! This module provides a flexible value system that can represent various data types
4//! commonly found in configuration files.
5
6use crate::error::{Error, Result};
7use std::collections::BTreeMap;
8use std::fmt;
9
10/// Represents a configuration value.
11#[derive(Debug, Clone, PartialEq)]
12pub enum Value {
13    /// Null/empty value
14    Null,
15    /// Boolean value
16    Bool(bool),
17    /// Integer value
18    Integer(i64),
19    /// Floating point value
20    Float(f64),
21    /// String value
22    String(String),
23    /// Array of values
24    Array(Vec<Value>),
25    /// Table (key-value pairs)
26    Table(BTreeMap<String, Value>),
27    /// DateTime value (when chrono feature is enabled)
28    #[cfg(feature = "chrono")]
29    DateTime(chrono::DateTime<chrono::Utc>),
30}
31
32impl Value {
33    /// Create a new null value
34    pub fn null() -> Self {
35        Value::Null
36    }
37
38    /// Create a new boolean value
39    pub fn bool(value: bool) -> Self {
40        Value::Bool(value)
41    }
42
43    /// Create a new integer value
44    pub fn integer(value: i64) -> Self {
45        Value::Integer(value)
46    }
47
48    /// Create a new float value
49    pub fn float(value: f64) -> Self {
50        Value::Float(value)
51    }
52
53    /// Create a new string value
54    pub fn string<S: Into<String>>(value: S) -> Self {
55        Value::String(value.into())
56    }
57
58    /// Create a new array value
59    pub fn array(values: Vec<Value>) -> Self {
60        Value::Array(values)
61    }
62
63    /// Create a new table value
64    pub fn table(table: BTreeMap<String, Value>) -> Self {
65        Value::Table(table)
66    }
67
68    /// Create a new datetime value (when chrono feature is enabled)
69    #[cfg(feature = "chrono")]
70    pub fn datetime(dt: chrono::DateTime<chrono::Utc>) -> Self {
71        Value::DateTime(dt)
72    }
73
74    /// Get the type name of this value
75    pub fn type_name(&self) -> &'static str {
76        match self {
77            Value::Null => "null",
78            Value::Bool(_) => "bool",
79            Value::Integer(_) => "integer",
80            Value::Float(_) => "float",
81            Value::String(_) => "string",
82            Value::Array(_) => "array",
83            Value::Table(_) => "table",
84            #[cfg(feature = "chrono")]
85            Value::DateTime(_) => "datetime",
86        }
87    }
88
89    /// Check if this value is null
90    pub fn is_null(&self) -> bool {
91        matches!(self, Value::Null)
92    }
93
94    /// Check if this value is a boolean
95    pub fn is_bool(&self) -> bool {
96        matches!(self, Value::Bool(_))
97    }
98
99    /// Check if this value is an integer
100    pub fn is_integer(&self) -> bool {
101        matches!(self, Value::Integer(_))
102    }
103
104    /// Check if this value is a float
105    pub fn is_float(&self) -> bool {
106        matches!(self, Value::Float(_))
107    }
108
109    /// Check if this value is a string
110    pub fn is_string(&self) -> bool {
111        matches!(self, Value::String(_))
112    }
113
114    /// Check if this value is an array
115    pub fn is_array(&self) -> bool {
116        matches!(self, Value::Array(_))
117    }
118
119    /// Check if this value is a table
120    pub fn is_table(&self) -> bool {
121        matches!(self, Value::Table(_))
122    }
123
124    /// Try to convert this value to a boolean
125    pub fn as_bool(&self) -> Result<bool> {
126        match self {
127            Value::Bool(b) => Ok(*b),
128            // INI and environment values `1` and `0` are integers since
129            // v1.4.0; they still read as booleans
130            Value::Integer(1) => Ok(true),
131            Value::Integer(0) => Ok(false),
132            Value::String(s) => match s.to_lowercase().as_str() {
133                "true" | "yes" | "1" | "on" => Ok(true),
134                "false" | "no" | "0" | "off" => Ok(false),
135                _ => Err(Error::type_error(
136                    "Cannot convert to boolean",
137                    "bool",
138                    self.type_name(),
139                )),
140            },
141            _ => Err(Error::type_error(
142                "Cannot convert to boolean",
143                "bool",
144                self.type_name(),
145            )),
146        }
147    }
148
149    /// Try to convert this value to an integer
150    pub fn as_integer(&self) -> Result<i64> {
151        match self {
152            // Same rules as `i64::try_from`: a float converts only when it
153            // is whole and in range (before v1.4.0 NaN became 0, 100.9 became
154            // 100, and 1e20 saturated to i64::MAX)
155            Value::Integer(_) | Value::Float(_) => crate::convert::integer_from(self, "integer"),
156            Value::String(s) => s.parse::<i64>().map_err(|_| {
157                Error::type_error("Cannot convert to integer", "integer", self.type_name())
158            }),
159            _ => Err(Error::type_error(
160                "Cannot convert to integer",
161                "integer",
162                self.type_name(),
163            )),
164        }
165    }
166
167    /// Try to convert this value to a float
168    pub fn as_float(&self) -> Result<f64> {
169        match self {
170            Value::Float(f) => Ok(*f),
171            Value::Integer(i) => Ok(*i as f64),
172            Value::String(s) => s.parse::<f64>().map_err(|_| {
173                Error::type_error("Cannot convert to float", "float", self.type_name())
174            }),
175            _ => Err(Error::type_error(
176                "Cannot convert to float",
177                "float",
178                self.type_name(),
179            )),
180        }
181    }
182
183    /// Try to convert this value to a string - ZERO-COPY optimized
184    pub fn as_string(&self) -> Result<&str> {
185        match self {
186            Value::String(s) => Ok(s.as_str()),
187            _ => Err(Error::type_error(
188                "Cannot convert to string",
189                "string",
190                self.type_name(),
191            )),
192        }
193    }
194
195    /// Convert this value to a string representation (allocating)
196    pub fn to_string_representation(&self) -> Result<String> {
197        match self {
198            Value::String(s) => Ok(s.clone()),
199            Value::Integer(i) => Ok(i.to_string()),
200            Value::Float(f) => Ok(f.to_string()),
201            Value::Bool(b) => Ok(b.to_string()),
202            _ => Err(Error::type_error(
203                "Cannot convert to string representation",
204                "string",
205                self.type_name(),
206            )),
207        }
208    }
209
210    /// Try to get this value as an array
211    pub fn as_array(&self) -> Result<&Vec<Value>> {
212        match self {
213            Value::Array(arr) => Ok(arr),
214            _ => Err(Error::type_error(
215                "Cannot convert to array",
216                "array",
217                self.type_name(),
218            )),
219        }
220    }
221
222    /// Try to get this value as a mutable array
223    pub fn as_array_mut(&mut self) -> Result<&mut Vec<Value>> {
224        match self {
225            Value::Array(arr) => Ok(arr),
226            _ => Err(Error::type_error(
227                "Cannot convert to array",
228                "array",
229                self.type_name(),
230            )),
231        }
232    }
233
234    /// Try to get this value as a table
235    pub fn as_table(&self) -> Result<&BTreeMap<String, Value>> {
236        match self {
237            Value::Table(table) => Ok(table),
238            _ => Err(Error::type_error(
239                "Cannot convert to table",
240                "table",
241                self.type_name(),
242            )),
243        }
244    }
245
246    /// Try to get this value as a mutable table
247    pub fn as_table_mut(&mut self) -> Result<&mut BTreeMap<String, Value>> {
248        match self {
249            Value::Table(table) => Ok(table),
250            _ => Err(Error::type_error(
251                "Cannot convert to table",
252                "table",
253                self.type_name(),
254            )),
255        }
256    }
257
258    /// Get a value by path (dot-separated)
259    pub fn get(&self, path: &str) -> Option<&Value> {
260        if path.is_empty() {
261            return Some(self);
262        }
263
264        // First try nested table access
265        let mut current = self;
266        let mut found_nested = true;
267
268        for part in path.split('.') {
269            match current {
270                Value::Table(table) => {
271                    if let Some(next) = table.get(part) {
272                        current = next;
273                    } else {
274                        found_nested = false;
275                        break;
276                    }
277                }
278                _ => {
279                    found_nested = false;
280                    break;
281                }
282            }
283        }
284
285        // If nested access succeeds, return it
286        if found_nested {
287            return Some(current);
288        }
289
290        // Fallback: try flat key access for formats like INI that use dotted keys
291        if let Value::Table(table) = self {
292            table.get(path)
293        } else {
294            None
295        }
296    }
297
298    /// Get a mutable reference to a value by path (ENTERPRISE ERROR HANDLING)
299    pub fn get_mut_nested(&mut self, path: &str) -> Result<&mut Value> {
300        if path.is_empty() {
301            return Ok(self);
302        }
303
304        let parts: Vec<&str> = path.split('.').collect();
305        if parts.is_empty() {
306            return Err(Error::key_not_found(path));
307        }
308
309        let (last_key, parent_path) = parts
310            .split_last()
311            .ok_or_else(|| Error::key_not_found(path))?;
312
313        // Navigate to parent
314        let mut current = self;
315        for part in parent_path {
316            match current {
317                Value::Table(table) => {
318                    current = table
319                        .get_mut(*part)
320                        .ok_or_else(|| Error::key_not_found(*part))?;
321                }
322                _ => {
323                    return Err(Error::type_error(
324                        format!(
325                            "Cannot navigate into {} when looking for key '{}'",
326                            current.type_name(),
327                            part
328                        ),
329                        "table",
330                        current.type_name(),
331                    ))
332                }
333            }
334        }
335
336        // Get the final value
337        match current {
338            Value::Table(table) => table
339                .get_mut(*last_key)
340                .ok_or_else(|| Error::key_not_found(*last_key)),
341            _ => Err(Error::type_error(
342                format!("Cannot get key '{}' from {}", last_key, current.type_name()),
343                "table",
344                current.type_name(),
345            )),
346        }
347    }
348
349    /// Set a value by path, creating intermediate tables as needed (ZERO-COPY optimized)
350    pub fn set_nested(&mut self, path: &str, value: Value) -> Result<()> {
351        if path.is_empty() {
352            return Err(Error::key_not_found(""));
353        }
354
355        let parts: Vec<&str> = path.split('.').collect();
356        if parts.is_empty() {
357            return Err(Error::key_not_found(path));
358        }
359
360        let (last_key, parent_path) = parts
361            .split_last()
362            .ok_or_else(|| Error::key_not_found(path))?;
363
364        // Navigate to parent, creating tables as needed
365        let mut current = self;
366        for part in parent_path {
367            if let Value::Table(table) = current {
368                // ZERO-COPY: Use entry API to avoid string allocation when possible
369                let entry = table
370                    .entry((*part).to_string())
371                    .or_insert_with(|| Value::table(BTreeMap::new()));
372                current = entry;
373            } else {
374                return Err(Error::type_error(
375                    format!("Cannot navigate into {}", current.type_name()),
376                    "table",
377                    current.type_name(),
378                ));
379            }
380        }
381
382        // Set the final value
383        if let Value::Table(table) = current {
384            table.insert((*last_key).to_string(), value);
385            Ok(())
386        } else {
387            Err(Error::type_error(
388                format!("Cannot set key in {}", current.type_name()),
389                "table",
390                current.type_name(),
391            ))
392        }
393    }
394
395    /// Remove a value by path (ENTERPRISE ERROR HANDLING)
396    pub fn remove(&mut self, path: &str) -> Result<Option<Value>> {
397        if path.is_empty() {
398            let old = std::mem::replace(self, Value::Null);
399            return Ok(Some(old));
400        }
401
402        let parts: Vec<&str> = path.split('.').collect();
403        if parts.is_empty() {
404            return Err(Error::key_not_found(path));
405        }
406
407        let (last_key, parent_path) = parts
408            .split_last()
409            .ok_or_else(|| Error::key_not_found(path))?;
410
411        // Navigate to parent
412        let mut current = self;
413        for part in parent_path {
414            match current {
415                Value::Table(table) => {
416                    current = table
417                        .get_mut(*part)
418                        .ok_or_else(|| Error::key_not_found(*part))?;
419                }
420                _ => {
421                    return Err(Error::type_error(
422                        format!(
423                            "Cannot navigate into {} when removing key '{}'",
424                            current.type_name(),
425                            part
426                        ),
427                        "table",
428                        current.type_name(),
429                    ))
430                }
431            }
432        }
433
434        // Remove from parent
435        if let Value::Table(table) = current {
436            Ok(table.remove(*last_key))
437        } else {
438            Err(Error::type_error(
439                format!(
440                    "Cannot remove key '{}' from {}",
441                    last_key,
442                    current.type_name()
443                ),
444                "table",
445                current.type_name(),
446            ))
447        }
448    }
449
450    /// Get all keys at the current level (for tables only) - ZERO-COPY optimized
451    pub fn keys(&self) -> Result<Vec<&str>> {
452        match self {
453            Value::Table(table) => Ok(table.keys().map(|k| k.as_str()).collect()),
454            _ => Err(Error::type_error(
455                "Cannot get keys from non-table value",
456                "table",
457                self.type_name(),
458            )),
459        }
460    }
461
462    /// Check if a path exists
463    pub fn contains_key(&self, path: &str) -> bool {
464        self.get(path).is_some()
465    }
466
467    /// Set a value by path (backward compatibility alias)
468    pub fn set(&mut self, path: &str, value: Value) -> Result<()> {
469        self.set_nested(path, value)
470    }
471
472    /// Get the length of arrays or tables
473    pub fn len(&self) -> usize {
474        match self {
475            Value::Array(arr) => arr.len(),
476            Value::Table(table) => table.len(),
477            Value::String(s) => s.len(),
478            _ => 0,
479        }
480    }
481
482    /// Check if arrays or tables are empty
483    pub fn is_empty(&self) -> bool {
484        self.len() == 0
485    }
486}
487
488impl fmt::Display for Value {
489    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
490        match self {
491            Value::Null => write!(f, "null"),
492            Value::Bool(b) => write!(f, "{b}"),
493            Value::Integer(i) => write!(f, "{i}"),
494            Value::Float(fl) => write!(f, "{fl}"),
495            Value::String(s) => write!(f, "{s}"),
496            Value::Array(arr) => {
497                write!(f, "[")?;
498                for (i, item) in arr.iter().enumerate() {
499                    if i > 0 {
500                        write!(f, ", ")?;
501                    }
502                    write!(f, "{item}")?;
503                }
504                write!(f, "]")
505            }
506            Value::Table(table) => {
507                write!(f, "{{")?;
508                for (i, (key, value)) in table.iter().enumerate() {
509                    if i > 0 {
510                        write!(f, ", ")?;
511                    }
512                    write!(f, "{key}: {value}")?;
513                }
514                write!(f, "}}")
515            }
516            #[cfg(feature = "chrono")]
517            Value::DateTime(dt) => write!(f, "{}", dt.to_rfc3339()),
518        }
519    }
520}
521
522// ZERO-COPY conversion implementations
523impl From<bool> for Value {
524    fn from(value: bool) -> Self {
525        Value::Bool(value)
526    }
527}
528
529impl From<i32> for Value {
530    fn from(value: i32) -> Self {
531        Value::Integer(i64::from(value))
532    }
533}
534
535impl From<i64> for Value {
536    fn from(value: i64) -> Self {
537        Value::Integer(value)
538    }
539}
540
541impl From<f32> for Value {
542    fn from(value: f32) -> Self {
543        Value::Float(f64::from(value))
544    }
545}
546
547impl From<f64> for Value {
548    fn from(value: f64) -> Self {
549        Value::Float(value)
550    }
551}
552
553impl From<String> for Value {
554    fn from(value: String) -> Self {
555        Value::String(value)
556    }
557}
558
559impl From<&str> for Value {
560    fn from(value: &str) -> Self {
561        Value::String(value.to_string())
562    }
563}
564
565impl From<Vec<Value>> for Value {
566    fn from(value: Vec<Value>) -> Self {
567        Value::Array(value)
568    }
569}
570
571impl From<BTreeMap<String, Value>> for Value {
572    fn from(value: BTreeMap<String, Value>) -> Self {
573        Value::Table(value)
574    }
575}
576
577// ENTERPRISE: Helper functions for zero-copy operations
578impl Value {
579    /// Create a string value from a slice without unnecessary allocation
580    pub fn string_from_slice(value: &str) -> Self {
581        Value::String(value.to_string())
582    }
583
584    /// Get string slice without allocation - enterprise optimization
585    pub fn as_str(&self) -> Result<&str> {
586        match self {
587            Value::String(s) => Ok(s.as_str()),
588            _ => Err(Error::type_error(
589                "Value is not a string",
590                "string",
591                self.type_name(),
592            )),
593        }
594    }
595}
596
597#[cfg(test)]
598mod tests {
599    use super::*;
600
601    #[test]
602    fn test_value_creation() {
603        assert_eq!(Value::null(), Value::Null);
604        assert_eq!(Value::bool(true), Value::Bool(true));
605        assert_eq!(Value::integer(42), Value::Integer(42));
606        assert_eq!(Value::float(1.234), Value::Float(1.234));
607        assert_eq!(Value::string("test"), Value::String("test".to_string()));
608    }
609
610    #[test]
611    fn test_type_checking() {
612        let null = Value::null();
613        let bool_val = Value::bool(true);
614        let int_val = Value::integer(42);
615        let float_val = Value::float(5.678);
616        let string_val = Value::string("test");
617        let array_val = Value::array(vec![Value::integer(1), Value::integer(2)]);
618        let table_val = Value::table(BTreeMap::new());
619
620        assert!(null.is_null());
621        assert!(bool_val.is_bool());
622        assert!(int_val.is_integer());
623        assert!(float_val.is_float());
624        assert!(string_val.is_string());
625        assert!(array_val.is_array());
626        assert!(table_val.is_table());
627    }
628
629    #[test]
630    fn test_value_conversion() {
631        let bool_val = Value::bool(true);
632        let int_val = Value::integer(42);
633        let float_val = Value::float(1.234);
634        let string_val = Value::string("test");
635
636        assert!(bool_val.as_bool().unwrap());
637        assert_eq!(int_val.as_integer().unwrap(), 42);
638        assert_eq!(float_val.as_float().unwrap(), 1.234);
639        assert_eq!(string_val.as_string().unwrap(), "test");
640    }
641
642    #[test]
643    fn test_nested_access() {
644        let mut table = BTreeMap::new();
645        let mut inner_table = BTreeMap::new();
646        inner_table.insert("inner_key".to_string(), Value::string("inner_value"));
647        table.insert("outer_key".to_string(), Value::table(inner_table));
648
649        let value = Value::table(table);
650
651        assert_eq!(
652            value
653                .get("outer_key.inner_key")
654                .unwrap()
655                .as_string()
656                .unwrap(),
657            "inner_value"
658        );
659    }
660
661    #[test]
662    fn test_enterprise_error_handling() {
663        let mut value = Value::table(BTreeMap::new());
664
665        // Test proper error handling instead of panics
666        assert!(value.get_mut_nested("nonexistent.key").is_err());
667        assert!(value.remove("nonexistent.key").is_err());
668
669        // Test successful operations
670        assert!(value.set_nested("test.key", Value::string("value")).is_ok());
671        assert!(value.get("test.key").is_some());
672    }
673}