tbigint_backend.nim 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. import std/private/jsutils
  2. type JsBigIntImpl {.importc: "bigint".} = int
  3. type JsBigInt = distinct JsBigIntImpl
  4. doAssert JsBigInt isnot int
  5. func big*(integer: SomeInteger): JsBigInt {.importjs: "BigInt(#)".}
  6. func big*(integer: cstring): JsBigInt {.importjs: "BigInt(#)".}
  7. func `<=`*(x, y: JsBigInt): bool {.importjs: "(# $1 #)".}
  8. func `==`*(x, y: JsBigInt): bool {.importjs: "(# === #)".}
  9. func inc*(x: var JsBigInt) {.importjs: "[#][0][0]++".}
  10. func inc2*(x: var JsBigInt) {.importjs: "#++".}
  11. func toCstring*(this: JsBigInt): cstring {.importjs: "#.toString()".}
  12. func `$`*(this: JsBigInt): string =
  13. $toCstring(this)
  14. block:
  15. doAssert defined(nimHasJsBigIntBackend)
  16. let z1 = big"10"
  17. let z2 = big"15"
  18. doAssert z1 == big"10"
  19. doAssert z1 == z1
  20. doAssert z1 != z2
  21. var s: seq[cstring]
  22. for i in z1 .. z2:
  23. s.add $i
  24. doAssert s == @["10".cstring, "11", "12", "13", "14", "15"]
  25. block:
  26. var a=big"3"
  27. a.inc
  28. doAssert a == big"4"
  29. block:
  30. var z: JsBigInt
  31. doAssert $z == "0"
  32. doAssert z.jsTypeOf == "bigint" # would fail without codegen change
  33. doAssert z != big(1)
  34. doAssert z == big"0" # ditto
  35. # ditto below
  36. block:
  37. let z: JsBigInt = big"1"
  38. doAssert $z == "1"
  39. doAssert z.jsTypeOf == "bigint"
  40. doAssert z == big"1"
  41. block:
  42. let z = JsBigInt.default
  43. doAssert $z == "0"
  44. doAssert z.jsTypeOf == "bigint"
  45. doAssert z == big"0"
  46. block:
  47. var a: seq[JsBigInt]
  48. a.setLen 3
  49. doAssert a[^1].jsTypeOf == "bigint"
  50. doAssert a[^1] == big"0"