helpers.odin 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. /*
  2. Copyright 2021 Jeroen van Rijn <[email protected]>.
  3. Made available under Odin's BSD-3 license.
  4. An arbitrary precision mathematics implementation in Odin.
  5. For the theoretical underpinnings, see Knuth's The Art of Computer Programming, Volume 2, section 4.3.
  6. The code started out as an idiomatic source port of libTomMath, which is in the public domain, with thanks.
  7. */
  8. package math_big
  9. import "core:intrinsics"
  10. import rnd "core:math/rand"
  11. /*
  12. TODO: Int.flags and Constants like ONE, NAN, etc, are not yet properly handled everywhere.
  13. */
  14. /*
  15. Deallocates the backing memory of one or more `Int`s.
  16. */
  17. int_destroy :: proc(integers: ..^Int) {
  18. integers := integers
  19. for a in &integers {
  20. assert_if_nil(a)
  21. }
  22. #force_inline internal_int_destroy(..integers)
  23. }
  24. /*
  25. Helpers to set an `Int` to a specific value.
  26. */
  27. int_set_from_integer :: proc(dest: ^Int, src: $T, minimize := false, allocator := context.allocator) -> (err: Error)
  28. where intrinsics.type_is_integer(T) {
  29. context.allocator = allocator
  30. src := src
  31. /*
  32. Check that `src` is usable and `dest` isn't immutable.
  33. */
  34. assert_if_nil(dest)
  35. #force_inline internal_error_if_immutable(dest) or_return
  36. return #force_inline internal_int_set_from_integer(dest, src, minimize)
  37. }
  38. set :: proc {
  39. int_set_from_integer,
  40. int_copy,
  41. int_atoi,
  42. rat_set_f64,
  43. rat_set_f32,
  44. rat_set_f16,
  45. rat_set_u64,
  46. rat_set_i64,
  47. rat_set_int,
  48. rat_set_digit,
  49. rat_set_rat,
  50. }
  51. /*
  52. Copy one `Int` to another.
  53. */
  54. int_copy :: proc(dest, src: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  55. /*
  56. If dest == src, do nothing
  57. */
  58. if (dest == src) { return nil }
  59. /*
  60. Check that `src` is usable and `dest` isn't immutable.
  61. */
  62. assert_if_nil(dest, src)
  63. context.allocator = allocator
  64. #force_inline internal_clear_if_uninitialized(src) or_return
  65. #force_inline internal_error_if_immutable(dest) or_return
  66. return #force_inline internal_int_copy(dest, src, minimize)
  67. }
  68. copy :: proc {
  69. int_copy,
  70. rat_copy,
  71. }
  72. /*
  73. In normal code, you can also write `a, b = b, a`.
  74. However, that only swaps within the current scope.
  75. This helper swaps completely.
  76. */
  77. int_swap :: proc(a, b: ^Int) {
  78. assert_if_nil(a, b)
  79. #force_inline internal_swap(a, b)
  80. }
  81. swap :: proc { int_swap, rat_swap }
  82. /*
  83. Set `dest` to |`src`|.
  84. */
  85. int_abs :: proc(dest, src: ^Int, allocator := context.allocator) -> (err: Error) {
  86. /*
  87. Check that `src` is usable and `dest` isn't immutable.
  88. */
  89. assert_if_nil(dest, src)
  90. context.allocator = allocator
  91. #force_inline internal_clear_if_uninitialized(src) or_return
  92. #force_inline internal_error_if_immutable(dest) or_return
  93. return #force_inline internal_int_abs(dest, src)
  94. }
  95. platform_abs :: proc(n: $T) -> T where intrinsics.type_is_integer(T) {
  96. return n if n >= 0 else -n
  97. }
  98. abs :: proc{ int_abs, platform_abs, rat_abs }
  99. /*
  100. Set `dest` to `-src`.
  101. */
  102. int_neg :: proc(dest, src: ^Int, allocator := context.allocator) -> (err: Error) {
  103. /*
  104. Check that `src` is usable and `dest` isn't immutable.
  105. */
  106. assert_if_nil(dest, src)
  107. context.allocator = allocator
  108. #force_inline internal_clear_if_uninitialized(src) or_return
  109. #force_inline internal_error_if_immutable(dest) or_return
  110. return #force_inline internal_int_neg(dest, src)
  111. }
  112. neg :: proc { int_neg, rat_neg }
  113. /*
  114. Helpers to extract values from the `Int`.
  115. */
  116. int_bitfield_extract_single :: proc(a: ^Int, offset: int, allocator := context.allocator) -> (bit: _WORD, err: Error) {
  117. return #force_inline int_bitfield_extract(a, offset, 1, allocator)
  118. }
  119. int_bitfield_extract :: proc(a: ^Int, offset, count: int, allocator := context.allocator) -> (res: _WORD, err: Error) {
  120. /*
  121. Check that `a` is usable.
  122. */
  123. assert_if_nil(a)
  124. context.allocator = allocator
  125. #force_inline internal_clear_if_uninitialized(a) or_return
  126. return #force_inline internal_int_bitfield_extract(a, offset, count)
  127. }
  128. /*
  129. Resize backing store.
  130. */
  131. shrink :: proc(a: ^Int, allocator := context.allocator) -> (err: Error) {
  132. /*
  133. Check that `a` is usable.
  134. */
  135. assert_if_nil(a)
  136. context.allocator = allocator
  137. #force_inline internal_clear_if_uninitialized(a) or_return
  138. return #force_inline internal_shrink(a)
  139. }
  140. int_grow :: proc(a: ^Int, digits: int, allow_shrink := false, allocator := context.allocator) -> (err: Error) {
  141. /*
  142. Check that `a` is usable.
  143. */
  144. assert_if_nil(a)
  145. return #force_inline internal_int_grow(a, digits, allow_shrink, allocator)
  146. }
  147. grow :: proc { int_grow, }
  148. /*
  149. Clear `Int` and resize it to the default size.
  150. */
  151. int_clear :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  152. /*
  153. Check that `a` is usable.
  154. */
  155. assert_if_nil(a)
  156. return #force_inline internal_int_clear(a, minimize, allocator)
  157. }
  158. clear :: proc { int_clear, }
  159. zero :: clear
  160. /*
  161. Set the `Int` to 1 and optionally shrink it to the minimum backing size.
  162. */
  163. int_one :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  164. /*
  165. Check that `a` is usable.
  166. */
  167. assert_if_nil(a)
  168. return #force_inline internal_one(a, minimize, allocator)
  169. }
  170. one :: proc { int_one, }
  171. /*
  172. Set the `Int` to -1 and optionally shrink it to the minimum backing size.
  173. */
  174. int_minus_one :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  175. /*
  176. Check that `a` is usable.
  177. */
  178. assert_if_nil(a)
  179. return #force_inline internal_minus_one(a, minimize, allocator)
  180. }
  181. minus_one :: proc { int_minus_one, }
  182. /*
  183. Set the `Int` to Inf and optionally shrink it to the minimum backing size.
  184. */
  185. int_inf :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  186. /*
  187. Check that `a` is usable.
  188. */
  189. assert_if_nil(a)
  190. return #force_inline internal_inf(a, minimize, allocator)
  191. }
  192. inf :: proc { int_inf, }
  193. /*
  194. Set the `Int` to -Inf and optionally shrink it to the minimum backing size.
  195. */
  196. int_minus_inf :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  197. /*
  198. Check that `a` is usable.
  199. */
  200. assert_if_nil(a)
  201. return #force_inline internal_minus_inf(a, minimize, allocator)
  202. }
  203. minus_inf :: proc { int_inf, }
  204. /*
  205. Set the `Int` to NaN and optionally shrink it to the minimum backing size.
  206. */
  207. int_nan :: proc(a: ^Int, minimize := false, allocator := context.allocator) -> (err: Error) {
  208. /*
  209. Check that `a` is usable.
  210. */
  211. assert_if_nil(a)
  212. return #force_inline internal_nan(a, minimize, allocator)
  213. }
  214. nan :: proc { int_nan, }
  215. power_of_two :: proc(a: ^Int, power: int, allocator := context.allocator) -> (err: Error) {
  216. /*
  217. Check that `a` is usable.
  218. */
  219. assert_if_nil(a)
  220. return #force_inline internal_int_power_of_two(a, power, allocator)
  221. }
  222. int_get_u128 :: proc(a: ^Int, allocator := context.allocator) -> (res: u128, err: Error) {
  223. /*
  224. Check that `a` is usable.
  225. */
  226. assert_if_nil(a)
  227. return int_get(a, u128, allocator)
  228. }
  229. get_u128 :: proc { int_get_u128, }
  230. int_get_i128 :: proc(a: ^Int, allocator := context.allocator) -> (res: i128, err: Error) {
  231. /*
  232. Check that `a` is usable.
  233. */
  234. assert_if_nil(a)
  235. return int_get(a, i128, allocator)
  236. }
  237. get_i128 :: proc { int_get_i128, }
  238. int_get_u64 :: proc(a: ^Int, allocator := context.allocator) -> (res: u64, err: Error) {
  239. /*
  240. Check that `a` is usable.
  241. */
  242. assert_if_nil(a)
  243. return int_get(a, u64, allocator)
  244. }
  245. get_u64 :: proc { int_get_u64, }
  246. int_get_i64 :: proc(a: ^Int, allocator := context.allocator) -> (res: i64, err: Error) {
  247. /*
  248. Check that `a` is usable.
  249. */
  250. assert_if_nil(a)
  251. return int_get(a, i64, allocator)
  252. }
  253. get_i64 :: proc { int_get_i64, }
  254. int_get_u32 :: proc(a: ^Int, allocator := context.allocator) -> (res: u32, err: Error) {
  255. /*
  256. Check that `a` is usable.
  257. */
  258. assert_if_nil(a)
  259. return int_get(a, u32, allocator)
  260. }
  261. get_u32 :: proc { int_get_u32, }
  262. int_get_i32 :: proc(a: ^Int, allocator := context.allocator) -> (res: i32, err: Error) {
  263. /*
  264. Check that `a` is usable.
  265. */
  266. assert_if_nil(a)
  267. return int_get(a, i32, allocator)
  268. }
  269. get_i32 :: proc { int_get_i32, }
  270. /*
  271. TODO: Think about using `count_bits` to check if the value could be returned completely,
  272. and maybe return max(T), .Integer_Overflow if not?
  273. */
  274. int_get :: proc(a: ^Int, $T: typeid, allocator := context.allocator) -> (res: T, err: Error) where intrinsics.type_is_integer(T) {
  275. /*
  276. Check that `a` is usable.
  277. */
  278. assert_if_nil(a)
  279. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  280. return #force_inline internal_int_get(a, T)
  281. }
  282. get :: proc { int_get, }
  283. int_get_float :: proc(a: ^Int, allocator := context.allocator) -> (res: f64, err: Error) {
  284. /*
  285. Check that `a` is usable.
  286. */
  287. assert_if_nil(a)
  288. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  289. return #force_inline internal_int_get_float(a)
  290. }
  291. /*
  292. Count bits in an `Int`.
  293. */
  294. count_bits :: proc(a: ^Int, allocator := context.allocator) -> (count: int, err: Error) {
  295. /*
  296. Check that `a` is usable.
  297. */
  298. assert_if_nil(a)
  299. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  300. return #force_inline internal_count_bits(a), nil
  301. }
  302. /*
  303. Returns the number of trailing zeroes before the first one.
  304. Differs from regular `ctz` in that 0 returns 0.
  305. */
  306. int_count_lsb :: proc(a: ^Int, allocator := context.allocator) -> (count: int, err: Error) {
  307. /*
  308. Check that `a` is usable.
  309. */
  310. assert_if_nil(a)
  311. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  312. return #force_inline internal_int_count_lsb(a)
  313. }
  314. platform_count_lsb :: #force_inline proc(a: $T) -> (count: int)
  315. where intrinsics.type_is_integer(T) && intrinsics.type_is_unsigned(T) {
  316. return int(intrinsics.count_trailing_zeros(a)) if a > 0 else 0
  317. }
  318. count_lsb :: proc { int_count_lsb, platform_count_lsb, }
  319. int_random_digit :: proc(r: ^rnd.Rand = nil) -> (res: DIGIT) {
  320. when _DIGIT_BITS == 60 { // DIGIT = u64
  321. return DIGIT(rnd.uint64(r)) & _MASK
  322. } else when _DIGIT_BITS == 28 { // DIGIT = u32
  323. return DIGIT(rnd.uint32(r)) & _MASK
  324. } else {
  325. panic("Unsupported DIGIT size.")
  326. }
  327. return 0 // We shouldn't get here.
  328. }
  329. int_random :: proc(dest: ^Int, bits: int, r: ^rnd.Rand = nil, allocator := context.allocator) -> (err: Error) {
  330. /*
  331. Check that `a` is usable.
  332. */
  333. assert_if_nil(dest)
  334. return #force_inline internal_int_random(dest, bits, r, allocator)
  335. }
  336. random :: proc { int_random, }
  337. /*
  338. Internal helpers.
  339. */
  340. assert_initialized :: proc(a: ^Int, loc := #caller_location) {
  341. assert_if_nil(a)
  342. assert(is_initialized(a), "`Int` was not properly initialized.", loc)
  343. }
  344. zero_unused :: proc(dest: ^Int, old_used := -1) {
  345. assert_if_nil(dest)
  346. if ! #force_inline is_initialized(dest) { return }
  347. #force_inline internal_zero_unused(dest, old_used)
  348. }
  349. clear_if_uninitialized_single :: proc(arg: ^Int, allocator := context.allocator) -> (err: Error) {
  350. assert_if_nil(arg)
  351. return #force_inline internal_clear_if_uninitialized_single(arg, allocator)
  352. }
  353. clear_if_uninitialized_multi :: proc(args: ..^Int, allocator := context.allocator) -> (err: Error) {
  354. args := args
  355. assert_if_nil(..args)
  356. for i in &args {
  357. #force_inline internal_clear_if_uninitialized_single(i, allocator) or_return
  358. }
  359. return err
  360. }
  361. clear_if_uninitialized :: proc {clear_if_uninitialized_single, clear_if_uninitialized_multi, }
  362. error_if_immutable_single :: proc(arg: ^Int) -> (err: Error) {
  363. if arg != nil && .Immutable in arg.flags { return .Assignment_To_Immutable }
  364. return nil
  365. }
  366. error_if_immutable_multi :: proc(args: ..^Int) -> (err: Error) {
  367. for i in args {
  368. if i != nil && .Immutable in i.flags { return .Assignment_To_Immutable }
  369. }
  370. return nil
  371. }
  372. error_if_immutable :: proc {error_if_immutable_single, error_if_immutable_multi, }
  373. /*
  374. Allocates several `Int`s at once.
  375. */
  376. int_init_multi :: proc(integers: ..^Int, allocator := context.allocator) -> (err: Error) {
  377. assert_if_nil(..integers)
  378. integers := integers
  379. for a in &integers {
  380. #force_inline internal_clear(a, true, allocator) or_return
  381. }
  382. return nil
  383. }
  384. init_multi :: proc { int_init_multi, }
  385. copy_digits :: proc(dest, src: ^Int, digits: int, offset := int(0), allocator := context.allocator) -> (err: Error) {
  386. context.allocator = allocator
  387. /*
  388. Check that `src` is usable and `dest` isn't immutable.
  389. */
  390. assert_if_nil(dest, src)
  391. #force_inline internal_clear_if_uninitialized(src) or_return
  392. return #force_inline internal_copy_digits(dest, src, digits, offset)
  393. }
  394. /*
  395. Trim unused digits.
  396. This is used to ensure that leading zero digits are trimmed and the leading "used" digit will be non-zero.
  397. Typically very fast. Also fixes the sign if there are no more leading digits.
  398. */
  399. clamp :: proc(a: ^Int, allocator := context.allocator) -> (err: Error) {
  400. assert_if_nil(a)
  401. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  402. for a.used > 0 && a.digit[a.used - 1] == 0 {
  403. a.used -= 1
  404. }
  405. if z, _ := is_zero(a); z {
  406. a.sign = .Zero_or_Positive
  407. }
  408. return nil
  409. }
  410. /*
  411. Size binary representation
  412. */
  413. int_to_bytes_size :: proc(a: ^Int, signed := false, allocator := context.allocator) -> (size_in_bytes: int, err: Error) {
  414. assert_if_nil(a)
  415. #force_inline internal_clear_if_uninitialized(a, allocator) or_return
  416. size_in_bits := internal_count_bits(a)
  417. size_in_bytes = (size_in_bits / 8)
  418. size_in_bytes += 0 if size_in_bits % 8 == 0 else 1
  419. size_in_bytes += 1 if signed else 0
  420. return
  421. }
  422. /*
  423. Return Little Endian binary representation of `a`, either signed or unsigned.
  424. If `a` is negative and we ask for the default unsigned representation, we return abs(a).
  425. */
  426. int_to_bytes_little :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  427. assert_if_nil(a)
  428. size_in_bytes := int_to_bytes_size(a, signed, allocator) or_return
  429. l := len(buf)
  430. if size_in_bytes > l { return .Buffer_Overflow }
  431. size_in_bits := internal_count_bits(a)
  432. i := 0
  433. if signed {
  434. buf[l - 1] = 1 if a.sign == .Negative else 0
  435. }
  436. #no_bounds_check for offset := 0; offset < size_in_bits; offset += 8 {
  437. bits, _ := internal_int_bitfield_extract(a, offset, 8)
  438. buf[i] = u8(bits & 255); i += 1
  439. }
  440. return
  441. }
  442. /*
  443. Return Big Endian binary representation of `a`, either signed or unsigned.
  444. If `a` is negative and we ask for the default unsigned representation, we return abs(a).
  445. */
  446. int_to_bytes_big :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  447. assert_if_nil(a)
  448. size_in_bytes := int_to_bytes_size(a, signed, allocator) or_return
  449. l := len(buf)
  450. if size_in_bytes > l { return .Buffer_Overflow }
  451. size_in_bits := internal_count_bits(a)
  452. i := l - 1
  453. if signed {
  454. buf[0] = 1 if a.sign == .Negative else 0
  455. }
  456. #no_bounds_check for offset := 0; offset < size_in_bits; offset += 8 {
  457. bits, _ := internal_int_bitfield_extract(a, offset, 8)
  458. buf[i] = u8(bits & 255); i -= 1
  459. }
  460. return
  461. }
  462. /*
  463. Return Python 3.x compatible Little Endian binary representation of `a`, either signed or unsigned.
  464. If `a` is negative when asking for an unsigned number, we return an error like Python does.
  465. */
  466. int_to_bytes_little_python :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  467. assert_if_nil(a)
  468. if !signed && a.sign == .Negative { return .Invalid_Argument }
  469. l := len(buf)
  470. size_in_bytes := int_to_bytes_size(a, signed, allocator) or_return
  471. if size_in_bytes > l { return .Buffer_Overflow }
  472. if a.sign == .Negative {
  473. t := &Int{}
  474. defer destroy(t)
  475. internal_complement(t, a, allocator) or_return
  476. size_in_bits := internal_count_bits(t)
  477. i := 0
  478. #no_bounds_check for offset := 0; offset < size_in_bits; offset += 8 {
  479. bits, _ := internal_int_bitfield_extract(t, offset, 8)
  480. buf[i] = 255 - u8(bits & 255); i += 1
  481. }
  482. buf[l-1] = 255
  483. } else {
  484. size_in_bits := internal_count_bits(a)
  485. i := 0
  486. #no_bounds_check for offset := 0; offset < size_in_bits; offset += 8 {
  487. bits, _ := internal_int_bitfield_extract(a, offset, 8)
  488. buf[i] = u8(bits & 255); i += 1
  489. }
  490. }
  491. return
  492. }
  493. /*
  494. Return Python 3.x compatible Big Endian binary representation of `a`, either signed or unsigned.
  495. If `a` is negative when asking for an unsigned number, we return an error like Python does.
  496. */
  497. int_to_bytes_big_python :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  498. assert_if_nil(a)
  499. if !signed && a.sign == .Negative { return .Invalid_Argument }
  500. if a.sign == .Zero_or_Positive { return int_to_bytes_big(a, buf, signed, allocator) }
  501. l := len(buf)
  502. size_in_bytes := int_to_bytes_size(a, signed, allocator) or_return
  503. if size_in_bytes > l { return .Buffer_Overflow }
  504. t := &Int{}
  505. defer destroy(t)
  506. internal_complement(t, a, allocator) or_return
  507. size_in_bits := internal_count_bits(t)
  508. i := l - 1
  509. #no_bounds_check for offset := 0; offset < size_in_bits; offset += 8 {
  510. bits, _ := internal_int_bitfield_extract(t, offset, 8)
  511. buf[i] = 255 - u8(bits & 255); i -= 1
  512. }
  513. buf[0] = 255
  514. return
  515. }
  516. /*
  517. Read `Int` from a Big Endian binary representation.
  518. Sign is detected from the first byte if `signed` is true.
  519. */
  520. int_from_bytes_big :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  521. assert_if_nil(a)
  522. buf := buf
  523. l := len(buf)
  524. if l == 0 { return .Invalid_Argument }
  525. sign: Sign
  526. size_in_bits := l * 8
  527. if signed {
  528. /*
  529. First byte denotes the sign.
  530. */
  531. size_in_bits -= 8
  532. }
  533. size_in_digits := (size_in_bits + _DIGIT_BITS - 1) / _DIGIT_BITS
  534. size_in_digits += 0 if size_in_bits % 8 == 0 else 1
  535. internal_zero(a, false, allocator) or_return
  536. internal_grow(a, size_in_digits, false, allocator) or_return
  537. if signed {
  538. sign = .Zero_or_Positive if buf[0] == 0 else .Negative
  539. buf = buf[1:]
  540. }
  541. #no_bounds_check for v in buf {
  542. internal_shl(a, a, 8) or_return
  543. a.digit[0] |= DIGIT(v)
  544. }
  545. a.sign = sign
  546. a.used = size_in_digits
  547. return internal_clamp(a)
  548. }
  549. /*
  550. Read `Int` from a Big Endian Python binary representation.
  551. Sign is detected from the first byte if `signed` is true.
  552. */
  553. int_from_bytes_big_python :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  554. assert_if_nil(a)
  555. buf := buf
  556. l := len(buf)
  557. if l == 0 { return .Invalid_Argument }
  558. sign: Sign
  559. size_in_bits := l * 8
  560. if signed {
  561. /*
  562. First byte denotes the sign.
  563. */
  564. size_in_bits -= 8
  565. }
  566. size_in_digits := (size_in_bits + _DIGIT_BITS - 1) / _DIGIT_BITS
  567. size_in_digits += 0 if size_in_bits % 8 == 0 else 1
  568. internal_zero(a, false, allocator) or_return
  569. internal_grow(a, size_in_digits, false, allocator) or_return
  570. if signed {
  571. sign = .Zero_or_Positive if buf[0] == 0 else .Negative
  572. buf = buf[1:]
  573. }
  574. #no_bounds_check for v in buf {
  575. internal_shl(a, a, 8) or_return
  576. if signed && sign == .Negative {
  577. a.digit[0] |= DIGIT(255 - v)
  578. } else {
  579. a.digit[0] |= DIGIT(v)
  580. }
  581. }
  582. a.sign = sign
  583. a.used = size_in_digits
  584. internal_clamp(a) or_return
  585. if signed && sign == .Negative {
  586. return internal_sub(a, a, 1)
  587. }
  588. return nil
  589. }
  590. /*
  591. Read `Int` from a Little Endian binary representation.
  592. Sign is detected from the last byte if `signed` is true.
  593. */
  594. int_from_bytes_little :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  595. assert_if_nil(a)
  596. buf := buf
  597. l := len(buf)
  598. if l == 0 { return .Invalid_Argument }
  599. sign: Sign
  600. size_in_bits := l * 8
  601. if signed {
  602. /*
  603. First byte denotes the sign.
  604. */
  605. size_in_bits -= 8
  606. }
  607. size_in_digits := (size_in_bits + _DIGIT_BITS - 1) / _DIGIT_BITS
  608. size_in_digits += 0 if size_in_bits % 8 == 0 else 1
  609. internal_zero(a, false, allocator) or_return
  610. internal_grow(a, size_in_digits, false, allocator) or_return
  611. if signed {
  612. sign = .Zero_or_Positive if buf[l-1] == 0 else .Negative
  613. buf = buf[:l-1]
  614. l -= 1
  615. }
  616. for _, i in buf {
  617. internal_shl(a, a, 8) or_return
  618. a.digit[0] |= DIGIT(buf[l-i-1])
  619. }
  620. a.sign = sign
  621. a.used = size_in_digits
  622. return internal_clamp(a)
  623. }
  624. /*
  625. Read `Int` from a Little Endian Python binary representation.
  626. Sign is detected from the first byte if `signed` is true.
  627. */
  628. int_from_bytes_little_python :: proc(a: ^Int, buf: []u8, signed := false, allocator := context.allocator) -> (err: Error) {
  629. assert_if_nil(a)
  630. buf := buf
  631. l := len(buf)
  632. if l == 0 { return .Invalid_Argument }
  633. sign: Sign
  634. size_in_bits := l * 8
  635. if signed {
  636. /*
  637. First byte denotes the sign.
  638. */
  639. size_in_bits -= 8
  640. }
  641. size_in_digits := (size_in_bits + _DIGIT_BITS - 1) / _DIGIT_BITS
  642. size_in_digits += 0 if size_in_bits % 8 == 0 else 1
  643. internal_zero(a, false, allocator) or_return
  644. internal_grow(a, size_in_digits, false, allocator) or_return
  645. if signed {
  646. sign = .Zero_or_Positive if buf[l-1] == 0 else .Negative
  647. buf = buf[:l-1]
  648. l -= 1
  649. }
  650. for _, i in buf {
  651. internal_shl(a, a, 8) or_return
  652. if signed && sign == .Negative {
  653. a.digit[0] |= DIGIT(255 - buf[l-i-1])
  654. } else {
  655. a.digit[0] |= DIGIT(buf[l-i-1])
  656. }
  657. }
  658. a.sign = sign
  659. a.used = size_in_digits
  660. internal_clamp(a) or_return
  661. if signed && sign == .Negative {
  662. return internal_sub(a, a, 1)
  663. }
  664. return nil
  665. }
  666. /*
  667. Initialize constants.
  668. */
  669. INT_ONE, INT_ZERO, INT_MINUS_ONE, INT_INF, INT_MINUS_INF, INT_NAN := &Int{}, &Int{}, &Int{}, &Int{}, &Int{}, &Int{}
  670. initialize_constants :: proc() -> (res: int) {
  671. internal_set( INT_ZERO, 0); INT_ZERO.flags = {.Immutable}
  672. internal_set( INT_ONE, 1); INT_ONE.flags = {.Immutable}
  673. internal_set(INT_MINUS_ONE, -1); INT_MINUS_ONE.flags = {.Immutable}
  674. /*
  675. We set these special values to -1 or 1 so they don't get mistake for zero accidentally.
  676. This allows for shortcut tests of is_zero as .used == 0.
  677. */
  678. internal_set( INT_NAN, 1); INT_NAN.flags = {.Immutable, .NaN}
  679. internal_set( INT_INF, 1); INT_INF.flags = {.Immutable, .Inf}
  680. internal_set( INT_INF, -1); INT_MINUS_INF.flags = {.Immutable, .Inf}
  681. return _DEFAULT_MUL_KARATSUBA_CUTOFF
  682. }
  683. /*
  684. Destroy constants.
  685. Optional for an EXE, as this would be called at the very end of a process.
  686. */
  687. destroy_constants :: proc() {
  688. internal_destroy(INT_ONE, INT_ZERO, INT_MINUS_ONE, INT_INF, INT_MINUS_INF, INT_NAN)
  689. }
  690. assert_if_nil :: proc{
  691. assert_if_nil_int,
  692. assert_if_nil_rat,
  693. }
  694. assert_if_nil_int :: #force_inline proc(integers: ..^Int, loc := #caller_location) {
  695. for i in integers {
  696. assert(i != nil, "(nil)", loc)
  697. }
  698. }
  699. assert_if_nil_rat :: #force_inline proc(rationals: ..^Rat, loc := #caller_location) {
  700. for r in rationals {
  701. assert(r != nil, "(nil)", loc)
  702. }
  703. }