Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: Parse toml array of tables while preserving order
Hello,
I would like to parse the following toml while preserving the order.
[[custom]]
message = "Test"
command = "Echo test"
[banner]
[[custom]]
message = "Test 2"
command = "Echo test 2"
By preserving the order, I mean I want the output to be:
I want to parse this into Vec<Box<dyn Component>>
where custom and global can both be parsed into the trait Component.
I tried this, but map.next_entry::<CustomElement>()
gives me the entire array, not just the next element.
impl<'de> Deserialize<'de> for Config {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ConfigVisitor;
impl<'de> Visitor<'de> for ConfigVisitor {
type Value = Config;
fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
formatter.write_str("struct Config")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut result = Config {
components: vec![],
global: GlobalConfig::default(),
};
while let Some(key) = map.next_key()? {
match key {
Fields::Global => {
result.global = map.next_value()?;
}
Fields::Banner => {
result
.components
.push(Box::new(map.next_value::<Banner>()?));
}
Fields::CustomElement => {
println!("{:?}", map.next_entry::<CustomElement>()?);
}
}
}
Ok(result)
}
}
deserializer.deserialize_map(ConfigVisitor)
}
}
After a lot of searching and trying different crates, I was not able to find any way to do this.
The reason I want to preserve the order is that the order of the elements in the configuration controls the order in which the elements are printed.
The project and issue for context: Add the ability to write custom messages or commands. ยท Issue #37 ยท rust-motd/rust-motd ยท GitHub
1 post - 1 participant
๐ท๏ธ rust_feed