Skip to content

Commit c67fada

Browse files
committed
support for UTF-8 surrogate pairs (fixes #319)
1 parent f7142cd commit c67fada

File tree

2 files changed

+31
-3
lines changed

2 files changed

+31
-3
lines changed

compiler/prelude/jsmapping.go

Lines changed: 20 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,7 +84,14 @@ var $externalize = function(v, t) {
8484
var s = "", r;
8585
for (var i = 0; i < v.length; i += r[1]) {
8686
r = $decodeRune(v, i);
87-
s += String.fromCharCode(r[0]);
87+
var c = r[0];
88+
if (c > 0xFFFF) {
89+
var h = Math.floor((c - 0x10000) / 0x400) + 0xD800;
90+
var l = (c - 0x10000) % 0x400 + 0xDC00;
91+
s += String.fromCharCode(h, l);
92+
continue;
93+
}
94+
s += String.fromCharCode(c);
8895
}
8996
return s;
9097
case $kindStruct:
@@ -316,8 +323,18 @@ var $internalize = function(v, t, recv) {
316323
return v;
317324
}
318325
var s = "";
319-
for (var i = 0; i < v.length; i++) {
320-
s += $encodeRune(v.charCodeAt(i));
326+
var i = 0;
327+
while (i < v.length) {
328+
var h = v.charCodeAt(i);
329+
if (0xD800 <= h && h <= 0xDBFF) {
330+
var l = v.charCodeAt(i + 1);
331+
var c = (h - 0xD800) * 0x400 + l - 0xDC00 + 0x10000;
332+
s += $encodeRune(c);
333+
i += 2;
334+
continue;
335+
}
336+
s += $encodeRune(h);
337+
i++;
321338
}
322339
return s;
323340
case $kindStruct:

js/js_test.go

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -528,3 +528,14 @@ func TestDereference(t *testing.T) {
528528
t.Fail()
529529
}
530530
}
531+
532+
func TestSurrogatePairs(t *testing.T) {
533+
js.Global.Set("str", "\U0001F600")
534+
str := js.Global.Get("str")
535+
if str.Get("length").Int() != 2 || str.Call("charCodeAt", 0).Int() != 55357 || str.Call("charCodeAt", 1).Int() != 56832 {
536+
t.Fail()
537+
}
538+
if str.String() != "\U0001F600" {
539+
t.Fail()
540+
}
541+
}

0 commit comments

Comments
 (0)