diff options
-rw-r--r-- | src/html/jsencoding.nim | 18 | ||||
-rw-r--r-- | test/js/encode_decode.html | 1 |
2 files changed, 10 insertions, 9 deletions
diff --git a/src/html/jsencoding.nim b/src/html/jsencoding.nim index 7aae5eb2..c552724f 100644 --- a/src/html/jsencoding.nim +++ b/src/html/jsencoding.nim @@ -74,19 +74,19 @@ func jencoding(this: JSTextEncoder): string {.jsfget: "encoding".} = return "utf-8" proc dealloc_wrap(rt: JSRuntime; opaque, p: pointer) {.cdecl.} = - dealloc(p) + if p != nil: + dealloc(p) proc encode(this: JSTextEncoder; input = ""): JSUint8Array {.jsfunc.} = # we have to validate input first :/ #TODO it is possible to do less copies here... - var input = input.toValidUTF8() - let buf = cast[ptr UncheckedArray[uint8]](alloc(input.len)) - copyMem(buf, addr input[0], input.len) - let abuf = JSArrayBuffer( - p: buf, - len: csize_t(input.len), - dealloc: dealloc_wrap - ) + let input = input.toValidUTF8() + let abuf = if input.len > 0: + let buf = cast[ptr UncheckedArray[uint8]](alloc(input.len)) + copyMem(buf, unsafeAddr input[0], input.len) + JSArrayBuffer(p: buf, len: csize_t(input.len), dealloc: dealloc_wrap) + else: + JSArrayBuffer(p: nil, len: 0, dealloc: dealloc_wrap) return JSUint8Array( abuf: abuf, offset: 0, diff --git a/test/js/encode_decode.html b/test/js/encode_decode.html index c2bcd509..e192c431 100644 --- a/test/js/encode_decode.html +++ b/test/js/encode_decode.html @@ -17,6 +17,7 @@ function bytesToBase64(bytes) { return btoa(binString); } +assertEquals(new TextEncoder().encode("").length, 0); const utf8 = new TextEncoder().encode("a Ā 𐀀 文 🦄") const b64utf8 = bytesToBase64(utf8); assertEquals(b64utf8, "YSDEgCDwkICAIOaWhyDwn6aE") |