From a58121e893e1753c7011d25893918b4419a04457 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Vladim=C3=ADr=20Vondru=C5=A1?= Date: Fri, 3 Apr 2015 23:39:49 +0200 Subject: [PATCH] Math: added div() function. --- src/Magnum/Math/Functions.h | 20 ++++++++++++++++++++ src/Magnum/Math/Test/FunctionsTest.cpp | 10 ++++++++++ 2 files changed, 30 insertions(+) diff --git a/src/Magnum/Math/Functions.h b/src/Magnum/Math/Functions.h index c6e7ae14e..4ccb2db1b 100644 --- a/src/Magnum/Math/Functions.h +++ b/src/Magnum/Math/Functions.h @@ -79,6 +79,26 @@ UnsignedInt MAGNUM_EXPORT log2(UnsignedInt number); */ UnsignedInt MAGNUM_EXPORT log(UnsignedInt base, UnsignedInt number); +/** +@brief Integer division with remainder + +Example usage: +@code +Int quotient, remainder; +std::tie(quotient, remainder) = Math::div(57, 6); // {9, 3} +@endcode +Equivalent to the following, but possibly done in a single CPU instruction: +@code +Int quotient = 57/6; +Int remainder = 57%6; +@endcode +*/ +template std::pair div(Integral x, Integral y) { + static_assert(std::is_integral{}, "Math::div(): not an integral type"); + const auto result = std::div(x, y); + return {result.quot, result.rem}; +} + /** @todo Can't trigonometric functions be done with only one overload? */ /** @brief Sine */ diff --git a/src/Magnum/Math/Test/FunctionsTest.cpp b/src/Magnum/Math/Test/FunctionsTest.cpp index 564bff971..95b71cbee 100644 --- a/src/Magnum/Math/Test/FunctionsTest.cpp +++ b/src/Magnum/Math/Test/FunctionsTest.cpp @@ -23,6 +23,7 @@ DEALINGS IN THE SOFTWARE. */ +#include #include #include "Magnum/Math/Functions.h" @@ -65,6 +66,7 @@ struct FunctionsTest: Corrade::TestSuite::Tester { void pow(); void log(); void log2(); + void div(); void trigonometric(); void trigonometricWithBase(); }; @@ -111,6 +113,7 @@ FunctionsTest::FunctionsTest() { &FunctionsTest::pow, &FunctionsTest::log, &FunctionsTest::log2, + &FunctionsTest::div, &FunctionsTest::trigonometric, &FunctionsTest::trigonometricWithBase}); } @@ -410,6 +413,13 @@ void FunctionsTest::log2() { CORRADE_COMPARE(Math::log2(2153), 11); } +void FunctionsTest::div() { + Int quotient, remainder; + std::tie(quotient, remainder) = Math::div(57, 6); + CORRADE_COMPARE(quotient, 9); + CORRADE_COMPARE(remainder, 3); +} + void FunctionsTest::trigonometric() { CORRADE_COMPARE(Math::sin(Deg(30.0f)), 0.5f); CORRADE_COMPARE(Math::sin(Rad(Constants::pi()/6)), 0.5f);