spin_locked_app/
values.rsuse serde::Serialize;
use serde_json::Value;
pub type ValuesMap = serde_json::Map<String, Value>;
#[derive(Default)]
pub struct ValuesMapBuilder(ValuesMap);
impl ValuesMapBuilder {
pub fn new() -> Self {
Self::default()
}
pub fn try_from<S: Serialize>(s: S) -> serde_json::Result<Self> {
let value = serde_json::to_value(s)?;
let map = serde_json::from_value(value)?;
Ok(Self(map))
}
pub fn string(&mut self, key: impl Into<String>, value: impl Into<String>) -> &mut Self {
let value = value.into();
if value.is_empty() {
return self;
}
self.entry(key, value)
}
pub fn string_option(
&mut self,
key: impl Into<String>,
value: Option<impl Into<String>>,
) -> &mut Self {
if let Some(value) = value {
self.0.insert(key.into(), value.into().into());
}
self
}
pub fn string_array<T: Into<String>>(
&mut self,
key: impl Into<String>,
iter: impl IntoIterator<Item = T>,
) -> &mut Self {
let entries = iter.into_iter().map(|s| s.into()).collect::<Vec<_>>();
if entries.is_empty() {
return self;
}
self.entry(key, entries)
}
pub fn entry(&mut self, key: impl Into<String>, value: impl Into<Value>) -> &mut Self {
self.0.insert(key.into(), value.into());
self
}
pub fn serializable(
&mut self,
key: impl Into<String>,
value: impl Serialize,
) -> serde_json::Result<&mut Self> {
let value = serde_json::to_value(value)?;
if !value.is_null() {
self.0.insert(key.into(), value);
}
Ok(self)
}
pub fn build(self) -> ValuesMap {
self.0
}
pub fn take(&mut self) -> ValuesMap {
std::mem::take(&mut self.0)
}
}