From 6df16d053ed9b50c495c1f86cebd3c166eb107de Mon Sep 17 00:00:00 2001 From: Seth Hillbrand Date: Fri, 14 Jun 2024 17:26:21 -0700 Subject: [PATCH] Add specialization for unsigned scalar add/sub Adding/subtracting an unsigned scalar to a signed vector should maintain the same signed vector Fixes https://gitlab.com/kicad/code/kicad/-/issues/18212 --- libs/kimath/include/math/vector2d.h | 13 +++++++++++++ qa/tests/libs/kimath/math/test_vector2.cpp | 16 +++++++++++++--- 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/libs/kimath/include/math/vector2d.h b/libs/kimath/include/math/vector2d.h index 5c4cd71123..1b1ac85e6b 100644 --- a/libs/kimath/include/math/vector2d.h +++ b/libs/kimath/include/math/vector2d.h @@ -439,6 +439,13 @@ VECTOR2> operator+( const VECTOR2& aLHS, const U& aS } +template +VECTOR2 operator+( const VECTOR2& aVector, std::unsigned_integral auto aScalar ) +{ + return VECTOR2( aVector.x + aScalar, aVector.y + aScalar ); +} + + template VECTOR2> operator-( const VECTOR2& aLHS, const VECTOR2& aRHS ) { @@ -452,6 +459,12 @@ VECTOR2> operator-( const VECTOR2& aLHS, const U& aS return VECTOR2>( aLHS.x - aScalar, aLHS.y - aScalar ); } +template +VECTOR2 operator-( const VECTOR2& aVector, std::unsigned_integral auto aScalar ) +{ + return VECTOR2( aVector.x - aScalar, aVector.y - aScalar ); +} + template VECTOR2 VECTOR2::operator-() diff --git a/qa/tests/libs/kimath/math/test_vector2.cpp b/qa/tests/libs/kimath/math/test_vector2.cpp index 33825b819a..5ca2b0b79b 100644 --- a/qa/tests/libs/kimath/math/test_vector2.cpp +++ b/qa/tests/libs/kimath/math/test_vector2.cpp @@ -154,12 +154,22 @@ BOOST_AUTO_TEST_CASE( test_casting ) BOOST_CHECK_EQUAL( vlong, VECTOR2L( -5, -4 ) ); BOOST_CHECK_EQUAL( vfloat, VECTOR2( -5.0f, -4.0f ) ); + vint = vint - 1u; + vdouble = vdouble - 1u; + vlong = vlong - 1u; + vfloat = vfloat - 1u; + + BOOST_CHECK_EQUAL( vint, VECTOR2I( -6, -5 ) ); + BOOST_CHECK_EQUAL( vdouble, VECTOR2D( -6.0, -5.0 ) ); + BOOST_CHECK_EQUAL( vlong, VECTOR2L( -6, -5 ) ); + BOOST_CHECK_EQUAL( vfloat, VECTOR2( -6.0f, -5.0f ) ); + auto add = vint + vdouble; - BOOST_CHECK_EQUAL( add, VECTOR2D( -10.0, -8.0 ) ); + BOOST_CHECK_EQUAL( add, VECTOR2D( -12.0, -10.0 ) ); auto sub = vint - 2 * vlong; - BOOST_CHECK_EQUAL( sub.x, 5 ); - BOOST_CHECK_EQUAL( sub.y, 4 ); + BOOST_CHECK_EQUAL( sub.x, 6 ); + BOOST_CHECK_EQUAL( sub.y, 5 ); vunsigned = VECTOR2( std::numeric_limits::max(), std::numeric_limits::max() ); vint = VECTOR2I( vunsigned );