Feature Request: "upsert_with" or "Entry::map_or_insert_with"
szbergeron opened this issue · 0 comments
I'm currently trying to recursively merge trees where copying nodes is an expensive operation.
I came across a use case for a function on Entry that takes a closure with the signature FnOnce(Option<V>) -> V
so that if the value exists, we can apply a computationally minimally expensive merge operation, but if it does not exist then we can insert with the value that was moved by the closure.
This is equivalent to Entry::and_modify(|prior| merge(prior, value)).or_insert(value)
for copy types, but allows flexibility for non-copy types of value
where the move into the first closure prevents reusing it for the or_insert
call.
Using this api, the example from before becomes:
Entry::upsert_with(move |prior| {
match prior {
Some(prior) => merge(prior, value),
None => value,
}
}
where merge: Fn(Node, Node) -> Node