From c3b243d95e3c200af7fe4533bec6ab8d9f8a27d9 Mon Sep 17 00:00:00 2001 From: Jack Lloyd Date: Thu, 23 Jul 2015 23:53:28 -0400 Subject: BigInt::to_u32bit failed on 32-bit integers. GH #220 --- doc/news.rst | 3 +++ src/lib/math/bigint/bigint.cpp | 2 +- src/tests/test_bigint.cpp | 48 +++++++++++++++++++++++++++++++++++++++++- 3 files changed, 51 insertions(+), 2 deletions(-) diff --git a/doc/news.rst b/doc/news.rst index 214e93962..41277760a 100644 --- a/doc/news.rst +++ b/doc/news.rst @@ -4,6 +4,9 @@ Release Notes Version 1.11.19, Not Yet Released ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ +* BigInt::to_u32bit would fail if the value was exactly 32 bits. + GH #220 + Version 1.11.18, 2015-07-05 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ diff --git a/src/lib/math/bigint/bigint.cpp b/src/lib/math/bigint/bigint.cpp index c9aa1d981..045117cbd 100644 --- a/src/lib/math/bigint/bigint.cpp +++ b/src/lib/math/bigint/bigint.cpp @@ -142,7 +142,7 @@ u32bit BigInt::to_u32bit() const { if(is_negative()) throw Encoding_Error("BigInt::to_u32bit: Number is negative"); - if(bits() >= 32) + if(bits() > 32) throw Encoding_Error("BigInt::to_u32bit: Number is too big to convert"); u32bit out = 0; diff --git a/src/tests/test_bigint.cpp b/src/tests/test_bigint.cpp index f6ae2a654..2bd7df2a7 100644 --- a/src/tests/test_bigint.cpp +++ b/src/tests/test_bigint.cpp @@ -17,7 +17,7 @@ #include #include - +#include #include #include #include @@ -26,6 +26,50 @@ using namespace Botan; namespace { +void test_failure(const char* function, const char* file, int line, + const std::string& what_failed) + { + std::cout << "FAIL " << function << " " << file << ":" << line << " " + << what_failed << std::endl; + } + +#define BOTAN_TEST(lhs, rhs, msg) try { \ + ++tests_run; \ + const auto lhs_val = lhs; \ + const auto rhs_val = rhs; \ + const bool cmp = lhs_val == rhs_val; \ + if(!cmp) \ + { \ + std::ostringstream fmt; \ + fmt << "expr '" << #lhs << " == " << #rhs << "' false, " \ + << "actually " << lhs_val << " " << rhs_val \ + << " (" << msg << ")"; \ + test_failure(BOTAN_CURRENT_FUNCTION, __FILE__, __LINE__, fmt.str()); \ + ++tests_failed; \ + } \ + } \ + catch(std::exception& e) \ + { \ + std::ostringstream fmt; \ + fmt << "exception '" << e.what() << "' (" << msg << ")"; \ + test_failure(BOTAN_CURRENT_FUNCTION, __FILE__, __LINE__, fmt.str()); \ + ++tests_failed; \ + } + +size_t test_bigint_to_u32bit() + { + size_t tests_run = 0, tests_failed = 0; + + for(size_t i = 0; i != 32; ++i) + { + const u32bit in = 1 << i; + BOTAN_TEST(in, BigInt(in).to_u32bit(), "In range round trips"); + } + + test_report("BigInt to_u32bit", tests_run, tests_failed); + return tests_failed; + } + void strip_comments(std::string& line) { if(line.find('#') != std::string::npos) @@ -303,6 +347,8 @@ size_t test_bigint() bool first = true; size_t counter = 0; + total_errors += test_bigint_to_u32bit(); + auto& rng = test_rng(); while(!test_data.eof()) -- cgit v1.2.3