From a1ded4dd5d6beb8f7e92f3aa20a0ec1644083323 Mon Sep 17 00:00:00 2001 From: mgros Date: Sun, 27 Sep 2026 23:43:53 +0200 Subject: [PATCH] Refactor YAML parsing functions --- src/definitions.rs | 52 +++++++++++++++++++--------------------------- 1 file changed, 21 insertions(+), 31 deletions(-) diff --git a/src/definitions.rs b/src/definitions.rs index 33b83391..ee3f72aa 100644 --- a/src/definitions.rs +++ b/src/definitions.rs @@ -234,44 +234,34 @@ fn build_values(definition: &Yaml, use_speech_defs: bool, path: &Path) -> Result return Ok(None); }); - fn get_vec_values(values: &Vec) -> Result> { - let mut result = Vec::with_capacity(values.len()); - for yaml_value in values { - let value = yaml_value.as_str() - .ok_or_else(|| anyhow!("list entry '{}' is not a string", yaml_to_type(yaml_value)))? - .to_string(); - result.push(value); - } - return Ok(result); + /// Convert a YAML string to an owned string; fail if the value is not a string. + fn yaml_string(value: &Yaml) -> Result { + Ok(value.as_str() + .ok_or_else(|| anyhow!("list entry '{}' is not a string", yaml_to_type(value)))? + .to_owned()) // &str -> String + } + + /// Convert a YAML sequence to strings; fail if any entry is not a string. + fn get_vec_values(values: &[Yaml]) -> Result> { + values.iter().map(yaml_string).collect() } + /// Convert null-valued YAML mapping keys to a set; fail on non-string keys or non-null values. fn get_set_values(values: &Hash) -> Result> { - let mut result = HashSet::with_capacity(2*values.len()); - for (key, value) in values { - let key = key.as_str() - .ok_or_else(|| anyhow!("list entry '{}' is not a string", yaml_to_type(key)))? - .to_string(); - if let Yaml::Null = value { - } else { - bail!("list entry '{}' is not a string", yaml_to_type(value)); + values.iter().map(|(key, value)| { + let key = yaml_string(key)?; + match value { + Yaml::Null => Ok(key), + _ => bail!("list entry '{}' is not a string", yaml_to_type(value)), } - result.insert(key); - } - return Ok(result); + }).collect() } + /// Convert a YAML mapping to string pairs; fail if any key or value is not a string. fn get_map_values(values: &Hash) -> Result> { - let mut result = HashMap::with_capacity(2*values.len()); - for (key, value) in values { - let key = key.as_str() - .ok_or_else(|| anyhow!("list entry '{}' is not a string", yaml_to_type(key)))? - .to_string(); - let value = value.as_str() - .ok_or_else(|| anyhow!("list entry '{}' is not a string", yaml_to_type(value)))? - .to_string(); - result.insert(key, value); - } - return Ok(result); + values.iter().map(|(key, value)| { + Ok((yaml_string(key)?, yaml_string(value)?)) + }).collect() } }