byteutils: compile-time to/fromBytes (#35)
This commit is contained in:
parent
8065e36c5a
commit
720f1a254d
|
@ -145,12 +145,22 @@ 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
|
||||||
## simply copies the bytes without a null terminator
|
## 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 =
|
func fromBytes*(T: type string, v: openArray[byte]): string =
|
||||||
if v.len > 0:
|
if v.len > 0:
|
||||||
result = newString(v.len)
|
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 =
|
func `<`*(a, b: openArray[byte]): bool =
|
||||||
## Lexicographical compare of two byte arrays
|
## Lexicographical compare of two byte arrays
|
||||||
|
|
|
@ -99,7 +99,8 @@ suite "Byte utils":
|
||||||
|
|
||||||
"".toBytes().len() == 0
|
"".toBytes().len() == 0
|
||||||
string.fromBytes([]) == ""
|
string.fromBytes([]) == ""
|
||||||
|
@[byte(ord('a'))] == static("a".toBytes())
|
||||||
|
"a" == static(string.fromBytes([byte(ord('a'))]))
|
||||||
test "slices":
|
test "slices":
|
||||||
var a: array[4, byte]
|
var a: array[4, byte]
|
||||||
a[0..<2] = [2'u8, 3]
|
a[0..<2] = [2'u8, 3]
|
||||||
|
|
Loading…
Reference in New Issue