MCPcopy Create free account
hub / github.com/bitcoin/bitcoin / TestOverflow

Function TestOverflow

src/test/fuzz/overflow.cpp:17–38  ·  view source on GitHub ↗

Source from the content-addressed store, hash-verified

15//! Test overflow operations for type T using a wider type, W, to verify results.
16template <typename T, typename W>
17void TestOverflow(FuzzedDataProvider& fuzzed_data_provider)
18{
19 constexpr auto min{std::numeric_limits<T>::min()};
20 constexpr auto max{std::numeric_limits<T>::max()};
21 // Range needs to be at least twice as big to allow two numbers to be added without overflowing.
22 static_assert(min >= std::numeric_limits<W>::min() / 2);
23 static_assert(max <= std::numeric_limits<W>::max() / 2);
24
25 auto widen = [](T value) -> W { return value; };
26 auto clamp = [](W value) -> W { return std::clamp<W>(value, min, max); };
27 auto check = [](W value) -> std::optional<W> { if (value >= min && value <= max) return value; else return std::nullopt; };
28
29 const T i = fuzzed_data_provider.ConsumeIntegral<T>();
30 const T j = fuzzed_data_provider.ConsumeIntegral<T>();
31 const unsigned shift = fuzzed_data_provider.ConsumeIntegralInRange<unsigned>(0, std::numeric_limits<W>::digits - std::numeric_limits<T>::digits);
32
33 Assert(clamp(widen(i) + widen(j)) == SaturatingAdd(i, j));
34 Assert(check(widen(i) + widen(j)) == CheckedAdd(i, j));
35
36 Assert(clamp(widen(i) << shift) == SaturatingLeftShift(i, shift));
37 Assert(check(widen(i) << shift) == CheckedLeftShift(i, shift));
38}
39} // namespace
40
41FUZZ_TARGET(overflow)

Callers

nothing calls this directly

Calls 5

SaturatingAddFunction · 0.85
checkFunction · 0.85
CheckedAddFunction · 0.85
SaturatingLeftShiftFunction · 0.85
CheckedLeftShiftFunction · 0.85

Tested by

no test coverage detected