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
{
int result;
unsigned result;
switch (tag_) {
case 1:
result = x.tag1_;
result = static_cast<unsigned>(x.tag1_);
break;
case 2:
result = x.tag2_;
result = static_cast<unsigned>(x.tag2_);
break;
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)

View File

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