Skip to content

Commit

Permalink
solve include patch
Browse files Browse the repository at this point in the history
Signed-off-by: fzhedu <[email protected]>
  • Loading branch information
fzhedu committed Jun 17, 2022
1 parent 5a6f464 commit 718a82c
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
6 changes: 4 additions & 2 deletions libs/libcommon/include/common/arithmeticOverflow.h
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
#pragma once
#include <Core/Types.h>
#include <boost/multiprecision/cpp_int.hpp>

namespace common
{
using Int256 = boost::multiprecision::checked_int256_t;

template <typename T>
inline bool addOverflow(T x, T y, T & res)
{
Expand Down Expand Up @@ -106,7 +108,7 @@ inline bool mulOverflow(__int128 x, __int128 y, __int128 & res)
/// Int256 doesn't use the complement representation to express negative values, but uses an extra bit to express the sign flag,
/// the actual range of Int256 is from -(2^256 - 1) to 2^256 - 1, so 2^255 ~ 2^256-1 do not overflow Int256.
template <>
inline bool mulOverflow(DB::Int256 x, DB::Int256 y, DB::Int256 & res)
inline bool mulOverflow(Int256 x, Int256 y, Int256 & res)
{
try
{
Expand Down
17 changes: 16 additions & 1 deletion libs/libcommon/src/tests/gtest_arithmetic_overflow.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@

#include <common/arithmeticOverflow.h>
#include <gtest/gtest.h>

TEST(OVERFLOW_Suite, SimpleTest)
{
/// mul int128
Expand All @@ -34,4 +33,20 @@ TEST(OVERFLOW_Suite, SimpleTest)
/// 2^126 << 2 = 2^128
is_overflow = common::mulOverflow(int_126, __int128(4), res128);
ASSERT_EQ(is_overflow, true);

/// mul int256
common::Int256 res256;
/// 2^254
static constexpr common::Int256 int_254 = common::Int256((common::Int256(0x1) << 254));
/// 2^254 << 0 = 2^254
is_overflow = common::mulOverflow(int_254, common::Int256(1), res256);
ASSERT_EQ(is_overflow, false);

/// 2^254 << 1 = 2^255
is_overflow = common::mulOverflow(int_254, common::Int256(2), res256);
ASSERT_EQ(is_overflow, false); /// because the sign flag is processed by an extra bit, excluding from 256 bits of Int256.

/// 2^254 << 2 = 2^256
is_overflow = common::mulOverflow(int_254, common::Int256(4), res256);
ASSERT_EQ(is_overflow, true);
}

0 comments on commit 718a82c

Please sign in to comment.