byteutils: lexicographical less than

This commit is contained in:
Jacek Sieka 2019-12-19 13:29:38 +01:00
parent e9d75c05f6
commit 9c18a1cc55
No known key found for this signature in database
GPG Key ID: A1B09461ABB656B8
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)