diff options
| author | Laurenz <laurmaedje@gmail.com> | 2022-12-15 22:51:55 +0100 |
|---|---|---|
| committer | Laurenz <laurmaedje@gmail.com> | 2022-12-15 23:11:20 +0100 |
| commit | b6202b646a0d5ecced301d9bac8bfcaf977d7ee4 (patch) | |
| tree | 7d42cb50f9e66153e7e8b2217009684e25f54f42 /src/model/dict.rs | |
| parent | f3980c704544a464f9729cc8bc9f97d3a7454769 (diff) | |
Reflection for castables
Diffstat (limited to 'src/model/dict.rs')
| -rw-r--r-- | src/model/dict.rs | 23 |
1 files changed, 18 insertions, 5 deletions
diff --git a/src/model/dict.rs b/src/model/dict.rs index d54a0e82..6e014d7e 100644 --- a/src/model/dict.rs +++ b/src/model/dict.rs @@ -62,6 +62,13 @@ impl Dict { Arc::make_mut(&mut self.0).entry(key).or_default() } + /// Remove the value if the dictionary contains the given key. + pub fn take(&mut self, key: &str) -> StrResult<Value> { + Arc::make_mut(&mut self.0) + .remove(key) + .ok_or_else(|| format_eco!("missing key: {:?}", Str::from(key))) + } + /// Whether the dictionary contains a specific key. pub fn contains(&self, key: &str) -> bool { self.0.contains_key(key) @@ -80,11 +87,6 @@ impl Dict { } } - /// Remove the value if the dictionary contains the given key. - pub fn take(&mut self, key: &str) -> Option<Value> { - Arc::make_mut(&mut self.0).remove(key) - } - /// Clear the dictionary. pub fn clear(&mut self) { if Arc::strong_count(&self.0) == 1 { @@ -118,6 +120,17 @@ impl Dict { pub fn iter(&self) -> std::collections::btree_map::Iter<Str, Value> { self.0.iter() } + + /// Return an "unexpected key" error if there is any remaining pair. + pub fn finish(&self, expected: &[&str]) -> StrResult<()> { + if let Some((key, _)) = self.iter().next() { + let parts: Vec<_> = expected.iter().map(|s| format_eco!("\"{s}\"")).collect(); + let mut msg = format!("unexpected key {key:?}, valid keys are "); + crate::diag::comma_list(&mut msg, &parts, "and"); + return Err(msg.into()); + } + Ok(()) + } } /// The missing key access error message. |
