diff --git a/stew/byteutils.nim b/stew/byteutils.nim index d51c66c..91b08a9 100644 --- a/stew/byteutils.nim +++ b/stew/byteutils.nim @@ -145,12 +145,22 @@ 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 - @(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 = if v.len > 0: 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 = ## Lexicographical compare of two byte arrays diff --git a/tests/test_byteutils.nim b/tests/test_byteutils.nim index c304a34..c27b729 100644 --- a/tests/test_byteutils.nim +++ b/tests/test_byteutils.nim @@ -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]