-
Notifications
You must be signed in to change notification settings - Fork 13.1k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Implement HashMap.find_with_or_insert_with() #14196
Merged
Merged
Changes from 3 commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
460b552
Reinstate HashMap.mangle().
chris-morgan acdce63
Tidy up the HashMap.mangle example.
chris-morgan 73dc1e0
Rename HashMap.mangle to find_with_or_insert_with.
chris-morgan 5b13ddb
Use assertions in find_with_or_insert_with example
chris-morgan ff98afe
Work around parse error caused by #14240.
chris-morgan File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -1239,31 +1239,14 @@ impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { | |
/// Return the value corresponding to the key in the map, or insert | ||
/// and return the value if it doesn't exist. | ||
pub fn find_or_insert<'a>(&'a mut self, k: K, v: V) -> &'a mut V { | ||
let hash = self.make_hash(&k); | ||
match self.search_hashed(&hash, &k) { | ||
Some(idx) => { | ||
let (_, v_ref) = self.table.read_mut(&idx); | ||
v_ref | ||
}, | ||
None => self.insert_hashed(hash, k, v) | ||
} | ||
self.find_with_or_insert_with(k, v, |_k, _v, _a| (), |_k, a| a) | ||
} | ||
|
||
/// Return the value corresponding to the key in the map, or create, | ||
/// insert, and return a new value if it doesn't exist. | ||
pub fn find_or_insert_with<'a>(&'a mut self, k: K, f: |&K| -> V) | ||
-> &'a mut V { | ||
let hash = self.make_hash(&k); | ||
match self.search_hashed(&hash, &k) { | ||
Some(idx) => { | ||
let (_, v_ref) = self.table.read_mut(&idx); | ||
v_ref | ||
}, | ||
None => { | ||
let v = f(&k); | ||
self.insert_hashed(hash, k, v) | ||
} | ||
} | ||
self.find_with_or_insert_with(k, (), |_k, _v, _a| (), |k, _a| f(k)) | ||
} | ||
|
||
/// Insert a key-value pair into the map if the key is not already present. | ||
|
@@ -1275,12 +1258,66 @@ impl<K: TotalEq + Hash<S>, V, S, H: Hasher<S>> HashMap<K, V, H> { | |
v: V, | ||
f: |&K, &mut V|) | ||
-> &'a mut V { | ||
self.find_with_or_insert_with(k, v, |k, v, _a| f(k, v), |_k, a| a) | ||
} | ||
|
||
/// Modify and return the value corresponding to the key in the map, or | ||
/// insert and return a new value if it doesn't exist. | ||
/// | ||
/// This method allows for all insertion behaviours of a hashmap; | ||
/// see methods like `insert`, `find_or_insert` and | ||
/// `insert_or_update_with` for less general and more friendly | ||
/// variations of this. | ||
/// | ||
/// # Example | ||
/// | ||
/// ```rust | ||
/// use collections::HashMap; | ||
/// | ||
/// // map some strings to vectors of strings | ||
/// let mut map = HashMap::new(); | ||
/// map.insert("a key", vec!["value"]); | ||
/// map.insert("z key", vec!["value"]); | ||
/// | ||
/// let new = vec!["a key", "b key", "z key"]; | ||
/// | ||
/// for k in new.move_iter() { | ||
/// map.find_with_or_insert_with( | ||
/// k, "new value", | ||
/// // if the key does exist either prepend or append this | ||
/// // new value based on the first letter of the key. | ||
/// |key, already, new| { | ||
/// if key.as_slice().starts_with("z") { | ||
/// already.unshift(new); | ||
/// } else { | ||
/// already.push(new); | ||
/// } | ||
/// }, | ||
/// // if the key doesn't exist in the map yet, add it in | ||
/// // the obvious way. | ||
/// |_k, v| vec![v], | ||
/// ); | ||
/// } | ||
/// | ||
/// for (k, v) in map.iter() { | ||
/// println!("{} -> {}", *k, *v); | ||
/// } | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This would be a little clearer if you asserted equality instead of printing, because I can't see what it prints without actually running the code locally. Instead you could use something like assert_eq!(map.len(), 3);
assert_eq!(map.get("a key"), vec!["value", "new value"]);
asesrt_eq!(map.get("b key"), vec!["value", "new value"]);
assert_eq!(map.get("z key"), vec!["new value", "value"]); |
||
/// ``` | ||
pub fn find_with_or_insert_with<'a, A>(&'a mut self, | ||
k: K, | ||
a: A, | ||
found: |&K, &mut V, A|, | ||
not_found: |&K, A| -> V) | ||
-> &'a mut V { | ||
let hash = self.make_hash(&k); | ||
match self.search_hashed(&hash, &k) { | ||
None => self.insert_hashed(hash, k, v), | ||
None => { | ||
let v = not_found(&k, a); | ||
self.insert_hashed(hash, k, v) | ||
}, | ||
Some(idx) => { | ||
let (_, v_ref) = self.table.read_mut(&idx); | ||
f(&k, v_ref); | ||
found(&k, v_ref, a); | ||
v_ref | ||
} | ||
} | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This example may be clearer without all the
StrBuf
, if they're replaced with just&str
, does it end up working out?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I don't see how it would. Prepending/appending the strings would have to produce a
StrBuf
as a result (as it must allocate), so the value type can't be&str
.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I believe that
already
has type&mut Vec<StrBuf>
, appending/unshifting on a vector, not a string.There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ah hah, you're right. I didn't read carefully enough.