fix fromBytes for zero length arrays

This commit is contained in:
Jacek Sieka 2020-03-07 23:29:46 +01:00
parent ca8fb7ebd0
commit 76beeb769e
No known key found for this signature in database
GPG Key ID: A1B09461ABB656B8
2 changed files with 6 additions and 2 deletions

View File

@ -145,8 +145,9 @@ func toBytes*(s: string): seq[byte] =
@(s.toOpenArrayByte(0, s.high)) @(s.toOpenArrayByte(0, s.high))
func fromBytes*(T: type string, v: openArray[byte]): string = func fromBytes*(T: type string, v: openArray[byte]): string =
result = newString(v.len) if v.len > 0:
copyMem(addr result[0], unsafeAddr v[0], v.len) 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

View File

@ -88,6 +88,9 @@ suite "Byte utils":
string.fromBytes([byte(ord('a'))]) == "a" string.fromBytes([byte(ord('a'))]) == "a"
cast[ptr UncheckedArray[byte]](cstring(string.fromBytes([byte(ord('a'))])))[1] == byte(0) cast[ptr UncheckedArray[byte]](cstring(string.fromBytes([byte(ord('a'))])))[1] == byte(0)
"".toBytes().len() == 0
string.fromBytes([]) == ""
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]