Add lookup_mut method for mutable access #88
Conversation
Mutable access may sometimes be desired in order to change values in the toml table. This can be used for dynamic configurations which will be easy to modify and store. lookup_mut requires a recursive method due to the borrow checker not allowing to have more than one mutable reference in the same scope.
Thanks! Could this have the same non-recursive implementation as |
I've tried but the borrow checker seems to complain. Asked in the irc and someone suggested a recursive solution. I think it's because there are two mutable references generated whilst the cur_value gets overwritten. Maybe the borrow checker chokes on this. |
Ah yeah sometimes you have to do something like: let tmp = value;
value = &mut tmp.foo (or something like that) Do you have a non-recursive version of the code I could peek at? |
This yields the same error as before. Unfortunately I didn't commit any attempts at the non-recursive solution. |
I think this should work: pub fn lookup_mut(&mut self, path: &str) -> Option<&mut Value> {
let mut cur = self;
if path.len() == 0 {
return Some(cur)
}
for key in path.split('.') {
let tmp = cur;
match *tmp {
Value::Table(ref mut hm) => {
match hm.get_mut(key) {
Some(v) => cur = v,
None => return None
}
}
Value::Array(ref mut v) => {
match key.parse::<usize>().ok() {
Some(idx) if idx < v.len() => cur = &mut v[idx],
_ => return None
}
}
_ => return None
}
}
Some(cur)
} |
Seems like it does! |
Oh I was actually thinking you may want to use that for this PR :) Could you add some various tests here and there for the method as well? |
Also include some tests simply by copying and modifying the other tests for lookup.
I think this should do it :) |
Thanks! Yeah I'd be fine using the same TOML syntax for key lookups, just haven't implemented it yet :) |
Mutable access may sometimes be desired in order to change values
in the toml table. This can be used for dynamic configurations which
will be easy to modify and store.
lookup_mut requires a recursive method due to the borrow checker
not allowing to have more than one mutable reference in the same
scope.