Skip to content

Commit 3dc8091

Browse files
authored
Merge pull request #10703 from VPanteleev-S7/json-tohash
std.json: Add JSONValue.toHash
2 parents 1fab9ac + 6beff68 commit 3dc8091

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

std/json.d

+47
Original file line numberDiff line numberDiff line change
@@ -1070,6 +1070,41 @@ struct JSONValue
10701070
}
10711071
}
10721072

1073+
/// Calculate a numerical hash value for this value,
1074+
/// allowing `JSONValue` to be used in associative arrays.
1075+
hash_t toHash() const @nogc nothrow pure @trusted
1076+
{
1077+
final switch (type_tag)
1078+
{
1079+
case JSONType.integer:
1080+
return hashOf(store.integer);
1081+
case JSONType.uinteger:
1082+
return hashOf(store.uinteger);
1083+
case JSONType.float_:
1084+
return hashOf(store.floating);
1085+
case JSONType.string:
1086+
return hashOf(store.str);
1087+
case JSONType.object:
1088+
hash_t result = hashOf(type_tag);
1089+
if (!store.object.isOrdered)
1090+
foreach (ref pair; store.object.unordered.byKeyValue)
1091+
result ^= hashOf(pair.key, pair.value.toHash());
1092+
else
1093+
foreach (ref pair; store.object.ordered)
1094+
result ^= hashOf(pair.key, pair.value.toHash());
1095+
return result;
1096+
case JSONType.array:
1097+
hash_t result = hashOf(type_tag);
1098+
foreach (ref v; store.array)
1099+
result = hashOf(v, result);
1100+
return result;
1101+
case JSONType.true_:
1102+
case JSONType.false_:
1103+
case JSONType.null_:
1104+
return hashOf(type_tag);
1105+
}
1106+
}
1107+
10731108
///
10741109
@safe unittest
10751110
{
@@ -2748,3 +2783,15 @@ pure nothrow @safe unittest
27482783

27492784
assert(app.data == s, app.data);
27502785
}
2786+
2787+
@safe unittest
2788+
{
2789+
bool[JSONValue] aa;
2790+
aa[JSONValue("test")] = true;
2791+
assert(parseJSON(`"test"`) in aa);
2792+
assert(parseJSON(`"boo"`) !in aa);
2793+
2794+
aa[JSONValue(int(5))] = true;
2795+
assert(JSONValue(int(5)) in aa);
2796+
assert(JSONValue(uint(5)) in aa);
2797+
}

0 commit comments

Comments
 (0)