non-cast implementation of toBytes, add fromBytes

This commit is contained in:
Jacek Sieka 2020-03-04 23:09:42 +01:00 committed by zah
parent 50562b515a
commit 598fe151f8
2 changed files with 12 additions and 2 deletions

View File

@ -127,8 +127,12 @@ func toHex*[N: static[int]](ba: array[N, byte]): string {.inline.} =
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
## is almost a noop
cast[seq[byte]](s)
## simply copies the bytes without a null terminator
@(s.toOpenArrayByte(0, s.high))
func fromBytes*(T: type string, v: openArray[byte]): string =
result = newString(v.len)
copyMem(addr result[0], unsafeAddr v[0], v.len)
func `<`*(a, b: openArray[byte]): bool =
## Lexicographical compare of two byte arrays

View File

@ -81,3 +81,9 @@ suite "Byte utils":
c < d
not (d < c)
test "strings":
check:
"a".toBytes() == @[byte(ord('a'))]
string.fromBytes([byte(ord('a'))]) == "a"
cast[ptr UncheckedArray[byte]](cstring(string.fromBytes([byte(ord('a'))])))[1] == byte(0)