1use crate::error::{Error, Result};
7use std::collections::BTreeMap;
8use std::fmt;
9
10#[derive(Debug, Clone, PartialEq)]
12pub enum Value {
13 Null,
15 Bool(bool),
17 Integer(i64),
19 Float(f64),
21 String(String),
23 Array(Vec<Value>),
25 Table(BTreeMap<String, Value>),
27 #[cfg(feature = "chrono")]
29 DateTime(chrono::DateTime<chrono::Utc>),
30}
31
32impl Value {
33 pub fn null() -> Self {
35 Value::Null
36 }
37
38 pub fn bool(value: bool) -> Self {
40 Value::Bool(value)
41 }
42
43 pub fn integer(value: i64) -> Self {
45 Value::Integer(value)
46 }
47
48 pub fn float(value: f64) -> Self {
50 Value::Float(value)
51 }
52
53 pub fn string<S: Into<String>>(value: S) -> Self {
55 Value::String(value.into())
56 }
57
58 pub fn array(values: Vec<Value>) -> Self {
60 Value::Array(values)
61 }
62
63 pub fn table(table: BTreeMap<String, Value>) -> Self {
65 Value::Table(table)
66 }
67
68 #[cfg(feature = "chrono")]
70 pub fn datetime(dt: chrono::DateTime<chrono::Utc>) -> Self {
71 Value::DateTime(dt)
72 }
73
74 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 pub fn is_null(&self) -> bool {
91 matches!(self, Value::Null)
92 }
93
94 pub fn is_bool(&self) -> bool {
96 matches!(self, Value::Bool(_))
97 }
98
99 pub fn is_integer(&self) -> bool {
101 matches!(self, Value::Integer(_))
102 }
103
104 pub fn is_float(&self) -> bool {
106 matches!(self, Value::Float(_))
107 }
108
109 pub fn is_string(&self) -> bool {
111 matches!(self, Value::String(_))
112 }
113
114 pub fn is_array(&self) -> bool {
116 matches!(self, Value::Array(_))
117 }
118
119 pub fn is_table(&self) -> bool {
121 matches!(self, Value::Table(_))
122 }
123
124 pub fn as_bool(&self) -> Result<bool> {
126 match self {
127 Value::Bool(b) => Ok(*b),
128 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 pub fn as_integer(&self) -> Result<i64> {
151 match self {
152 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 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 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 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 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 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 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 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 pub fn get(&self, path: &str) -> Option<&Value> {
260 if path.is_empty() {
261 return Some(self);
262 }
263
264 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 found_nested {
287 return Some(current);
288 }
289
290 if let Value::Table(table) = self {
292 table.get(path)
293 } else {
294 None
295 }
296 }
297
298 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 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 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 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 let mut current = self;
366 for part in parent_path {
367 if let Value::Table(table) = current {
368 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 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 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 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 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 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 pub fn contains_key(&self, path: &str) -> bool {
464 self.get(path).is_some()
465 }
466
467 pub fn set(&mut self, path: &str, value: Value) -> Result<()> {
469 self.set_nested(path, value)
470 }
471
472 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 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
522impl 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
577impl Value {
579 pub fn string_from_slice(value: &str) -> Self {
581 Value::String(value.to_string())
582 }
583
584 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 assert!(value.get_mut_nested("nonexistent.key").is_err());
667 assert!(value.remove("nonexistent.key").is_err());
668
669 assert!(value.set_nested("test.key", Value::string("value")).is_ok());
671 assert!(value.get("test.key").is_some());
672 }
673}