/*************************************************
* GNU MP Reducer Source File                     *
* (C) 1999-2004 The Botan Project                *
*************************************************/

#include <botan/eng_gmp.h>
#include <botan/gmp_wrap.h>
#include <gmp.h>

namespace Botan {

namespace {

/*************************************************
* GNU MP Reducer                                 *
*************************************************/
class GMP_Reducer : public ModularReducer
   {
   public:
      BigInt multiply(const BigInt&, const BigInt&) const;
      BigInt square(const BigInt&) const;
      BigInt reduce(const BigInt&) const;

      GMP_Reducer(const BigInt& mod) : ModularReducer(mod), n(mod) {}
   private:
      GNU_MPZ n;
   };

/*************************************************
* Modular Multiplication                         *
*************************************************/
BigInt GMP_Reducer::multiply(const BigInt& x_bn, const BigInt& y_bn) const
   {
   GNU_MPZ x(x_bn), y(y_bn);

   mpz_mul(x.value, x.value, y.value);
   mpz_mod(x.value, x.value, n.value);

   if((x_bn.sign() != y_bn.sign()) && (mpz_cmp_ui(x.value, 0) != 0))
      mpz_sub(x.value, n.value, x.value);

   return x.to_bigint();
   }

/*************************************************
* Modular Squaring                               *
*************************************************/
BigInt GMP_Reducer::square(const BigInt& x_bn) const
   {
   GNU_MPZ x(x_bn);
   mpz_mul(x.value, x.value, x.value);
   mpz_mod(x.value, x.value, n.value);
   return x.to_bigint();
   }

/*************************************************
* Modular Reduction                              *
*************************************************/
BigInt GMP_Reducer::reduce(const BigInt& x_bn) const
   {
   GNU_MPZ x(x_bn);
   mpz_mod(x.value, x.value, n.value);

   if((x_bn.is_negative()) && (mpz_cmp_ui(x.value, 0) != 0))
      mpz_sub(x.value, n.value, x.value);
   return x.to_bigint();
   }

}

/*************************************************
* Acquire a ModularReducer                       *
*************************************************/
ModularReducer* GMP_Engine::reducer(const BigInt& n, bool) const
   {
   return new GMP_Reducer(n);
   }

}
