int128.nim 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. {.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.addToHex(arg)
  144. proc inc*(a: var Int128, y: uint32 = 1) =
  145. a.udata[0] += y
  146. if unlikely(a.udata[0] < y):
  147. a.udata[1].inc
  148. if unlikely(a.udata[1] == 0):
  149. a.udata[2].inc
  150. if unlikely(a.udata[2] == 0):
  151. a.udata[3].inc
  152. doAssert(a.sdata(3) != low(int32), "overflow")
  153. proc cmp*(a, b: Int128): int =
  154. let tmp1 = cmp(a.sdata(3), b.sdata(3))
  155. if tmp1 != 0: return tmp1
  156. let tmp2 = cmp(a.udata[2], b.udata[2])
  157. if tmp2 != 0: return tmp2
  158. let tmp3 = cmp(a.udata[1], b.udata[1])
  159. if tmp3 != 0: return tmp3
  160. let tmp4 = cmp(a.udata[0], b.udata[0])
  161. return tmp4
  162. proc `<`*(a, b: Int128): bool =
  163. cmp(a, b) < 0
  164. proc `<=`*(a, b: Int128): bool =
  165. cmp(a, b) <= 0
  166. proc `==`*(a, b: Int128): bool =
  167. if a.udata[0] != b.udata[0]: return false
  168. if a.udata[1] != b.udata[1]: return false
  169. if a.udata[2] != b.udata[2]: return false
  170. if a.udata[3] != b.udata[3]: return false
  171. return true
  172. proc bitnot*(a: Int128): Int128 =
  173. result.udata[0] = not a.udata[0]
  174. result.udata[1] = not a.udata[1]
  175. result.udata[2] = not a.udata[2]
  176. result.udata[3] = not a.udata[3]
  177. proc bitand*(a, b: Int128): Int128 =
  178. result.udata[0] = a.udata[0] and b.udata[0]
  179. result.udata[1] = a.udata[1] and b.udata[1]
  180. result.udata[2] = a.udata[2] and b.udata[2]
  181. result.udata[3] = a.udata[3] and b.udata[3]
  182. proc bitor*(a, b: Int128): Int128 =
  183. result.udata[0] = a.udata[0] or b.udata[0]
  184. result.udata[1] = a.udata[1] or b.udata[1]
  185. result.udata[2] = a.udata[2] or b.udata[2]
  186. result.udata[3] = a.udata[3] or b.udata[3]
  187. proc bitxor*(a, b: Int128): Int128 =
  188. result.udata[0] = a.udata[0] xor b.udata[0]
  189. result.udata[1] = a.udata[1] xor b.udata[1]
  190. result.udata[2] = a.udata[2] xor b.udata[2]
  191. result.udata[3] = a.udata[3] xor b.udata[3]
  192. proc `shr`*(a: Int128, b: int): Int128 =
  193. let b = b and 127
  194. if b < 32:
  195. result.sdata(3) = a.sdata(3) shr b
  196. result.udata[2] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr b)
  197. result.udata[1] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr b)
  198. result.udata[0] = cast[uint32](bitconcat(a.udata[1], a.udata[0]) shr b)
  199. elif b < 64:
  200. if isNegative(a):
  201. result.sdata(3) = -1
  202. result.sdata(2) = a.sdata(3) shr (b and 31)
  203. result.udata[1] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
  204. result.udata[0] = cast[uint32](bitconcat(a.udata[2], a.udata[1]) shr (b and 31))
  205. elif b < 96:
  206. if isNegative(a):
  207. result.sdata(3) = -1
  208. result.sdata(2) = -1
  209. result.sdata(1) = a.sdata(3) shr (b and 31)
  210. result.udata[0] = cast[uint32](bitconcat(a.udata[3], a.udata[2]) shr (b and 31))
  211. else: # b < 128
  212. if isNegative(a):
  213. result.sdata(3) = -1
  214. result.sdata(2) = -1
  215. result.sdata(1) = -1
  216. result.sdata(0) = a.sdata(3) shr (b and 31)
  217. proc `shl`*(a: Int128, b: int): Int128 =
  218. let b = b and 127
  219. if b < 32:
  220. result.udata[0] = a.udata[0] shl b
  221. result.udata[1] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl b) shr 32)
  222. result.udata[2] = cast[uint32]((bitconcat(a.udata[2], a.udata[1]) shl b) shr 32)
  223. result.udata[3] = cast[uint32]((bitconcat(a.udata[3], a.udata[2]) shl b) shr 32)
  224. elif b < 64:
  225. result.udata[0] = 0
  226. result.udata[1] = a.udata[0] shl (b and 31)
  227. result.udata[2] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl (b and 31)) shr 32)
  228. result.udata[3] = cast[uint32]((bitconcat(a.udata[2], a.udata[1]) shl (b and 31)) shr 32)
  229. elif b < 96:
  230. result.udata[0] = 0
  231. result.udata[1] = 0
  232. result.udata[2] = a.udata[0] shl (b and 31)
  233. result.udata[3] = cast[uint32]((bitconcat(a.udata[1], a.udata[0]) shl (b and 31)) shr 32)
  234. else:
  235. result.udata[0] = 0
  236. result.udata[1] = 0
  237. result.udata[2] = 0
  238. result.udata[3] = a.udata[0] shl (b and 31)
  239. proc `+`*(a, b: Int128): Int128 =
  240. let tmp0 = uint64(a.udata[0]) + uint64(b.udata[0])
  241. result.udata[0] = cast[uint32](tmp0)
  242. let tmp1 = uint64(a.udata[1]) + uint64(b.udata[1]) + (tmp0 shr 32)
  243. result.udata[1] = cast[uint32](tmp1)
  244. let tmp2 = uint64(a.udata[2]) + uint64(b.udata[2]) + (tmp1 shr 32)
  245. result.udata[2] = cast[uint32](tmp2)
  246. let tmp3 = uint64(a.udata[3]) + uint64(b.udata[3]) + (tmp2 shr 32)
  247. result.udata[3] = cast[uint32](tmp3)
  248. proc `+=`*(a: var Int128, b: Int128) =
  249. a = a + b
  250. proc `-`*(a: Int128): Int128 =
  251. result = bitnot(a)
  252. result.inc
  253. proc `-`*(a, b: Int128): Int128 =
  254. a + (-b)
  255. proc `-=`*(a: var Int128, b: Int128) =
  256. a = a - b
  257. proc abs*(a: Int128): Int128 =
  258. if isNegative(a):
  259. -a
  260. else:
  261. a
  262. proc abs(a: int32): int =
  263. if a < 0: -a else: a
  264. proc `*`(a: Int128, b: uint32): Int128 =
  265. let tmp0 = uint64(a.udata[0]) * uint64(b)
  266. let tmp1 = uint64(a.udata[1]) * uint64(b)
  267. let tmp2 = uint64(a.udata[2]) * uint64(b)
  268. let tmp3 = uint64(a.udata[3]) * uint64(b)
  269. if unlikely(tmp3 > uint64(high(int32))):
  270. assert(false, "overflow")
  271. result.udata[0] = cast[uint32](tmp0)
  272. result.udata[1] = cast[uint32](tmp1) + cast[uint32](tmp0 shr 32)
  273. result.udata[2] = cast[uint32](tmp2) + cast[uint32](tmp1 shr 32)
  274. result.udata[3] = cast[uint32](tmp3) + cast[uint32](tmp2 shr 32)
  275. proc `*`*(a: Int128, b: int32): Int128 =
  276. result = a * cast[uint32](abs(b))
  277. if b < 0:
  278. result = -result
  279. proc `*=`*(a: var Int128, b: int32): Int128 =
  280. result = result * b
  281. proc makeInt128(high, low: uint64): Int128 =
  282. result.udata[0] = cast[uint32](low)
  283. result.udata[1] = cast[uint32](low shr 32)
  284. result.udata[2] = cast[uint32](high)
  285. result.udata[3] = cast[uint32](high shr 32)
  286. proc high64(a: Int128): uint64 =
  287. bitconcat(a.udata[3], a.udata[2])
  288. proc low64(a: Int128): uint64 =
  289. bitconcat(a.udata[1], a.udata[0])
  290. proc `*`*(lhs, rhs: Int128): Int128 =
  291. let a32 = uint64(lhs.udata[1])
  292. let a00 = uint64(lhs.udata[0])
  293. let b32 = uint64(rhs.udata[1])
  294. let b00 = uint64(rhs.udata[0])
  295. result = makeInt128(high64(lhs) * low64(rhs) + low64(lhs) * high64(rhs) + a32 * b32, a00 * b00)
  296. result += toInt128(a32 * b00) shl 32
  297. result += toInt128(a00 * b32) shl 32
  298. proc `*=`*(a: var Int128, b: Int128) =
  299. a = a * b
  300. import bitops
  301. proc fastLog2*(a: Int128): int =
  302. if a.udata[3] != 0:
  303. return 96 + fastLog2(a.udata[3])
  304. if a.udata[2] != 0:
  305. return 64 + fastLog2(a.udata[2])
  306. if a.udata[1] != 0:
  307. return 32 + fastLog2(a.udata[1])
  308. if a.udata[0] != 0:
  309. return fastLog2(a.udata[0])
  310. proc divMod*(dividend, divisor: Int128): tuple[quotient, remainder: Int128] =
  311. assert(divisor != Zero)
  312. let isNegativeA = isNegative(dividend)
  313. let isNegativeB = isNegative(divisor)
  314. var dividend = abs(dividend)
  315. let divisor = abs(divisor)
  316. if divisor > dividend:
  317. result.quotient = Zero
  318. if isNegativeA:
  319. result.remainder = -dividend
  320. else:
  321. result.remainder = dividend
  322. return
  323. if divisor == dividend:
  324. if isNegativeA xor isNegativeB:
  325. result.quotient = NegOne
  326. else:
  327. result.quotient = One
  328. result.remainder = Zero
  329. return
  330. var denominator = divisor
  331. var quotient = Zero
  332. # Left aligns the MSB of the denominator and the dividend.
  333. let shift = fastLog2(dividend) - fastLog2(denominator)
  334. denominator = denominator shl shift
  335. # Uses shift-subtract algorithm to divide dividend by denominator. The
  336. # remainder will be left in dividend.
  337. for i in 0..shift:
  338. quotient = quotient shl 1
  339. if dividend >= denominator:
  340. dividend -= denominator
  341. quotient = bitor(quotient, One)
  342. denominator = denominator shr 1
  343. if isNegativeA xor isNegativeB:
  344. result.quotient = -quotient
  345. else:
  346. result.quotient = quotient
  347. if isNegativeA:
  348. result.remainder = -dividend
  349. else:
  350. result.remainder = dividend
  351. proc `div`*(a, b: Int128): Int128 =
  352. let (a, _) = divMod(a, b)
  353. return a
  354. proc `mod`*(a, b: Int128): Int128 =
  355. let (_, b) = divMod(a, b)
  356. return b
  357. proc addInt128*(result: var string; value: Int128) =
  358. let initialSize = result.len
  359. if value == Zero:
  360. result.add '0'
  361. elif value == low(Int128):
  362. result.add "-170141183460469231731687303715884105728"
  363. else:
  364. let isNegative = isNegative(value)
  365. var value = abs(value)
  366. while value > Zero:
  367. let (quot, rem) = divMod(value, Ten)
  368. result.add "0123456789"[rem.toInt64]
  369. value = quot
  370. if isNegative:
  371. result.add '-'
  372. var i = initialSize
  373. var j = high(result)
  374. while i < j:
  375. swap(result[i], result[j])
  376. i += 1
  377. j -= 1
  378. proc `$`*(a: Int128): string =
  379. # "-170141183460469231731687303715884105728".len == 41
  380. result = newStringOfCap(41)
  381. result.addInt128(a)
  382. proc parseDecimalInt128*(arg: string, pos: int = 0): Int128 =
  383. assert(pos < arg.len)
  384. assert(arg[pos] in {'-', '0'..'9'})
  385. var isNegative = false
  386. var pos = pos
  387. if arg[pos] == '-':
  388. isNegative = true
  389. pos += 1
  390. result = Zero
  391. while pos < arg.len and arg[pos] in '0'..'9':
  392. result = result * Ten
  393. result.inc(uint32(arg[pos]) - uint32('0'))
  394. pos += 1
  395. if isNegative:
  396. result = -result
  397. # fluff
  398. proc `<`*(a: Int128, b: BiggestInt): bool =
  399. cmp(a, toInt128(b)) < 0
  400. proc `<`*(a: BiggestInt, b: Int128): bool =
  401. cmp(toInt128(a), b) < 0
  402. proc `<=`*(a: Int128, b: BiggestInt): bool =
  403. cmp(a, toInt128(b)) <= 0
  404. proc `<=`*(a: BiggestInt, b: Int128): bool =
  405. cmp(toInt128(a), b) <= 0
  406. proc `==`*(a: Int128, b: BiggestInt): bool =
  407. a == toInt128(b)
  408. proc `==`*(a: BiggestInt, b: Int128): bool =
  409. toInt128(a) == b
  410. proc `-`*(a: BiggestInt, b: Int128): Int128 =
  411. toInt128(a) - b
  412. proc `-`*(a: Int128, b: BiggestInt): Int128 =
  413. a - toInt128(b)
  414. proc `+`*(a: BiggestInt, b: Int128): Int128 =
  415. toInt128(a) + b
  416. proc `+`*(a: Int128, b: BiggestInt): Int128 =
  417. a + toInt128(b)
  418. proc toFloat64*(arg: Int128): float64 =
  419. let isNegative = isNegative(arg)
  420. let arg = abs(arg)
  421. let a = float64(bitconcat(arg.udata[1], arg.udata[0]))
  422. let b = float64(bitconcat(arg.udata[3], arg.udata[2]))
  423. result = a + 18446744073709551616'f64 * b # a + 2^64 * b
  424. if isNegative:
  425. result = -result
  426. proc ldexp(x: float64, exp: cint): float64 {.importc: "ldexp", header: "<math.h>".}
  427. template bitor(a, b, c: Int128): Int128 = bitor(bitor(a, b), c)
  428. proc toInt128*(arg: float64): Int128 =
  429. let isNegative = arg < 0
  430. let v0 = ldexp(abs(arg), -100)
  431. let w0 = uint64(trunc(v0))
  432. let v1 = ldexp(v0 - float64(w0), 50)
  433. let w1 = uint64(trunc(v1))
  434. let v2 = ldexp(v1 - float64(w1), 50)
  435. let w2 = uint64(trunc(v2))
  436. let res = bitor(toInt128(w0) shl 100, toInt128(w1) shl 50, toInt128(w2))
  437. if isNegative:
  438. return -res
  439. else:
  440. return res
  441. proc maskUInt64*(arg: Int128): Int128 {.noinit, inline.} =
  442. result.udata[0] = arg.udata[0]
  443. result.udata[1] = arg.udata[1]
  444. result.udata[2] = 0
  445. result.udata[3] = 0
  446. proc maskUInt32*(arg: Int128): Int128 {.noinit, inline.} =
  447. result.udata[0] = arg.udata[0]
  448. result.udata[1] = 0
  449. result.udata[2] = 0
  450. result.udata[3] = 0
  451. proc maskUInt16*(arg: Int128): Int128 {.noinit, inline.} =
  452. result.udata[0] = arg.udata[0] and 0xffff
  453. result.udata[1] = 0
  454. result.udata[2] = 0
  455. result.udata[3] = 0
  456. proc maskUInt8*(arg: Int128): Int128 {.noinit, inline.} =
  457. result.udata[0] = arg.udata[0] and 0xff
  458. result.udata[1] = 0
  459. result.udata[2] = 0
  460. result.udata[3] = 0
  461. proc maskBytes*(arg: Int128, numbytes: int): Int128 {.noinit.} =
  462. case numbytes
  463. of 1:
  464. return maskUInt8(arg)
  465. of 2:
  466. return maskUInt16(arg)
  467. of 4:
  468. return maskUInt32(arg)
  469. of 8:
  470. return maskUInt64(arg)
  471. else:
  472. assert(false, "masking only implemented for 1, 2, 4 and 8 bytes")