non-cast implementation of toBytes, add fromBytes
This commit is contained in:
parent
50562b515a
commit
598fe151f8
|
@ -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
|
||||
|
|
|
@ -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)
|
||||
|
|
Loading…
Reference in New Issue