Botan  1.10.9
gmp_wrap.cpp
Go to the documentation of this file.
1 /*
2 * GMP Wrapper
3 * (C) 1999-2007 Jack Lloyd
4 *
5 * Distributed under the terms of the Botan license
6 */
7 
8 #include <botan/internal/gmp_wrap.h>
9 
10 #define GNU_MP_VERSION_CODE_FOR(a,b,c) ((a << 16) | (b << 8) | (c))
11 
12 #define GNU_MP_VERSION_CODE \
13  GNU_MP_VERSION_CODE_FOR(__GNU_MP_VERSION, __GNU_MP_VERSION_MINOR, \
14  __GNU_MP_VERSION_PATCHLEVEL)
15 
16 #if GNU_MP_VERSION_CODE < GNU_MP_VERSION_CODE_FOR(4,1,0)
17  #error Your GNU MP install is too old, upgrade to 4.1 or later
18 #endif
19 
20 namespace Botan {
21 
22 /*
23 * GMP_MPZ Constructor
24 */
26  {
27  mpz_init(value);
28  if(in != 0)
29  mpz_import(value, in.sig_words(), -1, sizeof(word), 0, 0, in.data());
30  }
31 
32 /*
33 * GMP_MPZ Constructor
34 */
35 GMP_MPZ::GMP_MPZ(const byte in[], size_t length)
36  {
37  mpz_init(value);
38  mpz_import(value, length, 1, 1, 0, 0, in);
39  }
40 
41 /*
42 * GMP_MPZ Copy Constructor
43 */
45  {
46  mpz_init_set(value, other.value);
47  }
48 
49 /*
50 * GMP_MPZ Destructor
51 */
53  {
54  mpz_clear(value);
55  }
56 
57 /*
58 * GMP_MPZ Assignment Operator
59 */
61  {
62  mpz_set(value, other.value);
63  return (*this);
64  }
65 
66 /*
67 * Export the mpz_t as a bytestring
68 */
69 void GMP_MPZ::encode(byte out[], size_t length) const
70  {
71  size_t dummy = 0;
72  mpz_export(out + (length - bytes()), &dummy, 1, 1, 0, 0, value);
73  }
74 
75 /*
76 * Return the number of significant bytes
77 */
78 size_t GMP_MPZ::bytes() const
79  {
80  return ((mpz_sizeinbase(value, 2) + 7) / 8);
81  }
82 
83 /*
84 * GMP to BigInt Conversions
85 */
87  {
88  BigInt out(BigInt::Positive, (bytes() + sizeof(word) - 1) / sizeof(word));
89  size_t dummy = 0;
90  mpz_export(out.get_reg(), &dummy, -1, sizeof(word), 0, 0, value);
91 
92  if(mpz_sgn(value) < 0)
93  out.flip_sign();
94 
95  return out;
96  }
97 
98 }
size_t sig_words() const
Definition: bigint.h:290
SecureVector< word > & get_reg()
Definition: bigint.h:325
void encode(byte[], size_t) const
Definition: gmp_wrap.cpp:69
unsigned char byte
Definition: types.h:22
GMP_MPZ(const GMP_MPZ &)
Definition: gmp_wrap.cpp:44
const word * data() const
Definition: bigint.h:317
mpz_t value
Definition: gmp_wrap.h:22
GMP_MPZ & operator=(const GMP_MPZ &)
Definition: gmp_wrap.cpp:60
BigInt to_bigint() const
Definition: gmp_wrap.cpp:86
size_t bytes() const
Definition: gmp_wrap.cpp:78
void flip_sign()
Definition: bigint.cpp:302