diff options
| author | Michael Lohr <michael@lohr.dev> | 2023-05-03 12:34:35 +0200 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2023-05-03 12:34:35 +0200 |
| commit | ffad8516af0b91121dc0761c8026e0a12939a7d4 (patch) | |
| tree | ada5c6b5510b5f509997ccf5308a9cafc8618990 /src/eval/dict.rs | |
| parent | ca8462642a96ec282afeb0774b6d5daf546ac236 (diff) | |
Implement default values for at() (#995)
Diffstat (limited to 'src/eval/dict.rs')
| -rw-r--r-- | src/eval/dict.rs | 22 |
1 files changed, 18 insertions, 4 deletions
diff --git a/src/eval/dict.rs b/src/eval/dict.rs index b137f03c..1b28a6ba 100644 --- a/src/eval/dict.rs +++ b/src/eval/dict.rs @@ -53,16 +53,20 @@ impl Dict { self.0.len() as i64 } - /// Borrow the value the given `key` maps to. - pub fn at(&self, key: &str) -> StrResult<&Value> { - self.0.get(key).ok_or_else(|| missing_key(key)) + /// Borrow the value the given `key` maps to, + pub fn at<'a>( + &'a self, + key: &str, + default: Option<&'a Value>, + ) -> StrResult<&'a Value> { + self.0.get(key).or(default).ok_or_else(|| missing_key_no_default(key)) } /// Mutably borrow the value the given `key` maps to. pub fn at_mut(&mut self, key: &str) -> StrResult<&mut Value> { Arc::make_mut(&mut self.0) .get_mut(key) - .ok_or_else(|| missing_key(key)) + .ok_or_else(|| missing_key_no_default(key)) } /// Remove the value if the dictionary contains the given key. @@ -218,3 +222,13 @@ impl<'a> IntoIterator for &'a Dict { fn missing_key(key: &str) -> EcoString { eco_format!("dictionary does not contain key {:?}", Str::from(key)) } + +/// The missing key access error message when no default was fiven. +#[cold] +fn missing_key_no_default(key: &str) -> EcoString { + eco_format!( + "dictionary does not contain key {:?} \ + and no default value was specified", + Str::from(key) + ) +} |
