From ec09b914434b8dbc23bf6043b13ee5d5ecf4c2a6 Mon Sep 17 00:00:00 2001 From: Jay Berkenbilt Date: Thu, 4 Nov 2021 13:52:41 -0400 Subject: Add QIntC::range_check_subtract --- include/qpdf/QIntC.hh | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'include') diff --git a/include/qpdf/QIntC.hh b/include/qpdf/QIntC.hh index 2349e775..03da8853 100644 --- a/include/qpdf/QIntC.hh +++ b/include/qpdf/QIntC.hh @@ -250,6 +250,34 @@ namespace QIntC // QIntC = qpdf Integer Conversion throw std::range_error(msg.str()); } } + + template + void range_check_substract(T const& cur, T const& delta) + { + if ((delta >= 0) == (cur >= 0)) + { + return; + } + + if ((delta > 0) && + ((std::numeric_limits::min() + delta) > cur)) + { + std::ostringstream msg; + msg.imbue(std::locale::classic()); + msg << "subtracting " << delta << " from " << cur + << " would cause an integer underflow"; + throw std::range_error(msg.str()); + } + else if ((delta < 0) && + ((std::numeric_limits::max() + delta) < cur)) + { + std::ostringstream msg; + msg.imbue(std::locale::classic()); + msg << "subtracting " << delta << " from " << cur + << " would cause an integer overflow"; + throw std::range_error(msg.str()); + } + } }; #endif // QINTC_HH -- cgit v1.2.3-54-g00ecf