From d5fbbb843dc4606c375765d9e39497011e879045 Mon Sep 17 00:00:00 2001 From: Xuanwo Date: Wed, 18 May 2022 14:11:37 +0800 Subject: [PATCH] feat: Add deserialize_map support (#11) Signed-off-by: Xuanwo --- src/de.rs | 10 +++------- src/value.rs | 41 ++++++++++++++++++++++++++++++++++++++--- 2 files changed, 41 insertions(+), 10 deletions(-) diff --git a/src/de.rs b/src/de.rs index b1be3aa..082f3a1 100644 --- a/src/de.rs +++ b/src/de.rs @@ -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)) } @@ -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)) } @@ -601,7 +598,6 @@ mod tests { } #[test] - #[ignore] fn test_from_env_as_map() { let _ = env_logger::try_init(); diff --git a/src/value.rs b/src/value.rs index 5c2aa6f..92f8a2a 100644 --- a/src/value.rs +++ b/src/value.rs @@ -46,9 +46,29 @@ impl Node { self.0 } - /// Get children from node. - pub fn children(&self) -> &BTreeMap { - &self.1 + pub fn flatten(&self, prefix: &str) -> Vec { + 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 @@ -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"] + ); + } }