datadog_agent_config_corpus/
getter.rs1use std::collections::BTreeMap;
17
18use crate::json::Json;
19use crate::lists::Getter;
20
21#[derive(Clone, Debug, PartialEq)]
23pub struct Number<T> {
24 pub value: T,
26 pub token: String,
28}
29
30#[derive(Clone, Debug, PartialEq)]
32pub enum GoFloat {
33 Finite(Number<f64>),
35 NaN,
37 PosInf,
39 NegInf,
41}
42
43#[derive(Clone, Debug, PartialEq)]
45pub enum GoValue {
46 Null,
48 Bool(bool),
50 Int(Number<i128>),
52 Float(GoFloat),
54 String(String),
56 List(Vec<GoValue>),
58 Map(BTreeMap<String, GoValue>),
60}
61
62#[derive(Clone, Debug, PartialEq)]
64pub enum GetterResult {
65 Bool(bool),
67 String(String),
69 Int(Number<i64>),
71 Int32(Number<i32>),
73 SizeInBytes(Number<u64>),
75 Duration(Number<i64>),
77 Float64(GoFloat),
79 Float64Slice(Option<Vec<GoFloat>>),
81 StringSlice(Option<Vec<String>>),
83 StringMap(Option<BTreeMap<String, GoValue>>),
85 StringMapString(Option<BTreeMap<String, String>>),
87 StringMapStringSlice(BTreeMap<String, Option<Vec<String>>>),
89 Get(GoValue),
91 Section(BTreeMap<String, GoValue>),
93 IsConfigured(bool),
95}
96
97type R<T> = Result<T, String>;
98
99fn is_float_token(n: &str) -> bool {
100 n.contains(['.', 'e', 'E'])
101}
102
103fn integer<T: std::str::FromStr>(v: &Json, what: &str) -> R<Number<T>> {
104 match v {
105 Json::Num(n) if !is_float_token(n) => n
106 .parse()
107 .map(|value| Number {
108 value,
109 token: n.clone(),
110 })
111 .map_err(|_| format!("{what}: integer {n} is out of range")),
112 other => Err(format!("{what}: expected an integer token, found {}", describe(other))),
113 }
114}
115
116fn describe(v: &Json) -> String {
117 match v {
118 Json::Num(n) => format!("number {n}"),
119 other => other.kind().to_string(),
120 }
121}
122
123fn non_finite(m: &[(crate::json::JStr, Json)]) -> Option<R<GoFloat>> {
125 let [(k, v)] = m else { return None };
126 if k.text != "$float" {
127 return None;
128 }
129 Some(match v.as_str() {
130 Some("NaN") => Ok(GoFloat::NaN),
131 Some("+Inf") => Ok(GoFloat::PosInf),
132 Some("-Inf") => Ok(GoFloat::NegInf),
133 _ => Err("a map whose only key is \"$float\" must be NaN, +Inf or -Inf".into()),
134 })
135}
136
137fn float(v: &Json, what: &str) -> R<GoFloat> {
138 match v {
139 Json::Num(n) if is_float_token(n) => {
140 let value: f64 = n.parse().map_err(|_| format!("{what}: bad float {n}"))?;
141 if !value.is_finite() {
142 return Err(format!("{what}: float {n} is out of range"));
143 }
144 Ok(GoFloat::Finite(Number {
145 value,
146 token: n.clone(),
147 }))
148 }
149 Json::Obj(m) => non_finite(m).unwrap_or_else(|| Err(format!("{what}: expected a float, found object"))),
150 other => Err(format!(
151 "{what}: expected a float token (with '.', 'e' or 'E'), found {}",
152 describe(other)
153 )),
154 }
155}
156
157fn string(v: &Json, what: &str) -> R<String> {
158 v.as_str()
159 .map(str::to_string)
160 .ok_or_else(|| format!("{what}: expected a string, found {}", describe(v)))
161}
162
163fn nullable<T>(v: &Json, f: impl FnOnce(&Json) -> R<T>) -> R<Option<T>> {
164 match v {
165 Json::Null => Ok(None),
166 v => f(v).map(Some),
167 }
168}
169
170fn list<T>(v: &Json, what: &str, f: impl Fn(&Json) -> R<T>) -> R<Vec<T>> {
171 match v {
172 Json::Arr(a) => a.iter().map(f).collect(),
173 other => Err(format!("{what}: expected an array, found {}", describe(other))),
174 }
175}
176
177fn map<T>(v: &Json, what: &str, f: impl Fn(&Json) -> R<T>) -> R<BTreeMap<String, T>> {
178 match v {
179 Json::Obj(m) => {
180 if non_finite(m).is_some() {
181 return Err(format!("{what}: a map whose only key is \"$float\" is not a map"));
182 }
183 m.iter().map(|(k, x)| Ok((k.text.clone(), f(x)?))).collect()
184 }
185 other => Err(format!("{what}: expected an object, found {}", describe(other))),
186 }
187}
188
189fn go_value(v: &Json) -> R<GoValue> {
190 Ok(match v {
191 Json::Null => GoValue::Null,
192 Json::Bool(b) => GoValue::Bool(*b),
193 Json::Num(n) if is_float_token(n) => GoValue::Float(float(v, "value")?),
194 Json::Num(_) => GoValue::Int(integer(v, "value")?),
195 Json::Str(s) => GoValue::String(s.text.clone()),
196 Json::Arr(_) => GoValue::List(list(v, "value", go_value)?),
197 Json::Obj(m) => match non_finite(m) {
198 Some(f) => GoValue::Float(f?),
199 None => GoValue::Map(map(v, "value", go_value)?),
200 },
201 })
202}
203
204pub(crate) fn decode(getter: Getter, v: &Json) -> R<GetterResult> {
206 let what = getter.as_str();
207 Ok(match getter {
208 Getter::GetBool => match v {
209 Json::Bool(b) => GetterResult::Bool(*b),
210 other => return Err(format!("{what}: expected a boolean, found {}", describe(other))),
211 },
212 Getter::GetString => GetterResult::String(string(v, what)?),
213 Getter::GetInt | Getter::GetInt64 => GetterResult::Int(integer(v, what)?),
214 Getter::GetInt32 => GetterResult::Int32(integer(v, what)?),
215 Getter::GetSizeInBytes => GetterResult::SizeInBytes(integer(v, what)?),
216 Getter::GetDuration => GetterResult::Duration(integer(v, what)?),
217 Getter::GetFloat64 => GetterResult::Float64(float(v, what)?),
218 Getter::GetFloat64Slice => GetterResult::Float64Slice(nullable(v, |v| list(v, what, |x| float(x, what)))?),
219 Getter::GetStringSlice => GetterResult::StringSlice(nullable(v, |v| list(v, what, |x| string(x, what)))?),
220 Getter::GetStringMap => GetterResult::StringMap(nullable(v, |v| map(v, what, go_value))?),
221 Getter::GetStringMapString => {
222 GetterResult::StringMapString(nullable(v, |v| map(v, what, |x| string(x, what)))?)
223 }
224 Getter::GetStringMapStringSlice => {
225 GetterResult::StringMapStringSlice(map(v, what, |x| nullable(x, |x| list(x, what, |s| string(s, what))))?)
226 }
227 Getter::Get => GetterResult::Get(go_value(v)?),
228 Getter::ReadConfigSection => GetterResult::Section(map(v, what, go_value)?),
229 Getter::IsConfigured => match v {
230 Json::Bool(b) => GetterResult::IsConfigured(*b),
231 other => return Err(format!("{what}: expected a boolean, found {}", describe(other))),
232 },
233 })
234}