nim-stint/src/private/uint_comparison.nim

52 lines
1.6 KiB
Nim
Raw Normal View History

2018-03-02 10:48:08 +00:00
# Mpint
# 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.
2018-03-26 15:39:34 +00:00
import ./uint_type, ./size_mpuintimpl, macros
macro cast_optim(x: typed): untyped =
2018-03-26 15:39:34 +00:00
let size = size_mpuintimpl(x)
2018-03-26 14:47:04 +00:00
if size > 64:
result = quote do:
cast[array[`size` div 64, uint64]](`x`)
elif size == 64:
result = quote do:
cast[uint64](`x`)
elif size == 32:
result = quote do:
2018-03-26 14:47:04 +00:00
cast[uint32](`x`)
elif size == 16:
result = quote do:
2018-03-26 14:47:04 +00:00
cast[uint16](`x`)
elif size == 8:
result = quote do:
2018-03-26 14:47:04 +00:00
cast[uint8](`x`)
else:
error "Unreachable path reached"
2018-02-17 16:57:26 +00:00
proc isZero*(n: SomeUnsignedInt): bool {.noSideEffect,inline.} =
n == 0
2018-02-17 16:57:26 +00:00
proc isZero*(n: MpUintImpl): bool {.noSideEffect,inline.} =
2018-03-26 14:09:31 +00:00
n == (type n)()
proc `<`*(x, y: MpUintImpl): bool {.noSideEffect, noInit, inline.}=
(x.hi < y.hi) or ((x.hi == y.hi) and x.lo < y.lo)
proc `==`*(x, y: MpuintImpl): bool {.noSideEffect, noInit, inline.}=
# Equal comparison for multi-precision integers
2018-03-26 14:09:31 +00:00
# We cast to array of uint64 because the default comparison is slow
result = cast_optim(x) == cast_optim(y)
proc `<=`*(x, y: MpUintImpl): bool {.noSideEffect, noInit, inline.}=
# Lower or equal comparison for multi-precision integers
result = if x == y: true
else: x < y