byteutils: compile-time to/fromBytes (#35)
This commit is contained in:
parent
8065e36c5a
commit
720f1a254d
|
@ -145,11 +145,21 @@ 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
|
||||
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)
|
||||
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 =
|
||||
|
|
|
@ -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]
|
||||
|
|
Loading…
Reference in New Issue