Skip to content

Commit

Permalink
Merge pull request #154 from dlang-community/more-treemap-fixes
Browse files Browse the repository at this point in the history
Fix a few problems with TreeMap.getOrAdd
merged-on-behalf-of: Brian Schott <[email protected]>
  • Loading branch information
dlang-bot authored Oct 10, 2019
2 parents 82587ee + a33f1dc commit f4e7937
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/containers/treemap.d
Original file line number Diff line number Diff line change
Expand Up @@ -103,19 +103,25 @@ struct TreeMap(K, V, Allocator = Mallocator, alias less = "a < b",
* Params:
* key = the key to look up
* value = the default value
*
* Returns: A pointer to the existing value, or a pointer to the inserted
* value.
*/
auto getOrAdd(this This)(const K key, lazy V value) @safe
auto getOrAdd(this This)(const K key, lazy V defaultValue)
{
alias CET = ContainerElementType!(This, V);
auto tme = TreeMapElement(key);
auto er = tree.equalRange(tme);
if (er.empty)
{
insert(value, key);
return value;
// TODO: This does two lookups and should be made faster.
tree.insert(TreeMapElement(key, defaultValue));
return cast(CET*) &tree.equalRange(tme)._containersFront().value;
}
else
return er.front.value;
{
return cast(CET*) &er._containersFront().value;
}
}

/**
Expand Down Expand Up @@ -412,14 +418,14 @@ version(emsi_containers_unittest) unittest
{
TreeMap!(int, int) map;
auto p = map.getOrAdd(1, 1);
assert(p == 1);
assert(*p == 1);
}

version(emsi_containers_unittest) unittest
{
import std.uuid : randomUUID;
import std.range.primitives : walkLength;
import std.stdio;
//import std.stdio;

auto hm = TreeMap!(string, int)();
foreach (i; 0 .. 1_000_000)
Expand Down

0 comments on commit f4e7937

Please sign in to comment.