use serde_json::{Map, Value};
use crate::{new_error, Result};
#[track_caller]
pub(crate) fn test_value_as_str(values: &Map<String, Value>, key: &str, expected_value: &str) {
if let Err(e) = check_value_as_str(values, key, expected_value) {
panic!("{e:?}");
}
}
pub(crate) fn check_value_as_str(
values: &Map<String, Value>,
key: &str,
expected_value: &str,
) -> Result<()> {
let value = try_to_string(values, key)?;
if expected_value != value {
return Err(new_error!(
"expected value {} != value {}",
expected_value,
value
));
}
Ok(())
}
fn try_to_string<'a>(values: &'a Map<String, Value>, key: &'a str) -> Result<&'a str> {
if let Some(value) = values.get(key) {
if let Some(value_str) = value.as_str() {
Ok(value_str)
} else {
Err(new_error!("value with key {} was not a string", key))
}
} else {
Err(new_error!("value for key {} was not found", key))
}
}
pub(crate) type MapLookup<'a> = (&'a Map<String, Value>, &'a str);
pub(crate) fn try_to_strings<'a, const NUM: usize>(
lookups: [MapLookup<'a>; NUM],
) -> Result<[&'a str; NUM]> {
let mut ret_slc: [&'a str; NUM] = [""; NUM];
for (idx, lookup) in lookups.iter().enumerate() {
let map = lookup.0;
let key = lookup.1;
let val = try_to_string(map, key)?;
ret_slc[idx] = val
}
Ok(ret_slc)
}