Skip to content

Commit f4e7937

Browse files
authored
Merge pull request #154 from dlang-community/more-treemap-fixes
Fix a few problems with TreeMap.getOrAdd merged-on-behalf-of: Brian Schott <Hackerpilot@users.noreply.github.com>
2 parents 82587ee + a33f1dc commit f4e7937

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

src/containers/treemap.d

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -103,19 +103,25 @@ struct TreeMap(K, V, Allocator = Mallocator, alias less = "a < b",
103103
* Params:
104104
* key = the key to look up
105105
* value = the default value
106+
*
107+
* Returns: A pointer to the existing value, or a pointer to the inserted
108+
* value.
106109
*/
107-
auto getOrAdd(this This)(const K key, lazy V value) @safe
110+
auto getOrAdd(this This)(const K key, lazy V defaultValue)
108111
{
109112
alias CET = ContainerElementType!(This, V);
110113
auto tme = TreeMapElement(key);
111114
auto er = tree.equalRange(tme);
112115
if (er.empty)
113116
{
114-
insert(value, key);
115-
return value;
117+
// TODO: This does two lookups and should be made faster.
118+
tree.insert(TreeMapElement(key, defaultValue));
119+
return cast(CET*) &tree.equalRange(tme)._containersFront().value;
116120
}
117121
else
118-
return er.front.value;
122+
{
123+
return cast(CET*) &er._containersFront().value;
124+
}
119125
}
120126

121127
/**
@@ -412,14 +418,14 @@ version(emsi_containers_unittest) unittest
412418
{
413419
TreeMap!(int, int) map;
414420
auto p = map.getOrAdd(1, 1);
415-
assert(p == 1);
421+
assert(*p == 1);
416422
}
417423

418424
version(emsi_containers_unittest) unittest
419425
{
420426
import std.uuid : randomUUID;
421427
import std.range.primitives : walkLength;
422-
import std.stdio;
428+
//import std.stdio;
423429

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

0 commit comments

Comments
 (0)