implement compile time helpers

This commit is contained in:
andri lim 2019-10-09 08:51:53 +07:00 committed by zah
parent 0b06077c55
commit affbe30b41
3 changed files with 17 additions and 15 deletions

View File

@ -10,7 +10,7 @@
import
./private/datatypes,
./private/int_negabs,
./private/[int_bitwise_ops, uint_bitwise_ops],
./private/compiletime_helpers,
./intops,
typetraits, algorithm
@ -285,13 +285,11 @@ proc dumpHex*(x: Stint or StUint, order: static[Endianness] = bigEndian): string
result = newString(2*size)
when nimvm:
type DT = type x.data.leastSignificantWord
for i in 0 ..< size:
when order == system.cpuEndian:
let pos = (i * 8)
let byte = x.data.getByte(i)
else:
let pos = ((size - (i + 1)) * 8)
let byte = (x.data shr pos).leastSignificantWord and 0xFF.DT
let byte = x.data.getByte(size - 1 - i)
result[2*i] = hexChars[int byte shr 4 and 0xF]
result[2*i+1] = hexChars[int byte and 0xF]
else:

View File

@ -0,0 +1,9 @@
import ./datatypes, ./uint_bitwise_ops
func getByte*(x: SomeInteger, pos: int): byte {.compileTime.} =
type DT = type x
byte((x shr (pos * 8)) and 0xFF.DT)
func getByte*(x: UintImpl | IntImpl, pos: int): byte {.compileTime.} =
type DT = type x.leastSignificantWord
byte((x shr (pos * 8)).leastSignificantWord and 0xFF.DT)

View File

@ -1,5 +1,4 @@
import ./bitops2_priv, ./datatypes, ./uint_bitwise_ops
import ./bitops2_priv, ./datatypes, ./compiletime_helpers
import stew/endians2
export endians2
@ -9,25 +8,21 @@ func swapBytes*(x: UintImpl): UintImpl {.inline.} =
UintImpl(hi: hi, lo: lo)
func copyMem(x: UintImpl): auto {.compileTime.} =
func copyMem(x: UintImpl, ret: var openArray[byte]) {.compileTime.} =
const size = bitsof(x) div 8
var ret: array[size, byte]
type DT = type x.leastSignificantWord
for i in 0 ..< size:
let pos = i * 8
ret[i] = byte((x shr pos).leastSignificantWord and 0xFF.DT)
ret
ret[i] = x.getByte(i)
func toBytes*(x: UintImpl, endian: Endianness = system.cpuEndian): auto {.inline.} =
# TODO can't use bitsof in return type (compiler bug?), hence return auto
var ret: array[bitsof(x) div 8, byte]
when nimvm:
if endian == system.cpuEndian:
ret = copyMem(x)
copyMem(x, ret)
else:
let v = swapBytes(x)
ret = copyMem(v)
copyMem(v, ret)
else:
if endian == system.cpuEndian:
copyMem(addr ret[0], unsafeAddr x, ret.len)