Fix UB caused by integer overflow in hash functions by casting int to unsigned

This commit is contained in:
Christian Mazakas
2022-01-10 14:47:16 -08:00
parent 7a64f1634f
commit 21244ab832
2 changed files with 18 additions and 15 deletions

View File

@@ -194,18 +194,19 @@ namespace test {
std::size_t hash_impl(object const& x) const std::size_t hash_impl(object const& x) const
{ {
int result; unsigned result;
switch (tag_) { switch (tag_) {
case 1: case 1:
result = x.tag1_; result = static_cast<unsigned>(x.tag1_);
break; break;
case 2: case 2:
result = x.tag2_; result = static_cast<unsigned>(x.tag2_);
break; break;
default: default:
result = x.tag1_ + x.tag2_; result =
static_cast<unsigned>(x.tag1_) + static_cast<unsigned>(x.tag2_);
} }
return static_cast<std::size_t>(result); return result;
} }
friend bool operator==(hash const& x1, hash const& x2) friend bool operator==(hash const& x1, hash const& x2)

View File

@@ -195,34 +195,36 @@ namespace test {
std::size_t operator()(object const& x) const std::size_t operator()(object const& x) const
{ {
int result; unsigned result;
switch (type_) { switch (type_) {
case 1: case 1:
result = x.tag1_; result = static_cast<unsigned>(x.tag1_);
break; break;
case 2: case 2:
result = x.tag2_; result = static_cast<unsigned>(x.tag2_);
break; break;
default: default:
result = x.tag1_ + x.tag2_; result =
static_cast<unsigned>(x.tag1_) + static_cast<unsigned>(x.tag2_);
} }
return static_cast<std::size_t>(result); return result;
} }
std::size_t operator()(movable const& x) const std::size_t operator()(movable const& x) const
{ {
int result; unsigned result;
switch (type_) { switch (type_) {
case 1: case 1:
result = x.tag1_; result = static_cast<unsigned>(x.tag1_);
break; break;
case 2: case 2:
result = x.tag2_; result = static_cast<unsigned>(x.tag2_);
break; break;
default: default:
result = x.tag1_ + x.tag2_; result =
static_cast<unsigned>(x.tag1_) + static_cast<unsigned>(x.tag2_);
} }
return static_cast<std::size_t>(result); return result;
} }
std::size_t operator()(int x) const std::size_t operator()(int x) const