From fa90586f67538fc244b7e6adf93a1316aeb2265d Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Fri, 13 Nov 2015 13:44:09 +0530 Subject: [PATCH] Function to encode JS string as UTF-8 Uint8Arrays --- src/pyj/utils.pyj | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/pyj/utils.pyj b/src/pyj/utils.pyj index b31517f145..2261c83f04 100644 --- a/src/pyj/utils.pyj +++ b/src/pyj/utils.pyj @@ -20,3 +20,16 @@ def debounce(func, wait, immediate=False): timeout = window.setTimeout(later, wait) if call_now: func.apply(context, args) + +def to_utf8(string): + if type(TextEncoder) == 'function': + return TextEncoder('utf-8').encode(string) + escstr = encodeURIComponent(string) + binstr = escstr.replace(/%([0-9A-F]{2})/g, def(match, p1): + return String.fromCharCode('0x' + p1) + ) + ua = Uint8Array(binstr.length) + Array.prototype.forEach.call(binstr, def(ch, i): + ua[i] = ch.charCodeAt(0) + ) + return ua