nim-stint/stint/private/datatypes.nim

160 lines
4.6 KiB
Nim
Raw Normal View History

# Stint
# Copyright 2018 Status Research & Development GmbH
# Licensed under either of
#
# * Apache License, version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0)
# * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT)
#
# at your option. This file may not be copied, modified, or distributed except according to those terms.
2020-06-12 16:37:02 +00:00
import
# Status lib
stew/bitops2
2020-06-12 16:37:02 +00:00
when sizeof(int) == 8 and not defined(Stint32):
type
Word* = uint64
SignedWord* = int64
else:
type
Word* = uint32
SignedWord* = int32
2020-06-12 17:23:03 +00:00
const WordBitWidth* = sizeof(Word) * 8
2020-06-12 16:37:02 +00:00
func wordsRequired*(bits: int): int {.compileTime.} =
## Compute the number of limbs required
## for the **announced** bit length
2020-06-12 16:37:02 +00:00
(bits + WordBitWidth - 1) div WordBitWidth
type
2020-06-12 17:01:05 +00:00
Limbs*[N: static int] = array[N, Word]
## Limbs type
2018-04-25 10:52:00 +00:00
StUint*[bits: static[int]] = object
2020-06-12 16:37:02 +00:00
## Stack-based integer
## Unsigned
limbs*: array[bits.wordsRequired, Word]
# Limbs-Endianess is little-endian
2023-06-13 01:14:52 +00:00
StInt*[bits: static[int]] = object
## Stack-based integer
## Signed
2023-06-13 12:03:43 +00:00
imp*: StUint[bits]
2023-06-13 01:14:52 +00:00
# {.borrow: `.`.} only works with nim-devel
# StInt*[bits: static[int]] {.borrow: `.`.} = distinct StUint[bits]
## Stack-based integer
## Signed
2020-06-12 16:37:02 +00:00
Carry* = uint8 # distinct range[0'u8 .. 1]
Borrow* = uint8 # distinct range[0'u8 .. 1]
2023-06-12 14:07:15 +00:00
SomeBigInteger*[bits: static[int]] = StUint[bits] | StInt[bits]
2020-06-12 16:37:02 +00:00
const GCC_Compatible* = defined(gcc) or defined(clang) or defined(llvm_gcc)
const X86* = defined(amd64) or defined(i386)
2020-06-12 16:37:02 +00:00
when sizeof(int) == 8 and GCC_Compatible:
type
uint128*{.importc: "unsigned __int128".} = object
2022-04-07 07:52:36 +00:00
# Bithacks
# --------------------------------------------------------
2023-06-12 14:07:15 +00:00
{.push raises: [], inline, noinit, gcsafe.}
template clearExtraBitsOverMSB*(a: var StUint) =
## A Stuint is stored in an array of 32 of 64-bit word
## If we do bit manipulation at the word level,
## for example a 8-bit stuint stored in a 64-bit word
## we need to clear the upper 56-bit
when a.bits != a.limbs.len * WordBitWidth:
const posExtraBits = a.bits - (a.limbs.len-1) * WordBitWidth
const mask = (Word(1) shl posExtraBits) - 1
a[^1] = a[^1] and mask
func usedBitsAndWords*(a: openArray[Word]): tuple[bits, words: int] =
## Returns the number of used words and bits in a bigInt
## Returns (0, 0) for all-zeros array (even if technically you need 1 bit and 1 word to encode zero)
var clz = 0
# Count Leading Zeros
for i in countdown(a.len-1, 0):
let count = log2trunc(a[i])
# debugEcho "count: ", count, ", a[", i, "]: ", a[i].toBin(64)
if count == -1:
clz += WordBitWidth
else:
clz += WordBitWidth - count - 1
return (a.len*WordBitWidth - clz, i+1)
return (0, 0)
{.pop.}
# Accessors
# --------------------------------------------------------
2023-06-13 12:03:43 +00:00
template limbs*(a: StInt): untyped =
# TODO: remove this when we switch to borrow `.`
a.imp.limbs
2023-06-13 12:51:49 +00:00
template `[]`*(a: StInt, i: SomeInteger or BackwardsIndex): Word =
a.imp.limbs[i]
template `[]=`*(a: var StInt, i: SomeInteger or BackwardsIndex, val: Word) =
a.imp.limbs[i] = val
2023-06-13 12:03:43 +00:00
2023-06-14 02:52:56 +00:00
template `[]`*(a: StUint, i: SomeInteger or BackwardsIndex): Word =
a.limbs[i]
2023-06-14 02:52:56 +00:00
template `[]=`*(a: var StUint, i: SomeInteger or BackwardsIndex, val: Word) =
a.limbs[i] = val
# Iterations
# --------------------------------------------------------
2020-06-12 18:05:40 +00:00
import std/macros
proc replaceNodes(ast: NimNode, what: NimNode, by: NimNode): NimNode =
# Replace "what" ident node by "by"
proc inspect(node: NimNode): NimNode =
case node.kind:
of {nnkIdent, nnkSym}:
if node.eqIdent(what):
return by
return node
of nnkEmpty:
return node
of nnkLiterals:
return node
else:
var rTree = node.kind.newTree()
for child in node:
rTree.add inspect(child)
return rTree
result = inspect(ast)
macro staticFor*(idx: untyped{nkIdent}, start, stopEx: static int, body: untyped): untyped =
## staticFor [min inclusive, max exclusive)
result = newStmtList()
for i in start ..< stopEx:
result.add nnkBlockStmt.newTree(
ident("unrolledIter_" & $idx & $i),
body.replaceNodes(idx, newLit i)
)
2021-08-06 12:44:25 +00:00
# Copy
# --------------------------------------------------------
2023-06-12 14:07:15 +00:00
{.push raises: [], inline, noinit, gcsafe.}
func copyWords*(
a: var openArray[Word], startA: int,
b: openArray[Word], startB: int,
numWords: int) =
## Copy a slice of B into A. This properly deals
## with overlaps when A and B are slices of the same buffer
for i in countdown(numWords-1, 0):
a[startA+i] = b[startB+i]
{.pop.}