From 2f6799a42360a995b665244b922ebd3b2275c839 Mon Sep 17 00:00:00 2001 From: Benjamin Barenblat Date: Tue, 28 Jul 2015 10:38:10 -0400 Subject: Replace my bounds-checked numeric conversion with Boost’s MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Boost provides numeric_cast, which is much better than what I was using for safe numeric type conversion. This does introduce a Boost dependency, but that tends to be true of most nontrivial C++ programs, so it’s pretty reasonable. --- src/regex__FFI.cc | 32 +++++++++++--------------------- 1 file changed, 11 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/regex__FFI.cc b/src/regex__FFI.cc index 0ea3455..c2f8a4b 100644 --- a/src/regex__FFI.cc +++ b/src/regex__FFI.cc @@ -14,12 +14,10 @@ #include "regex__FFI.h" -#include - #include -#include #include +#include extern "C" { #include } @@ -54,18 +52,13 @@ void DeleteMatchResults(void* match_result, } // Bounds-checked numeric type conversion -template -U Number(uw_context* const context, const T input) { - Assert(context, input <= std::numeric_limits::max(), - "regex: detected overflow during numeric conversion"); - if (std::numeric_limits::is_signed == std::numeric_limits::is_signed) { - Assert(context, std::numeric_limits::lowest() <= input, - "regex: detected underflow during numeric conversion"); - } else if (std::numeric_limits::is_signed) { - Assert(context, 0 <= input, - "regex: detected underflow during numeric conversion"); +template +Target Number(uw_context* const context, Source arg) { + try { + return boost::numeric_cast(arg); + } catch (const boost::numeric::bad_numeric_cast& e) { + uw_error(context, FATAL, "regex: %s", e.what()); } - return static_cast(input); } } // namespace @@ -90,7 +83,7 @@ uw_Basis_int uw_Regex__FFI_n_subexpression_matches( } else { // At least one match occurred. Compute the number of parenthesized // subexpressions that got matched, and return it. - return Number(context, n_matches) - 1; + return Number(context, n_matches) - 1; } } @@ -101,18 +94,15 @@ uw_Basis_string uw_Regex__FFI_subexpression_match( const std::cmatch* const match_result = reinterpret_cast(match.result); const std::size_t match_index = - Number(context, match_index_signed); + Number(context, match_index_signed); Assert(context, match_index < match_result->size(), "regex: match does not exist"); const auto matched_substring = (*match_result)[match_index + 1]; // Save the matched substring. const std::size_t result_length = - Number( - context, - matched_substring.length()); + Number(context,matched_substring.length()); uw_Basis_string result = - reinterpret_cast( - uw_malloc(context, result_length + 1)); + reinterpret_cast(uw_malloc(context, result_length + 1)); std::strcpy(result, matched_substring.str().c_str()); return result; } -- cgit v1.2.3