common.odin 7.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. /*
  2. Copyright 2021 Jeroen van Rijn <[email protected]>.
  3. Made available under Odin's BSD-3 license.
  4. */
  5. package math_big
  6. import "base:intrinsics"
  7. /*
  8. TODO: Make the tunables runtime adjustable where practical.
  9. This allows to benchmark and/or setting optimized values for a certain CPU without recompiling.
  10. */
  11. /*
  12. ========================== TUNABLES ==========================
  13. `initialize_constants` returns `#config(MUL_KARATSUBA_CUTOFF, _DEFAULT_MUL_KARATSUBA_CUTOFF)`
  14. and we initialize this cutoff that way so that the procedure is used and called,
  15. because it handles initializing the constants ONE, ZERO, MINUS_ONE, NAN and INF.
  16. `initialize_constants` also replaces the other `_DEFAULT_*` cutoffs with custom compile-time values if so `#config`ured.
  17. */
  18. /*
  19. There is a bug with DLL globals. They don't get set.
  20. To allow tests to run we add `-define:MATH_BIG_EXE=false` to hardcode the cutoffs for now.
  21. */
  22. when #config(MATH_BIG_EXE, true) {
  23. MUL_KARATSUBA_CUTOFF := initialize_constants()
  24. SQR_KARATSUBA_CUTOFF := _DEFAULT_SQR_KARATSUBA_CUTOFF
  25. MUL_TOOM_CUTOFF := _DEFAULT_MUL_TOOM_CUTOFF
  26. SQR_TOOM_CUTOFF := _DEFAULT_SQR_TOOM_CUTOFF
  27. } else {
  28. MUL_KARATSUBA_CUTOFF := _DEFAULT_MUL_KARATSUBA_CUTOFF
  29. SQR_KARATSUBA_CUTOFF := _DEFAULT_SQR_KARATSUBA_CUTOFF
  30. MUL_TOOM_CUTOFF := _DEFAULT_MUL_TOOM_CUTOFF
  31. SQR_TOOM_CUTOFF := _DEFAULT_SQR_TOOM_CUTOFF
  32. }
  33. /*
  34. These defaults were tuned on an AMD A8-6600K (64-bit) using libTomMath's `make tune`.
  35. TODO(Jeroen): Port this tuning algorithm and tune them for more modern processors.
  36. It would also be cool if we collected some data across various processor families.
  37. This would let uss set reasonable defaults at runtime as this library initializes
  38. itself by using `cpuid` or the ARM equivalent.
  39. IMPORTANT: The 32_BIT path has largely gone untested. It needs to be tested and
  40. debugged where necessary.
  41. */
  42. _DEFAULT_MUL_KARATSUBA_CUTOFF :: #config(MATH_BIG_MUL_KARATSUBA_CUTOFF, 80)
  43. _DEFAULT_SQR_KARATSUBA_CUTOFF :: #config(MATH_BIG_SQR_KARATSUBA_CUTOFF, 120)
  44. _DEFAULT_MUL_TOOM_CUTOFF :: #config(MATH_BIG_MUL_TOOM_CUTOFF, 350)
  45. _DEFAULT_SQR_TOOM_CUTOFF :: #config(MATH_BIG_SQR_TOOM_CUTOFF, 400)
  46. MAX_ITERATIONS_ROOT_N := 500
  47. /*
  48. Largest `N` for which we'll compute `N!`
  49. */
  50. FACTORIAL_MAX_N := 1_000_000
  51. /*
  52. Cutoff to switch to int_factorial_binary_split, and its max recursion level.
  53. */
  54. FACTORIAL_BINARY_SPLIT_CUTOFF := 6100
  55. FACTORIAL_BINARY_SPLIT_MAX_RECURSIONS := 100
  56. /*
  57. `internal_int_is_prime` switchables.
  58. Use Frobenius-Underwood for primality testing, or use Lucas-Selfridge (default).
  59. */
  60. MATH_BIG_USE_LUCAS_SELFRIDGE_TEST :: #config(MATH_BIG_USE_LUCAS_SELFRIDGE_TEST, false)
  61. MATH_BIG_USE_FROBENIUS_TEST :: !MATH_BIG_USE_LUCAS_SELFRIDGE_TEST
  62. /*
  63. Runtime tunable to use Miller-Rabin primality testing only and skip the above.
  64. */
  65. USE_MILLER_RABIN_ONLY := false
  66. /*
  67. How many times we'll call `internal_int_random` during random prime generation before we bail out.
  68. Set to 0 or less to try indefinitely.
  69. */
  70. MAX_ITERATIONS_RANDOM_PRIME := 1_000_000
  71. /*
  72. How many iterations we used for the last random prime.
  73. */
  74. @thread_local RANDOM_PRIME_ITERATIONS_USED: int
  75. /*
  76. We don't allow these to be switched at runtime for two reasons:
  77. 1) 32-bit and 64-bit versions of procedures use different types for their storage,
  78. so we'd have to double the number of procedures, and they couldn't interact.
  79. 2) Optimizations thanks to precomputed masks wouldn't work.
  80. */
  81. MATH_BIG_FORCE_64_BIT :: #config(MATH_BIG_FORCE_64_BIT, false)
  82. MATH_BIG_FORCE_32_BIT :: #config(MATH_BIG_FORCE_32_BIT, false)
  83. when (MATH_BIG_FORCE_32_BIT && MATH_BIG_FORCE_64_BIT) { #panic("Cannot force 32-bit and 64-bit big backend simultaneously.") }
  84. /*
  85. Trade a smaller memory footprint for more processing overhead?
  86. */
  87. _LOW_MEMORY :: #config(MATH_BIG_SMALL_MEMORY, false)
  88. when _LOW_MEMORY {
  89. _DEFAULT_DIGIT_COUNT :: 8
  90. _TAB_SIZE :: 32
  91. _MAX_WIN_SIZE :: 5
  92. } else {
  93. _DEFAULT_DIGIT_COUNT :: 32
  94. _TAB_SIZE :: 256
  95. _MAX_WIN_SIZE :: 0
  96. }
  97. /*
  98. ======================= END OF TUNABLES =======================
  99. */
  100. Sign :: enum u8 {
  101. Zero_or_Positive = 0,
  102. Negative = 1,
  103. }
  104. Int :: struct {
  105. used: int,
  106. digit: [dynamic]DIGIT,
  107. sign: Sign,
  108. flags: Flags,
  109. }
  110. Flag :: enum u8 {
  111. NaN,
  112. Inf,
  113. Immutable,
  114. }
  115. Flags :: bit_set[Flag; u8]
  116. /*
  117. Errors are a strict superset of runtime.Allocation_Error.
  118. */
  119. Error :: enum int {
  120. Okay = 0,
  121. Out_Of_Memory = 1,
  122. Invalid_Pointer = 2,
  123. Invalid_Argument = 3,
  124. Assignment_To_Immutable = 10,
  125. Max_Iterations_Reached = 11,
  126. Buffer_Overflow = 12,
  127. Integer_Overflow = 13,
  128. Integer_Underflow = 14,
  129. Division_by_Zero = 30,
  130. Math_Domain_Error = 31,
  131. Cannot_Open_File = 50,
  132. Cannot_Read_File = 51,
  133. Cannot_Write_File = 52,
  134. Unimplemented = 127,
  135. }
  136. Error_String :: #sparse[Error]string{
  137. .Okay = "Okay",
  138. .Out_Of_Memory = "Out of memory",
  139. .Invalid_Pointer = "Invalid pointer",
  140. .Invalid_Argument = "Invalid argument",
  141. .Assignment_To_Immutable = "Assignment to immutable",
  142. .Max_Iterations_Reached = "Max iterations reached",
  143. .Buffer_Overflow = "Buffer overflow",
  144. .Integer_Overflow = "Integer overflow",
  145. .Integer_Underflow = "Integer underflow",
  146. .Division_by_Zero = "Division by zero",
  147. .Math_Domain_Error = "Math domain error",
  148. .Cannot_Open_File = "Cannot_Open_File",
  149. .Cannot_Read_File = "Cannot_Read_File",
  150. .Cannot_Write_File = "Cannot_Write_File",
  151. .Unimplemented = "Unimplemented",
  152. }
  153. Primality_Flag :: enum u8 {
  154. Blum_Blum_Shub = 0, // Make prime congruent to 3 mod 4
  155. Safe = 1, // Make sure (p-1)/2 is prime as well (implies .Blum_Blum_Shub)
  156. Second_MSB_On = 3, // Make the 2nd highest bit one
  157. }
  158. Primality_Flags :: bit_set[Primality_Flag; u8]
  159. /*
  160. How do we store the Ints?
  161. Minimum number of available digits in `Int`, `_DEFAULT_DIGIT_COUNT` >= `_MIN_DIGIT_COUNT`
  162. - Must be at least 3 for `_div_school`.
  163. - Must be large enough such that `init_integer` can store `u128` in the `Int` without growing.
  164. */
  165. _MIN_DIGIT_COUNT :: max(3, ((size_of(u128) + _DIGIT_BITS) - 1) / _DIGIT_BITS)
  166. #assert(_DEFAULT_DIGIT_COUNT >= _MIN_DIGIT_COUNT)
  167. /*
  168. Maximum number of digits.
  169. - Must be small enough such that `_bit_count` does not overflow.
  170. - Must be small enough such that `_radix_size` for base 2 does not overflow.
  171. `_radix_size` needs two additional bytes for zero termination and sign.
  172. */
  173. _MAX_BIT_COUNT :: (max(int) - 2)
  174. _MAX_DIGIT_COUNT :: _MAX_BIT_COUNT / _DIGIT_BITS
  175. when MATH_BIG_FORCE_64_BIT || (!MATH_BIG_FORCE_32_BIT && size_of(rawptr) == 8) {
  176. /*
  177. We can use u128 as an intermediary.
  178. */
  179. DIGIT :: distinct u64
  180. _WORD :: distinct u128
  181. } else {
  182. DIGIT :: distinct u32
  183. _WORD :: distinct u64
  184. }
  185. #assert(size_of(_WORD) == 2 * size_of(DIGIT))
  186. _DIGIT_TYPE_BITS :: 8 * size_of(DIGIT)
  187. _WORD_TYPE_BITS :: 8 * size_of(_WORD)
  188. _DIGIT_NAILS :: 4
  189. _DIGIT_BITS :: _DIGIT_TYPE_BITS - _DIGIT_NAILS
  190. _WORD_BITS :: 2 * _DIGIT_BITS
  191. _MASK :: (DIGIT(1) << DIGIT(_DIGIT_BITS)) - DIGIT(1)
  192. _DIGIT_MAX :: _MASK
  193. _MAX_COMBA :: 1 << (_WORD_TYPE_BITS - (2 * _DIGIT_BITS))
  194. _WARRAY :: 1 << ((_WORD_TYPE_BITS - (2 * _DIGIT_BITS)) + 1)
  195. Order :: enum i8 {
  196. LSB_First = -1,
  197. MSB_First = 1,
  198. }
  199. Endianness :: enum i8 {
  200. Little = -1,
  201. Platform = 0,
  202. Big = 1,
  203. }