From 61410e05ebcdb2b4eed97ed8d4f5e0864836e8a4 Mon Sep 17 00:00:00 2001 From: Linus Groh Date: Tue, 21 Dec 2021 21:27:14 +0100 Subject: [PATCH] LibJS: Add modulo(x, y) overload for Crypto::{Unsigned,Signed}BigInteger Just like with integral and floating numbers, doing it manually is error-prone: when we get a negative remainder, y has to be added to the result to match the spec's modulo. Solve this by just adding another (templated) overload to also permit using the function for LibCrypto BigInts. --- Userland/Libraries/LibJS/Runtime/AbstractOperations.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h index e9e6a7595d..de155d7e78 100644 --- a/Userland/Libraries/LibJS/Runtime/AbstractOperations.h +++ b/Userland/Libraries/LibJS/Runtime/AbstractOperations.h @@ -7,6 +7,7 @@ #pragma once #include +#include #include #include #include @@ -91,4 +92,13 @@ auto modulo(T x, U y) requires(IsArithmetic, IsArithmetic) } } +auto modulo(Crypto::BigInteger auto const& x, Crypto::BigInteger auto const& y) +{ + VERIFY(y != "0"_bigint); + auto result = x.divided_by(y).remainder; + if (result.is_negative()) + result = result.plus(y); + return result; +} + }