yaml-rust icon indicating copy to clipboard operation
yaml-rust copied to clipboard

Mutable access.

Open AnthonyJacob opened this issue 6 years ago • 2 comments

It would beneficial to expose mutable API, to make preproccessing of loaded YAML easier.

I have these two on my mind:

  • IndexMut
  • IntoIterator for &mut Yaml

AnthonyJacob avatar Mar 13 '19 20:03 AnthonyJacob

As a workaround I'm:

///Using path for error handling
fn replace(path: &Path, yaml: Yaml, keys: &[&str], value: &str) -> Result<Yaml, ConfigurationError> {
    match keys.first() {
        None => return Ok(Yaml::String(value.into())),
        Some(key) => {
            match yaml {
                Yaml::Hash(mut hash) => {
                    let removed_child = remove(path, &mut hash, key)?;
                    let new_child = replace(path, removed_child, &keys[1..], value)?;
                    hash.insert(Yaml::String(key.to_string()), new_child);
                    Ok(Yaml::Hash(hash))
                },
                _ => Err(bad_structure(path, format!("Expected hash when looking up key: {}", key)))
            }
        }
    }
}

fn remove(path: &Path, hash: &mut yaml_rust::yaml::Hash, key: &str) -> Result<Yaml, ConfigurationError> {
    Ok(hash.remove(&Yaml::String(key.into())).ok_or_else(|| bad_structure(path, format!("Missing key: {}", key)))?)
}

JamesSharkey avatar Apr 26 '21 17:04 JamesSharkey

Hi - old issue, but I have a fork implementing this. It adds as_<type>_mut methods to the Yaml public API. It does not currently implement the traits mentioned above, but those appear to be fairly thin wrappers of the as_<type>(_mut)? methods and can be added if necessary. @chyh1990, tell me if it's worth a PR!

oldaccountdeadname avatar Sep 30 '21 00:09 oldaccountdeadname