mirror of
https://github.com/status-im/nim-stew.git
synced 2025-01-09 11:45:42 +00:00
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] =
|
func toBytes*(s: string): seq[byte] =
|
||||||
## Convert a string to the corresponding byte sequence - since strings in
|
## Convert a string to the corresponding byte sequence - since strings in
|
||||||
## nim essentially are byte sequences without any particular encoding, this
|
## nim essentially are byte sequences without any particular encoding, this
|
||||||
## is almost a noop
|
## simply copies the bytes without a null terminator
|
||||||
cast[seq[byte]](s)
|
@(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 =
|
func `<`*(a, b: openArray[byte]): bool =
|
||||||
## Lexicographical compare of two byte arrays
|
## Lexicographical compare of two byte arrays
|
||||||
|
@ -81,3 +81,9 @@ suite "Byte utils":
|
|||||||
|
|
||||||
c < d
|
c < d
|
||||||
not (d < c)
|
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…
x
Reference in New Issue
Block a user