int128.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  1. ## This module is for compiler internal use only. For reliable error
  2. ## messages and range checks, the compiler needs a data type that can
  3. ## hold all from `low(BiggestInt)` to `high(BiggestUInt)`, This
  4. ## type is for that purpose.
  5. from std/math import trunc
  6. when defined(nimPreviewSlimSystem):
  7. import std/assertions
  8. type
  9. Int128* = object
  10. udata: array[4, uint32]
  11. template sdata(arg: Int128, idx: int): int32 =
  12. # udata and sdata was supposed to be in a union, but unions are
  13. # handled incorrectly in the VM.
  14. cast[ptr int32](arg.udata[idx].unsafeAddr)[]
  15. # encoding least significant int first (like LittleEndian)
  16. const
  17. Zero* = Int128(udata: [0'u32, 0, 0, 0])
  18. One* = Int128(udata: [1'u32, 0, 0, 0])
  19. Ten* = Int128(udata: [10'u32, 0, 0, 0])
  20. Min = Int128(udata: [0'u32, 0, 0, 0x80000000'u32])
  21. Max = Int128(udata: [high(uint32), high(uint32), high(uint32), uint32(high(int32))])
  22. NegOne* = Int128(udata: [0xffffffff'u32, 0xffffffff'u32, 0xffffffff'u32, 0xffffffff'u32])
  23. template low*(t: typedesc[Int128]): Int128 = Min
  24. template high*(t: typedesc[Int128]): Int128 = Max
  25. proc `$`*(a: Int128): string
  26. proc toInt128*[T: SomeInteger | bool](arg: T): Int128 =
  27. {.noSideEffect.}:
  28. when T is bool: result.sdata(0) = int32(arg)
  29. elif T is SomeUnsignedInt:
  30. when sizeof(arg) <= 4:
  31. result.udata[0] = uint32(arg)
  32. else:
  33. result.udata[0] = uint32(arg and T(0xffffffff))
  34. result.udata[1] = uint32(arg shr 32)
  35. elif sizeof(arg) <= 4:
  36. result.sdata(0) = int32(arg)
  37. if arg < 0: # sign extend
  38. result.sdata(1) = -1
  39. result.sdata(2) = -1
  40. result.sdata(3) = -1
  41. else:
  42. let tmp = int64(arg)
  43. result.udata[0] = uint32(tmp and 0xffffffff)
  44. result.sdata(1) = int32(tmp shr 32)
  45. if arg < 0: # sign extend
  46. result.sdata(2) = -1
  47. result.sdata(3) = -1
  48. template isNegative(arg: Int128): bool =
  49. arg.sdata(3) < 0
  50. proc bitconcat(a, b: uint32): uint64 =
  51. (uint64(a) shl 32) or uint64(b)
  52. proc toInt64*(arg: Int128): int64 =
  53. if isNegative(arg):
  54. assert(arg.sdata(3) == -1, "out of range")
  55. assert(arg.sdata(2) == -1, "out of range")
  56. else:
  57. assert(arg.sdata(3) == 0, "out of range")
  58. assert(arg.sdata(2) == 0, "out of range")
  59. cast[int64](bitconcat(arg.udata[1], arg.udata[0]))
  60. proc toInt64Checked*(arg: Int128; onError: int64): int64 =
  61. if isNegative(arg):
  62. if arg.sdata(3) != -1 or arg.sdata(2) != -1:
  63. return onError
  64. else:
  65. if arg.sdata(3) != 0 or arg.sdata(2) != 0:
  66. return onError
  67. return cast[int64](bitconcat(arg.udata[1], arg.udata[0]))
  68. proc toInt32*(arg: Int128): int32 =
  69. if isNegative(arg):
  70. assert(arg.sdata(3) == -1, "out of range")
  71. assert(arg.sdata(2) == -1, "out of range")
  72. assert(arg.sdata(1) == -1, "out of range")
  73. else:
  74. assert(arg.sdata(3) == 0, "out of range")
  75. assert(arg.sdata(2) == 0, "out of range")
  76. assert(arg.sdata(1) == 0, "out of range")
  77. arg.sdata(0)
  78. proc toInt16*(arg: Int128): int16 =
  79. if isNegative(arg):
  80. assert(arg.sdata(3) == -1, "out of range")
  81. assert(arg.sdata(2) == -1, "out of range")
  82. assert(arg.sdata(1) == -1, "out of range")
  83. else:
  84. assert(arg.sdata(3) == 0, "out of range")
  85. assert(arg.sdata(2) == 0, "out of range")
  86. assert(arg.sdata(1) == 0, "out of range")
  87. int16(arg.sdata(0))
  88. proc toInt8*(arg: Int128): int8 =
  89. if isNegative(arg):
  90. assert(arg.sdata(3) == -1, "out of range")
  91. assert(arg.sdata(2) == -1, "out of range")
  92. assert(arg.sdata(1) == -1, "out of range")
  93. else:
  94. assert(arg.sdata(3) == 0, "out of range")
  95. assert(arg.sdata(2) == 0, "out of range")
  96. assert(arg.sdata(1) == 0, "out of range")
  97. int8(arg.sdata(0))
  98. proc toInt*(arg: Int128): int =
  99. when sizeof(int) == 4:
  100. cast[int](toInt32(arg))
  101. else:
  102. cast[int](toInt64(arg))
  103. proc toUInt64*(arg: Int128): uint64 =
  104. assert(arg.udata[3] == 0)
  105. assert(arg.udata[2] == 0)
  106. bitconcat(arg.udata[1], arg.udata[0])
  107. proc toUInt32*(arg: Int128): uint32 =
  108. assert(arg.udata[3] == 0)
  109. assert(arg.udata[2] == 0)
  110. assert(arg.udata[1] == 0)
  111. arg.udata[0]
  112. proc toUInt16*(arg: Int128): uint16 =
  113. assert(arg.udata[3] == 0)
  114. assert(arg.udata[2] == 0)
  115. assert(arg.udata[1] == 0)
  116. uint16(arg.udata[0])
  117. proc toUInt8*(arg: Int128): uint8 =
  118. assert(arg.udata[3] == 0)
  119. assert(arg.udata[2] == 0)
  120. assert(arg.udata[1] == 0)
  121. uint8(arg.udata[0])
  122. proc toUInt*(arg: Int128): uint =
  123. when sizeof(int) == 4:
  124. cast[uint](toInt32(arg))
  125. else:
  126. cast[uint](toInt64(arg))
  127. proc castToInt64*(arg: Int128): int64 =
  128. ## Conversion to int64 without range check.
  129. cast[int64](bitconcat(arg.udata[1], arg.udata[0]))
  130. proc castToUInt64*(arg: Int128): uint64 =
  131. ## Conversion to uint64 without range check.
  132. cast[uint64](bitconcat(arg.udata[1], arg.udata[0]))
  133. proc addToHex(result: var string; arg: uint32) =
  134. for i in 0..<8:
  135. let idx = (arg shr ((7-i) * 4)) and 0xf
  136. result.add "0123456789abcdef"[idx]
  137. proc addToHex*(result: var string; arg: Int128) =
  138. var i = 3
  139. while i >= 0:
  140. result.addToHex(arg.udata[i])
  141. i -= 1
  142. proc toHex*(arg: Int128): string =
  143. result = ""
  144. result.addToHex(arg)
  145. proc inc*(a: var Int128, y: uint32 = 1) =
  146. a.udata[0] += y
  147. if unlikely(a.udata[0] < y):
  148. a.udata[1].inc
  149. if unlikely(a.udata[1] == 0):
  150. a.udata[2].inc
  151. if unlikely(a.udata[2] == 0):
  152. a.udata[3].inc
  153. doAssert(a.sdata(3) != low(int32), "overflow")
  154. proc cmp*(a, b: Int128): int =
  155. let tmp1 = cmp(a.sdata(3), b.sdata(3))
  156. if tmp1 != 0: return tmp1
  157. let tmp2 = cmp(a.udata[2], b.udata[2])
  158. if tmp2 != 0: return tmp2
  159. let tmp3 = cmp(a.udata[1], b.udata[1])
  160. if tmp3 != 0: return tmp3
  161. let tmp4 = cmp(a.udata[0], b.udata[0])
  162. return tmp4
  163. proc `<`*(a, b: Int128): bool =
  164. cmp(a, b) < 0
  165. proc `<=`*(a, b: Int128): bool =
  166. cmp(a, b) <= 0
  167. proc `==`*(a, b: Int128): bool =
  168. if a.udata[0] != b.udata[0]: return false
  169. if a.udata[1] != b.udata[1]: return false
  170. if a.udata[2] != b.udata[2]: return false
  171. if a.udata[3] != b.udata[3]: return false
  172. return true
  173. proc bitnot*(a: Int128): Int128 =
  174. result.udata[0] = not a.udata[0]
  175. result.udata[1] = not a.udata[1]
  176. result.udata[2] = not a.udata[2]
  177. result.udata[3] = not a.udata[3]
  178. proc bitand*(a, b: Int128): Int128 =
  179. result.udata[0] = a.udata[0] and b.udata[0]
  180. result.udata[1] = a.udata[1] and b.udata[1]
  181. result.udata[2] = a.udata[2] and b.udata[2]
  182. result.udata[3] = a.udata[3] and b.udata[3]
  183. proc bitor*(a, b: Int128): Int128 =
  184. result.udata[0] = a.udata[0] or b.udata[0]
  185. result.udata[1] = a.udata[1] or b.udata[1]
  186. result.udata[2] = a.udata[2] or b.udata[2]
  187. result.udata[3] = a.udata[3] or b.udata[3]
  188. proc bitxor*(a, b: Int128): Int128 =
  189. result.udata[0] = a.udata[0] xor b.udata[0]
  190. result.udata[1] = a.udata[1] xor b.udata[1]
  191. result.udata[2] = a.udata[2] xor b.udata[2]
  192. result.udata[3] = a.udata[3] xor b.udata[3]
  193. proc `shr`*(a: Int128, b: int): Int128 =
  194. let b = b and 127
  195. if b < 32:
  196. result.sdata(3) = a.sdata(3) shr b
  197. result.udata[2] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr b)
  198. result.udata[1] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr b)
  199. result.udata[0] = cast[uint32](bitconcat(a.udata[1], a.udata[0]) shr b)
  200. elif b < 64:
  201. if isNegative(a):
  202. result.sdata(3) = -1
  203. result.sdata(2) = a.sdata(3) shr (b and 31)
  204. result.udata[1] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
  205. result.udata[0] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr (b and 31))
  206. elif b < 96:
  207. if isNegative(a):
  208. result.sdata(3) = -1
  209. result.sdata(2) = -1
  210. result.sdata(1) = a.sdata(3) shr (b and 31)
  211. result.udata[0] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
  212. else: # b < 128
  213. if isNegative(a):
  214. result.sdata(3) = -1
  215. result.sdata(2) = -1
  216. result.sdata(1) = -1
  217. result.sdata(0) = a.sdata(3) shr (b and 31)
  218. proc `shl`*(a: Int128, b: int): Int128 =
  219. let b = b and 127
  220. if b < 32:
  221. result.udata[0] = a.udata[0] shl b
  222. result.udata[1] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl b) shr 32)
  223. result.udata[2] = cast[uint32]((bitconcat(a.udata[2], a.udata[1]) shl b) shr 32)
  224. result.udata[3] = cast[uint32]((bitconcat(a.udata[3], a.udata[2]) shl b) shr 32)
  225. elif b < 64:
  226. result.udata[0] = 0
  227. result.udata[1] = a.udata[0] shl (b and 31)
  228. result.udata[2] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl (b and 31)) shr 32)
  229. result.udata[3] = cast[uint32]((bitconcat(a.udata[2], a.udata[1]) shl (b and 31)) shr 32)
  230. elif b < 96:
  231. result.udata[0] = 0
  232. result.udata[1] = 0
  233. result.udata[2] = a.udata[0] shl (b and 31)
  234. result.udata[3] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl (b and 31)) shr 32)
  235. else:
  236. result.udata[0] = 0
  237. result.udata[1] = 0
  238. result.udata[2] = 0
  239. result.udata[3] = a.udata[0] shl (b and 31)
  240. proc `+`*(a, b: Int128): Int128 =
  241. let tmp0 = uint64(a.udata[0]) + uint64(b.udata[0])
  242. result.udata[0] = cast[uint32](tmp0)
  243. let tmp1 = uint64(a.udata[1]) + uint64(b.udata[1]) + (tmp0 shr 32)
  244. result.udata[1] = cast[uint32](tmp1)
  245. let tmp2 = uint64(a.udata[2]) + uint64(b.udata[2]) + (tmp1 shr 32)
  246. result.udata[2] = cast[uint32](tmp2)
  247. let tmp3 = uint64(a.udata[3]) + uint64(b.udata[3]) + (tmp2 shr 32)
  248. result.udata[3] = cast[uint32](tmp3)
  249. proc `+=`*(a: var Int128, b: Int128) =
  250. a = a + b
  251. proc `-`*(a: Int128): Int128 =
  252. result = bitnot(a)
  253. result.inc
  254. proc `-`*(a, b: Int128): Int128 =
  255. a + (-b)
  256. proc `-=`*(a: var Int128, b: Int128) =
  257. a = a - b
  258. proc abs*(a: Int128): Int128 =
  259. if isNegative(a):
  260. -a
  261. else:
  262. a
  263. proc abs(a: int32): int =
  264. if a < 0: -a else: a
  265. proc `*`(a: Int128, b: uint32): Int128 =
  266. let tmp0 = uint64(a.udata[0]) * uint64(b)
  267. let tmp1 = uint64(a.udata[1]) * uint64(b)
  268. let tmp2 = uint64(a.udata[2]) * uint64(b)
  269. let tmp3 = uint64(a.udata[3]) * uint64(b)
  270. if unlikely(tmp3 > uint64(high(int32))):
  271. assert(false, "overflow")
  272. result.udata[0] = cast[uint32](tmp0)
  273. result.udata[1] = cast[uint32](tmp1) + cast[uint32](tmp0 shr 32)
  274. result.udata[2] = cast[uint32](tmp2) + cast[uint32](tmp1 shr 32)
  275. result.udata[3] = cast[uint32](tmp3) + cast[uint32](tmp2 shr 32)
  276. proc `*`*(a: Int128, b: int32): Int128 =
  277. result = a * cast[uint32](abs(b))
  278. if b < 0:
  279. result = -result
  280. proc `*=`(a: var Int128, b: int32) =
  281. a = a * b
  282. proc makeInt128(high, low: uint64): Int128 =
  283. result.udata[0] = cast[uint32](low)
  284. result.udata[1] = cast[uint32](low shr 32)
  285. result.udata[2] = cast[uint32](high)
  286. result.udata[3] = cast[uint32](high shr 32)
  287. proc high64(a: Int128): uint64 =
  288. bitconcat(a.udata[3], a.udata[2])
  289. proc low64(a: Int128): uint64 =
  290. bitconcat(a.udata[1], a.udata[0])
  291. proc `*`*(lhs, rhs: Int128): Int128 =
  292. let a32 = uint64(lhs.udata[1])
  293. let a00 = uint64(lhs.udata[0])
  294. let b32 = uint64(rhs.udata[1])
  295. let b00 = uint64(rhs.udata[0])
  296. result = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
  297. result += toInt128(a32 * b00) shl 32
  298. result += toInt128(a00 * b32) shl 32
  299. proc `*=`*(a: var Int128, b: Int128) =
  300. a = a * b
  301. import std/bitops
  302. proc fastLog2*(a: Int128): int =
  303. result = 0
  304. if a.udata[3] != 0:
  305. return 96 + fastLog2(a.udata[3])
  306. if a.udata[2] != 0:
  307. return 64 + fastLog2(a.udata[2])
  308. if a.udata[1] != 0:
  309. return 32 + fastLog2(a.udata[1])
  310. if a.udata[0] != 0:
  311. return fastLog2(a.udata[0])
  312. proc divMod*(dividend, divisor: Int128): tuple[quotient, remainder: Int128] =
  313. assert(divisor != Zero)
  314. let isNegativeA = isNegative(dividend)
  315. let isNegativeB = isNegative(divisor)
  316. var dividend = abs(dividend)
  317. let divisor = abs(divisor)
  318. if divisor > dividend:
  319. result.quotient = Zero
  320. if isNegativeA:
  321. result.remainder = -dividend
  322. else:
  323. result.remainder = dividend
  324. return
  325. if divisor == dividend:
  326. if isNegativeA xor isNegativeB:
  327. result.quotient = NegOne
  328. else:
  329. result.quotient = One
  330. result.remainder = Zero
  331. return
  332. var denominator = divisor
  333. var quotient = Zero
  334. # Left aligns the MSB of the denominator and the dividend.
  335. let shift = fastLog2(dividend) - fastLog2(denominator)
  336. denominator = denominator shl shift
  337. # Uses shift-subtract algorithm to divide dividend by denominator. The
  338. # remainder will be left in dividend.
  339. for i in 0..shift:
  340. quotient = quotient shl 1
  341. if dividend >= denominator:
  342. dividend -= denominator
  343. quotient = bitor(quotient, One)
  344. denominator = denominator shr 1
  345. if isNegativeA xor isNegativeB:
  346. result.quotient = -quotient
  347. else:
  348. result.quotient = quotient
  349. if isNegativeA:
  350. result.remainder = -dividend
  351. else:
  352. result.remainder = dividend
  353. proc `div`*(a, b: Int128): Int128 =
  354. let (a, _) = divMod(a, b)
  355. return a
  356. proc `mod`*(a, b: Int128): Int128 =
  357. let (_, b) = divMod(a, b)
  358. return b
  359. proc addInt128*(result: var string; value: Int128) =
  360. let initialSize = result.len
  361. if value == Zero:
  362. result.add '0'
  363. elif value == low(Int128):
  364. result.add "-170141183460469231731687303715884105728"
  365. else:
  366. let isNegative = isNegative(value)
  367. var value = abs(value)
  368. while value > Zero:
  369. let (quot, rem) = divMod(value, Ten)
  370. result.add "0123456789"[rem.toInt64]
  371. value = quot
  372. if isNegative:
  373. result.add '-'
  374. var i = initialSize
  375. var j = high(result)
  376. while i < j:
  377. swap(result[i], result[j])
  378. i += 1
  379. j -= 1
  380. proc `$`*(a: Int128): string =
  381. # "-170141183460469231731687303715884105728".len == 41
  382. result = newStringOfCap(41)
  383. result.addInt128(a)
  384. proc parseDecimalInt128*(arg: string, pos: int = 0): Int128 =
  385. assert(pos < arg.len)
  386. assert(arg[pos] in {'-', '0'..'9'})
  387. var isNegative = false
  388. var pos = pos
  389. if arg[pos] == '-':
  390. isNegative = true
  391. pos += 1
  392. result = Zero
  393. while pos < arg.len and arg[pos] in '0'..'9':
  394. result = result * Ten
  395. result.inc(uint32(arg[pos]) - uint32('0'))
  396. pos += 1
  397. if isNegative:
  398. result = -result
  399. # fluff
  400. proc `<`*(a: Int128, b: BiggestInt): bool =
  401. cmp(a, toInt128(b)) < 0
  402. proc `<`*(a: BiggestInt, b: Int128): bool =
  403. cmp(toInt128(a), b) < 0
  404. proc `<=`*(a: Int128, b: BiggestInt): bool =
  405. cmp(a, toInt128(b)) <= 0
  406. proc `<=`*(a: BiggestInt, b: Int128): bool =
  407. cmp(toInt128(a), b) <= 0
  408. proc `==`*(a: Int128, b: BiggestInt): bool =
  409. a == toInt128(b)
  410. proc `==`*(a: BiggestInt, b: Int128): bool =
  411. toInt128(a) == b
  412. proc `-`*(a: BiggestInt, b: Int128): Int128 =
  413. toInt128(a) - b
  414. proc `-`*(a: Int128, b: BiggestInt): Int128 =
  415. a - toInt128(b)
  416. proc `+`*(a: BiggestInt, b: Int128): Int128 =
  417. toInt128(a) + b
  418. proc `+`*(a: Int128, b: BiggestInt): Int128 =
  419. a + toInt128(b)
  420. proc toFloat64*(arg: Int128): float64 =
  421. let isNegative = isNegative(arg)
  422. let arg = abs(arg)
  423. let a = float64(bitconcat(arg.udata[1], arg.udata[0]))
  424. let b = float64(bitconcat(arg.udata[3], arg.udata[2]))
  425. result = a + 18446744073709551616'f64 * b # a + 2^64 * b
  426. if isNegative:
  427. result = -result
  428. proc ldexp(x: float64, exp: cint): float64 {.importc: "ldexp", header: "<math.h>".}
  429. template bitor(a, b, c: Int128): Int128 = bitor(bitor(a, b), c)
  430. proc toInt128*(arg: float64): Int128 =
  431. let isNegative = arg < 0
  432. let v0 = ldexp(abs(arg), -100)
  433. let w0 = uint64(trunc(v0))
  434. let v1 = ldexp(v0 - float64(w0), 50)
  435. let w1 = uint64(trunc(v1))
  436. let v2 = ldexp(v1 - float64(w1), 50)
  437. let w2 = uint64(trunc(v2))
  438. let res = bitor(toInt128(w0) shl 100, toInt128(w1) shl 50, toInt128(w2))
  439. if isNegative:
  440. return -res
  441. else:
  442. return res
  443. proc maskUInt64*(arg: Int128): Int128 {.noinit, inline.} =
  444. result.udata[0] = arg.udata[0]
  445. result.udata[1] = arg.udata[1]
  446. result.udata[2] = 0
  447. result.udata[3] = 0
  448. proc maskUInt32*(arg: Int128): Int128 {.noinit, inline.} =
  449. result.udata[0] = arg.udata[0]
  450. result.udata[1] = 0
  451. result.udata[2] = 0
  452. result.udata[3] = 0
  453. proc maskUInt16*(arg: Int128): Int128 {.noinit, inline.} =
  454. result.udata[0] = arg.udata[0] and 0xffff
  455. result.udata[1] = 0
  456. result.udata[2] = 0
  457. result.udata[3] = 0
  458. proc maskUInt8*(arg: Int128): Int128 {.noinit, inline.} =
  459. result.udata[0] = arg.udata[0] and 0xff
  460. result.udata[1] = 0
  461. result.udata[2] = 0
  462. result.udata[3] = 0
  463. proc maskBytes*(arg: Int128, numbytes: int): Int128 {.noinit.} =
  464. case numbytes
  465. of 1:
  466. return maskUInt8(arg)
  467. of 2:
  468. return maskUInt16(arg)
  469. of 4:
  470. return maskUInt32(arg)
  471. of 8:
  472. return maskUInt64(arg)
  473. else:
  474. raiseAssert "masking only implemented for 1, 2, 4 and 8 bytes"