hocon/value.rs
1use indexmap::IndexMap;
2
3/// A resolved HOCON value.
4///
5/// This is the tree that [`Config`](crate::Config) wraps. You normally interact
6/// with it through the typed getters on `Config`, but it is also returned
7/// directly by [`Config::get`](crate::Config::get) and
8/// [`Config::get_list`](crate::Config::get_list).
9#[non_exhaustive]
10#[derive(Debug, Clone, PartialEq)]
11pub enum HoconValue {
12 /// An ordered map of key-value pairs (HOCON object / JSON object).
13 Object(IndexMap<String, HoconValue>),
14 /// An ordered list of values (HOCON array / JSON array).
15 Array(Vec<HoconValue>),
16 /// A leaf value (string, number, boolean, or null).
17 Scalar(ScalarValue),
18}
19
20/// The type tag for a scalar value.
21#[non_exhaustive]
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
23pub enum ScalarType {
24 /// A string value.
25 String,
26 /// A numeric value (integer or floating-point).
27 Number,
28 /// A boolean value.
29 Boolean,
30 /// An explicit null.
31 Null,
32}
33
34/// A scalar (leaf) value inside a HOCON document.
35///
36/// Stores the raw string representation alongside a type tag.
37/// Typed access (i64, f64, bool) is done by parsing `raw` on demand.
38#[non_exhaustive]
39#[derive(Debug, Clone, PartialEq)]
40pub struct ScalarValue {
41 /// The raw string as it appeared in the source (or was produced by resolution).
42 pub raw: String,
43 /// The semantic type of this scalar.
44 pub value_type: ScalarType,
45}
46
47impl ScalarValue {
48 /// Create a new scalar value with explicit type.
49 pub fn new(raw: String, value_type: ScalarType) -> Self {
50 Self { raw, value_type }
51 }
52
53 /// Create a string-typed scalar.
54 pub fn string(raw: String) -> Self {
55 Self {
56 raw,
57 value_type: ScalarType::String,
58 }
59 }
60
61 /// Create a null scalar.
62 pub fn null() -> Self {
63 Self {
64 raw: "null".to_string(),
65 value_type: ScalarType::Null,
66 }
67 }
68
69 /// Create a boolean scalar.
70 pub fn boolean(value: bool) -> Self {
71 Self {
72 raw: if value { "true" } else { "false" }.to_string(),
73 value_type: ScalarType::Boolean,
74 }
75 }
76
77 /// Create a number scalar from a raw string.
78 pub fn number(raw: String) -> Self {
79 Self {
80 raw,
81 value_type: ScalarType::Number,
82 }
83 }
84}