int128.nim 16 KB

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