Merge pull request #16 from status-im/comparebyte

byteutils: lexicographical less than
This commit is contained in:
Jacek Sieka 2019-12-20 12:48:10 +01:00 committed by GitHub
commit d8c2a64055
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 0 deletions

View File

@ -129,3 +129,12 @@ func toBytes*(s: string): seq[byte] =
## nim essentially are byte sequences without any particular encoding, this
## is almost a noop
cast[seq[byte]](s)
func `<`*(a, b: openArray[byte]): bool =
## Lexicographical compare of two byte arrays
let minlen = min(a.len, b.len)
for i in 0..<minlen:
if a[i] != b[i]: return a[i] < b[i]
a.len < b.len

View File

@ -59,3 +59,25 @@ suite "Byte utils":
block:
expect AssertionError:
let a = hexToPaddedByteArray[2]("0x12345")
test "lessThan":
let
a = [0'u8, 1, 2]
b = [2'u8, 1, 0]
c = [0'u8, 1, 2, 3]
d = [0'u8, 1, 3, 3]
check:
not (a < a)
a < b
not (b < a)
c < b
not (b < c)
a < c
not (c < a)
c < d
not (d < c)