imath.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421
  1. /*
  2. Name: imath.h
  3. Purpose: Arbitrary precision integer arithmetic routines.
  4. Author: M. J. Fromberger
  5. Copyright (C) 2002-2007 Michael J. Fromberger, All Rights Reserved.
  6. Permission is hereby granted, free of charge, to any person obtaining a copy
  7. of this software and associated documentation files (the "Software"), to deal
  8. in the Software without restriction, including without limitation the rights
  9. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  10. copies of the Software, and to permit persons to whom the Software is
  11. furnished to do so, subject to the following conditions:
  12. The above copyright notice and this permission notice shall be included in
  13. all copies or substantial portions of the Software.
  14. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  15. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  16. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  17. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  18. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  19. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. SOFTWARE.
  21. */
  22. #ifndef IMATH_H_
  23. #define IMATH_H_
  24. #include <limits.h>
  25. #include <stdbool.h>
  26. #include <stdint.h>
  27. #ifdef __cplusplus
  28. extern "C" {
  29. #endif
  30. typedef unsigned char mp_sign;
  31. typedef unsigned int mp_size;
  32. typedef int mp_result;
  33. typedef long mp_small; /* must be a signed type */
  34. typedef unsigned long mp_usmall; /* must be an unsigned type */
  35. /* Build with words as uint64_t by default. */
  36. #ifdef USE_32BIT_WORDS
  37. typedef uint16_t mp_digit;
  38. typedef uint32_t mp_word;
  39. # define MP_DIGIT_MAX (UINT16_MAX * 1UL)
  40. # define MP_WORD_MAX (UINT32_MAX * 1UL)
  41. #else
  42. typedef uint32_t mp_digit;
  43. typedef uint64_t mp_word;
  44. # define MP_DIGIT_MAX (UINT32_MAX * UINT64_C(1))
  45. # define MP_WORD_MAX (UINT64_MAX)
  46. #endif
  47. typedef struct {
  48. mp_digit single;
  49. mp_digit* digits;
  50. mp_size alloc;
  51. mp_size used;
  52. mp_sign sign;
  53. } mpz_t, *mp_int;
  54. static inline mp_digit* MP_DIGITS(mp_int Z) { return Z->digits; }
  55. static inline mp_size MP_ALLOC(mp_int Z) { return Z->alloc; }
  56. static inline mp_size MP_USED(mp_int Z) { return Z->used; }
  57. static inline mp_sign MP_SIGN(mp_int Z) { return Z->sign; }
  58. extern const mp_result MP_OK;
  59. extern const mp_result MP_FALSE;
  60. extern const mp_result MP_TRUE;
  61. extern const mp_result MP_MEMORY;
  62. extern const mp_result MP_RANGE;
  63. extern const mp_result MP_UNDEF;
  64. extern const mp_result MP_TRUNC;
  65. extern const mp_result MP_BADARG;
  66. extern const mp_result MP_MINERR;
  67. #define MP_DIGIT_BIT (sizeof(mp_digit) * CHAR_BIT)
  68. #define MP_WORD_BIT (sizeof(mp_word) * CHAR_BIT)
  69. #define MP_SMALL_MIN LONG_MIN
  70. #define MP_SMALL_MAX LONG_MAX
  71. #define MP_USMALL_MAX ULONG_MAX
  72. #define MP_MIN_RADIX 2
  73. #define MP_MAX_RADIX 36
  74. /** Sets the default number of digits allocated to an `mp_int` constructed by
  75. `mp_int_init_size()` with `prec == 0`. Allocations are rounded up to
  76. multiples of this value. `MP_DEFAULT_PREC` is the default value. Requires
  77. `ndigits > 0`. */
  78. void mp_int_default_precision(mp_size ndigits);
  79. /** Sets the number of digits below which multiplication will use the standard
  80. quadratic "schoolbook" multiplication algorithm rather than Karatsuba-Ofman.
  81. Requires `ndigits >= sizeof(mp_word)`. */
  82. void mp_int_multiply_threshold(mp_size ndigits);
  83. /** A sign indicating a (strictly) negative value. */
  84. extern const mp_sign MP_NEG;
  85. /** A sign indicating a zero or positive value. */
  86. extern const mp_sign MP_ZPOS;
  87. /** Reports whether `z` is odd, having remainder 1 when divided by 2. */
  88. static inline bool mp_int_is_odd(mp_int z) { return (z->digits[0] & 1) != 0; }
  89. /** Reports whether `z` is even, having remainder 0 when divided by 2. */
  90. static inline bool mp_int_is_even(mp_int z) { return (z->digits[0] & 1) == 0; }
  91. /** Initializes `z` with 1-digit precision and sets it to zero. This function
  92. cannot fail unless `z == NULL`. */
  93. mp_result mp_int_init(mp_int z);
  94. /** Allocates a fresh zero-valued `mpz_t` on the heap, returning NULL in case
  95. of error. The only possible error is out-of-memory. */
  96. mp_int mp_int_alloc(void);
  97. /** Initializes `z` with at least `prec` digits of storage, and sets it to
  98. zero. If `prec` is zero, the default precision is used. In either case the
  99. size is rounded up to the nearest multiple of the word size. */
  100. mp_result mp_int_init_size(mp_int z, mp_size prec);
  101. /** Initializes `z` to be a copy of an already-initialized value in `old`. The
  102. new copy does not share storage with the original. */
  103. mp_result mp_int_init_copy(mp_int z, mp_int old);
  104. /** Initializes `z` to the specified signed `value` at default precision. */
  105. mp_result mp_int_init_value(mp_int z, mp_small value);
  106. /** Initializes `z` to the specified unsigned `value` at default precision. */
  107. mp_result mp_int_init_uvalue(mp_int z, mp_usmall uvalue);
  108. /** Sets `z` to the value of the specified signed `value`. */
  109. mp_result mp_int_set_value(mp_int z, mp_small value);
  110. /** Sets `z` to the value of the specified unsigned `value`. */
  111. mp_result mp_int_set_uvalue(mp_int z, mp_usmall uvalue);
  112. /** Releases the storage used by `z`. */
  113. void mp_int_clear(mp_int z);
  114. /** Releases the storage used by `z` and also `z` itself.
  115. This should only be used for `z` allocated by `mp_int_alloc()`. */
  116. void mp_int_free(mp_int z);
  117. /** Replaces the value of `c` with a copy of the value of `a`. No new memory is
  118. allocated unless `a` has more significant digits than `c` has allocated. */
  119. mp_result mp_int_copy(mp_int a, mp_int c);
  120. /** Swaps the values and storage between `a` and `c`. */
  121. void mp_int_swap(mp_int a, mp_int c);
  122. /** Sets `z` to zero. The allocated storage of `z` is not changed. */
  123. void mp_int_zero(mp_int z);
  124. /** Sets `c` to the absolute value of `a`. */
  125. mp_result mp_int_abs(mp_int a, mp_int c);
  126. /** Sets `c` to the additive inverse (negation) of `a`. */
  127. mp_result mp_int_neg(mp_int a, mp_int c);
  128. /** Sets `c` to the sum of `a` and `b`. */
  129. mp_result mp_int_add(mp_int a, mp_int b, mp_int c);
  130. /** Sets `c` to the sum of `a` and `value`. */
  131. mp_result mp_int_add_value(mp_int a, mp_small value, mp_int c);
  132. /** Sets `c` to the difference of `a` less `b`. */
  133. mp_result mp_int_sub(mp_int a, mp_int b, mp_int c);
  134. /** Sets `c` to the difference of `a` less `value`. */
  135. mp_result mp_int_sub_value(mp_int a, mp_small value, mp_int c);
  136. /** Sets `c` to the product of `a` and `b`. */
  137. mp_result mp_int_mul(mp_int a, mp_int b, mp_int c);
  138. /** Sets `c` to the product of `a` and `value`. */
  139. mp_result mp_int_mul_value(mp_int a, mp_small value, mp_int c);
  140. /** Sets `c` to the product of `a` and `2^p2`. Requires `p2 >= 0`. */
  141. mp_result mp_int_mul_pow2(mp_int a, mp_small p2, mp_int c);
  142. /** Sets `c` to the square of `a`. */
  143. mp_result mp_int_sqr(mp_int a, mp_int c);
  144. /** Sets `q` and `r` to the quotent and remainder of `a / b`. Division by
  145. powers of 2 is detected and handled efficiently. The remainder is pinned
  146. to `0 <= r < b`.
  147. Either of `q` or `r` may be NULL, but not both, and `q` and `r` may not
  148. point to the same value. */
  149. mp_result mp_int_div(mp_int a, mp_int b, mp_int q, mp_int r);
  150. /** Sets `q` and `*r` to the quotent and remainder of `a / value`. Division by
  151. powers of 2 is detected and handled efficiently. The remainder is pinned to
  152. `0 <= *r < b`. Either of `q` or `r` may be NULL. */
  153. mp_result mp_int_div_value(mp_int a, mp_small value, mp_int q, mp_small *r);
  154. /** Sets `q` and `r` to the quotient and remainder of `a / 2^p2`. This is a
  155. special case for division by powers of two that is more efficient than
  156. using ordinary division. Note that `mp_int_div()` will automatically handle
  157. this case, this function is for cases where you have only the exponent. */
  158. mp_result mp_int_div_pow2(mp_int a, mp_small p2, mp_int q, mp_int r);
  159. /** Sets `c` to the remainder of `a / m`.
  160. The remainder is pinned to `0 <= c < m`. */
  161. mp_result mp_int_mod(mp_int a, mp_int m, mp_int c);
  162. /** Sets `c` to the value of `a` raised to the `b` power.
  163. It returns `MP_RANGE` if `b < 0`. */
  164. mp_result mp_int_expt(mp_int a, mp_small b, mp_int c);
  165. /** Sets `c` to the value of `a` raised to the `b` power.
  166. It returns `MP_RANGE` if `b < 0`. */
  167. mp_result mp_int_expt_value(mp_small a, mp_small b, mp_int c);
  168. /** Sets `c` to the value of `a` raised to the `b` power.
  169. It returns `MP_RANGE`) if `b < 0`. */
  170. mp_result mp_int_expt_full(mp_int a, mp_int b, mp_int c);
  171. /** Sets `*r` to the remainder of `a / value`.
  172. The remainder is pinned to `0 <= r < value`. */
  173. static inline
  174. mp_result mp_int_mod_value(mp_int a, mp_small value, mp_small* r) {
  175. return mp_int_div_value(a, value, 0, r);
  176. }
  177. /** Returns the comparator of `a` and `b`. */
  178. int mp_int_compare(mp_int a, mp_int b);
  179. /** Returns the comparator of the magnitudes of `a` and `b`, disregarding their
  180. signs. Neither `a` nor `b` is modified by the comparison. */
  181. int mp_int_compare_unsigned(mp_int a, mp_int b);
  182. /** Returns the comparator of `z` and zero. */
  183. int mp_int_compare_zero(mp_int z);
  184. /** Returns the comparator of `z` and the signed value `v`. */
  185. int mp_int_compare_value(mp_int z, mp_small v);
  186. /** Returns the comparator of `z` and the unsigned value `uv`. */
  187. int mp_int_compare_uvalue(mp_int z, mp_usmall uv);
  188. /** Reports whether `a` is divisible by `v`. */
  189. bool mp_int_divisible_value(mp_int a, mp_small v);
  190. /** Returns `k >= 0` such that `z` is `2^k`, if such a `k` exists. If no such
  191. `k` exists, the function returns -1. */
  192. int mp_int_is_pow2(mp_int z);
  193. /** Sets `c` to the value of `a` raised to the `b` power, reduced modulo `m`.
  194. It returns `MP_RANGE` if `b < 0` or `MP_UNDEF` if `m == 0`. */
  195. mp_result mp_int_exptmod(mp_int a, mp_int b, mp_int m, mp_int c);
  196. /** Sets `c` to the value of `a` raised to the `value` power, modulo `m`.
  197. It returns `MP_RANGE` if `value < 0` or `MP_UNDEF` if `m == 0`. */
  198. mp_result mp_int_exptmod_evalue(mp_int a, mp_small value, mp_int m, mp_int c);
  199. /** Sets `c` to the value of `value` raised to the `b` power, modulo `m`.
  200. It returns `MP_RANGE` if `b < 0` or `MP_UNDEF` if `m == 0`. */
  201. mp_result mp_int_exptmod_bvalue(mp_small value, mp_int b, mp_int m, mp_int c);
  202. /** Sets `c` to the value of `a` raised to the `b` power, reduced modulo `m`,
  203. given a precomputed reduction constant `mu` defined for Barrett's modular
  204. reduction algorithm.
  205. It returns `MP_RANGE` if `b < 0` or `MP_UNDEF` if `m == 0`. */
  206. mp_result mp_int_exptmod_known(mp_int a, mp_int b, mp_int m, mp_int mu, mp_int c);
  207. /** Sets `c` to the reduction constant for Barrett reduction by modulus `m`.
  208. Requires that `c` and `m` point to distinct locations. */
  209. mp_result mp_int_redux_const(mp_int m, mp_int c);
  210. /** Sets `c` to the multiplicative inverse of `a` modulo `m`, if it exists.
  211. The least non-negative representative of the congruence class is computed.
  212. It returns `MP_UNDEF` if the inverse does not exist, or `MP_RANGE` if `a ==
  213. 0` or `m <= 0`. */
  214. mp_result mp_int_invmod(mp_int a, mp_int m, mp_int c);
  215. /** Sets `c` to the greatest common divisor of `a` and `b`.
  216. It returns `MP_UNDEF` if the GCD is undefined, such as for example if `a`
  217. and `b` are both zero. */
  218. mp_result mp_int_gcd(mp_int a, mp_int b, mp_int c);
  219. /** Sets `c` to the greatest common divisor of `a` and `b`, and sets `x` and
  220. `y` to values satisfying Bezout's identity `gcd(a, b) = ax + by`.
  221. It returns `MP_UNDEF` if the GCD is undefined, such as for example if `a`
  222. and `b` are both zero. */
  223. mp_result mp_int_egcd(mp_int a, mp_int b, mp_int c, mp_int x, mp_int y);
  224. /** Sets `c` to the least common multiple of `a` and `b`.
  225. It returns `MP_UNDEF` if the LCM is undefined, such as for example if `a`
  226. and `b` are both zero. */
  227. mp_result mp_int_lcm(mp_int a, mp_int b, mp_int c);
  228. /** Sets `c` to the greatest integer not less than the `b`th root of `a`,
  229. using Newton's root-finding algorithm.
  230. It returns `MP_UNDEF` if `a < 0` and `b` is even. */
  231. mp_result mp_int_root(mp_int a, mp_small b, mp_int c);
  232. /** Sets `c` to the greatest integer not less than the square root of `a`.
  233. This is a special case of `mp_int_root()`. */
  234. static inline
  235. mp_result mp_int_sqrt(mp_int a, mp_int c) { return mp_int_root(a, 2, c); }
  236. /** Returns `MP_OK` if `z` is representable as `mp_small`, else `MP_RANGE`.
  237. If `out` is not NULL, `*out` is set to the value of `z` when `MP_OK`. */
  238. mp_result mp_int_to_int(mp_int z, mp_small *out);
  239. /** Returns `MP_OK` if `z` is representable as `mp_usmall`, or `MP_RANGE`.
  240. If `out` is not NULL, `*out` is set to the value of `z` when `MP_OK`. */
  241. mp_result mp_int_to_uint(mp_int z, mp_usmall *out);
  242. /** Converts `z` to a zero-terminated string of characters in the specified
  243. `radix`, writing at most `limit` characters to `str` including the
  244. terminating NUL value. A leading `-` is used to indicate a negative value.
  245. Returns `MP_TRUNC` if `limit` was to small to write all of `z`.
  246. Requires `MP_MIN_RADIX <= radix <= MP_MAX_RADIX`. */
  247. mp_result mp_int_to_string(mp_int z, mp_size radix, char *str, int limit);
  248. /** Reports the minimum number of characters required to represent `z` as a
  249. zero-terminated string in the given `radix`.
  250. Requires `MP_MIN_RADIX <= radix <= MP_MAX_RADIX`. */
  251. mp_result mp_int_string_len(mp_int z, mp_size radix);
  252. /** Reads a string of ASCII digits in the specified `radix` from the zero
  253. terminated `str` provided into `z`. For values of `radix > 10`, the letters
  254. `A`..`Z` or `a`..`z` are accepted. Letters are interpreted without respect
  255. to case.
  256. Leading whitespace is ignored, and a leading `+` or `-` is interpreted as a
  257. sign flag. Processing stops when a NUL or any other character out of range
  258. for a digit in the given radix is encountered.
  259. If the whole string was consumed, `MP_OK` is returned; otherwise
  260. `MP_TRUNC`. is returned.
  261. Requires `MP_MIN_RADIX <= radix <= MP_MAX_RADIX`. */
  262. mp_result mp_int_read_string(mp_int z, mp_size radix, const char *str);
  263. /** Reads a string of ASCII digits in the specified `radix` from the zero
  264. terminated `str` provided into `z`. For values of `radix > 10`, the letters
  265. `A`..`Z` or `a`..`z` are accepted. Letters are interpreted without respect
  266. to case.
  267. Leading whitespace is ignored, and a leading `+` or `-` is interpreted as a
  268. sign flag. Processing stops when a NUL or any other character out of range
  269. for a digit in the given radix is encountered.
  270. If the whole string was consumed, `MP_OK` is returned; otherwise
  271. `MP_TRUNC`. is returned. If `end` is not NULL, `*end` is set to point to
  272. the first unconsumed byte of the input string (the NUL byte if the whole
  273. string was consumed). This emulates the behavior of the standard C
  274. `strtol()` function.
  275. Requires `MP_MIN_RADIX <= radix <= MP_MAX_RADIX`. */
  276. mp_result mp_int_read_cstring(mp_int z, mp_size radix, const char *str, char **end);
  277. /** Returns the number of significant bits in `z`. */
  278. mp_result mp_int_count_bits(mp_int z);
  279. /** Converts `z` to 2's complement binary, writing at most `limit` bytes into
  280. the given `buf`. Returns `MP_TRUNC` if the buffer limit was too small to
  281. contain the whole value. If this occurs, the contents of buf will be
  282. effectively garbage, as the function uses the buffer as scratch space.
  283. The binary representation of `z` is in base-256 with digits ordered from
  284. most significant to least significant (network byte ordering). The
  285. high-order bit of the first byte is set for negative values, clear for
  286. non-negative values.
  287. As a result, non-negative values will be padded with a leading zero byte if
  288. the high-order byte of the base-256 magnitude is set. This extra byte is
  289. accounted for by the `mp_int_binary_len()` function. */
  290. mp_result mp_int_to_binary(mp_int z, unsigned char *buf, int limit);
  291. /** Reads a 2's complement binary value from `buf` into `z`, where `len` is the
  292. length of the buffer. The contents of `buf` may be overwritten during
  293. processing, although they will be restored when the function returns. */
  294. mp_result mp_int_read_binary(mp_int z, unsigned char *buf, int len);
  295. /** Returns the number of bytes to represent `z` in 2's complement binary. */
  296. mp_result mp_int_binary_len(mp_int z);
  297. /** Converts the magnitude of `z` to unsigned binary, writing at most `limit`
  298. bytes into the given `buf`. The sign of `z` is ignored, but `z` is not
  299. modified. Returns `MP_TRUNC` if the buffer limit was too small to contain
  300. the whole value. If this occurs, the contents of `buf` will be effectively
  301. garbage, as the function uses the buffer as scratch space during
  302. conversion.
  303. The binary representation of `z` is in base-256 with digits ordered from
  304. most significant to least significant (network byte ordering). */
  305. mp_result mp_int_to_unsigned(mp_int z, unsigned char *buf, int limit);
  306. /** Reads an unsigned binary value from `buf` into `z`, where `len` is the
  307. length of the buffer. The contents of `buf` are not modified during
  308. processing. */
  309. mp_result mp_int_read_unsigned(mp_int z, unsigned char *buf, int len);
  310. /** Returns the number of bytes required to represent `z` as an unsigned binary
  311. value in base 256. */
  312. mp_result mp_int_unsigned_len(mp_int z);
  313. /** Returns a pointer to a brief, human-readable, zero-terminated string
  314. describing `res`. The returned string is statically allocated and must not
  315. be freed by the caller. */
  316. const char *mp_error_string(mp_result res);
  317. #ifdef __cplusplus
  318. }
  319. #endif
  320. #endif /* end IMATH_H_ */