Skip to content

Commit

Permalink
feat: Add deserialize_map support (#11)
Browse files Browse the repository at this point in the history
Signed-off-by: Xuanwo <github@xuanwo.io>
  • Loading branch information
Xuanwo authored May 18, 2022
1 parent 84381db commit d5fbbb8
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 10 deletions.
10 changes: 3 additions & 7 deletions src/de.rs
Original file line number Diff line number Diff line change
Expand Up @@ -253,13 +253,9 @@ impl<'de> de::Deserializer<'de> for Deserializer {
where
V: Visitor<'de>,
{
debug!(
"deserialize map: {:?}, {:?}",
&self.0.value(),
&self.0.children()
);
debug!("deserialize map: {:#?}", &self.0);

let keys = self.0.children().keys().map(|v| v.to_string()).collect();
let keys = self.0.flatten("");
vis.visit_map(MapAccessor::new(keys, self.0))
}

Expand All @@ -278,6 +274,7 @@ impl<'de> de::Deserializer<'de> for Deserializer {
);

let keys = fields.iter().map(|v| v.to_string()).collect();
debug!("flatten keys: {:?}", keys);
vis.visit_map(MapAccessor::new(keys, self.0))
}

Expand Down Expand Up @@ -601,7 +598,6 @@ mod tests {
}

#[test]
#[ignore]
fn test_from_env_as_map() {
let _ = env_logger::try_init();

Expand Down
41 changes: 38 additions & 3 deletions src/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,29 @@ impl Node {
self.0
}

/// Get children from node.
pub fn children(&self) -> &BTreeMap<String, Node> {
&self.1
pub fn flatten(&self, prefix: &str) -> Vec<String> {
let mut m = Vec::new();

for (key, value) in self.1.iter() {
let prefix_key = if prefix.is_empty() {
key.to_string()
} else {
format!("{prefix}_{key}")
};

if !value.0.is_empty() {
m.push(prefix_key.clone())
}
if !value.1.is_empty() {
m.push(prefix_key.clone());
m.extend(value.flatten(&prefix_key))
}
}

m.sort();
m.dedup();

m
}

/// Get node value full key name
Expand Down Expand Up @@ -171,4 +191,19 @@ mod tests {
)
)
}

#[test]
fn test_flatten() {
let mut root = Node::new("");

root.push("a", "Hello, World!");
root.push("a_b_c_d", "Hello, World!");
root.push("a_b_c_e", "Hello, Mars!");
root.push("a_b_f", "Hello, Moon!");

assert_eq!(
root.flatten(""),
vec!["a", "a_b", "a_b_c", "a_b_c_d", "a_b_c_e", "a_b_f"]
);
}
}

0 comments on commit d5fbbb8

Please sign in to comment.