Banned Patriot
Banned Patriot

Reputation: 21

Excessive memory operations, can I borrow as mutable all the way down the chain?

Is there a way to borrow as mutable all the way down the chain and return ownership to config? The memory operations here seem really excessive to update a single variable.

The code is working as expected but coming from high level languages it seems a little "hacky". Am I on the right track? The documentation is a little sparse on this library.

// Read Config File
let mut file = File::open("config.yaml").unwrap();
let mut contents = String::new();
file.read_to_string(&mut contents);

// Get Mutable 'endpoints'
let mut docs = YamlLoader::load_from_str(&contents).unwrap();
let mut config = docs[0].as_hash().unwrap().clone();
let mut endpoints = config[&Yaml::from_str("endpoints")].as_vec().unwrap().clone();


// Find the correct 'endpoint'
for (i, endpoint) in endpoints.clone().iter().enumerate() {
    let mut endpoint = endpoint.as_hash().unwrap().clone();
    
    if endpoint[&Yaml::from_str("name")] == Yaml::from_str("Current Name") {
        // Found the endpoint, let's update it's name
        endpoint.insert(Yaml::from_str("name"), Yaml::from_str("New Name"));
        endpoints.insert(i, Yaml::Hash(endpoint));
        config.insert(Yaml::from_str("endpoints"), Yaml::Array(endpoints.clone()));
    }
}

Upvotes: 1

Views: 95

Answers (1)

Banned Patriot
Banned Patriot

Reputation: 21

This is working, and I think solves all the pitfalls of my previous code.

let mut docs = YamlLoader::load_from_str(&contents).unwrap();
let mut config = docs[0].borrow_mut();

if let Yaml::Hash(hash_map) = config {
    if let Yaml::Array(endpoints) = hash_map[&Yaml::from_str("endpoints")].borrow_mut() {
        for endpoint in endpoints.iter_mut() {
            if let Yaml::Hash(endpoint) = endpoint.borrow_mut() {
                if endpoint[&Yaml::from_str("name")] == Yaml::from_str("Current Name") {
                    endpoint.insert(Yaml::from_str("name"), Yaml::from_str("New Name"));
                }
            }
        }
    }
}

Upvotes: 1

Related Questions