byteutils: compile-time to/fromBytes (#35)

This commit is contained in:
Jacek Sieka 2020-05-06 15:51:07 +02:00 committed by GitHub
parent 8065e36c5a
commit 720f1a254d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 14 additions and 3 deletions

View File

@ -145,12 +145,22 @@ func toBytes*(s: string): seq[byte] =
## Convert a string to the corresponding byte sequence - since strings in
## nim essentially are byte sequences without any particular encoding, this
## simply copies the bytes without a null terminator
@(s.toOpenArrayByte(0, s.high))
when nimvm:
var r = newSeq[byte](s.len)
for i, c in s:
r[i] = cast[byte](c)
r
else:
@(s.toOpenArrayByte(0, s.high))
func fromBytes*(T: type string, v: openArray[byte]): string =
if v.len > 0:
result = newString(v.len)
copyMem(addr result[0], unsafeAddr v[0], v.len)
when nimvm:
for i, c in v:
result[i] = cast[char](c)
else:
copyMem(addr result[0], unsafeAddr v[0], v.len)
func `<`*(a, b: openArray[byte]): bool =
## Lexicographical compare of two byte arrays

View File

@ -99,7 +99,8 @@ suite "Byte utils":
"".toBytes().len() == 0
string.fromBytes([]) == ""
@[byte(ord('a'))] == static("a".toBytes())
"a" == static(string.fromBytes([byte(ord('a'))]))
test "slices":
var a: array[4, byte]
a[0..<2] = [2'u8, 3]