use std::collections::BTreeMap;
use serde::de::{MapAccess, Visitor};
use serde::ser::SerializeStruct;
use serde::{Deserialize, Serialize, Serializer};
use crate::results::MinimalFallback;
#[derive(Debug, Clone)]
pub enum IniTypeInfo {
Scalar(String),
Table(BTreeMap<String, IniTypeInfo>),
}
impl Serialize for IniTypeInfo {
fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
match self {
IniTypeInfo::Scalar(x) => x.serialize(s),
IniTypeInfo::Table(m) => m.serialize(s),
}
}
}
impl<'de> Deserialize<'de> for IniTypeInfo {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
d.deserialize_any(IniTypeInfoVisitor)
}
}
struct IniTypeInfoVisitor;
impl<'de> Visitor<'de> for IniTypeInfoVisitor {
type Value = IniTypeInfo;
fn expecting(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
f.write_str("a string or an object (section table)")
}
fn visit_str<E: serde::de::Error>(self, v: &str) -> Result<Self::Value, E> {
Ok(IniTypeInfo::Scalar(v.to_string()))
}
fn visit_string<E: serde::de::Error>(self, v: String) -> Result<Self::Value, E> {
Ok(IniTypeInfo::Scalar(v))
}
fn visit_map<A: MapAccess<'de>>(self, mut map: A) -> Result<Self::Value, A::Error> {
let mut table = BTreeMap::new();
while let Some(k) = map.next_key::<String>()? {
let v = map.next_value::<IniTypeInfo>()?;
table.insert(k, v);
}
Ok(IniTypeInfo::Table(table))
}
}
#[derive(Debug, Clone, Deserialize, Default)]
pub struct IniMetadata {
pub file_size: Option<usize>,
pub section_count: Option<usize>,
pub key_count: Option<usize>,
pub comment_count: Option<usize>,
pub max_depth: Option<usize>,
#[serde(skip_serializing_if = "Option::is_none")]
pub schema: Option<BTreeMap<String, IniTypeInfo>>,
}
impl Serialize for IniMetadata {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut state = serializer.serialize_struct("IniMetadata", 6)?;
crate::serialize_optional!(state, self.file_size, "file_size");
crate::serialize_optional!(state, self.section_count, "section_count");
crate::serialize_optional!(state, self.key_count, "key_count");
crate::serialize_optional!(state, self.comment_count, "comment_count");
crate::serialize_optional!(state, self.max_depth, "max_depth");
crate::serialize_optional!(state, self.schema, "schema");
state.end()
}
}
crate::impl_minimal_fallback!(IniMetadata, file_size);