Skip to content

Commit 5c35971

Browse files
committed
Web.JSON: Convert UTF-16 surrogate pairs.
1 parent 92c274c commit 5c35971

File tree

2 files changed

+14
-3
lines changed

2 files changed

+14
-3
lines changed

autoload/vital/__vital__/Web/JSON.vim

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ function! s:_resolve(val, prefix) abort
6363
return a:val
6464
endfunction
6565

66-
6766
function! s:_vital_created(module) abort
6867
" define constant variables
6968
if !exists('s:const')
@@ -96,6 +95,10 @@ function! s:decode(json, ...) abort
9695
let json = join(split(json, "\n"), '')
9796
let json = substitute(json, '\\u34;', '\\"', 'g')
9897
let json = substitute(json, '\\u\(\x\x\x\x\)', '\=s:string.nr2enc_char("0x".submatch(1))', 'g')
98+
" convert surrogate pair
99+
let json = substitute(json, '\([\uD800-\uDBFF]\)\([\uDC00-\uDFFF]\)',
100+
\ '\=nr2char(0x10000+and(0x7ff,char2nr(submatch(1)))*0x400+and(0x3ff,char2nr(submatch(2))))',
101+
\ 'g')
99102
if settings.use_token
100103
let prefix = '__Web.JSON__'
101104
while stridx(json, prefix) != -1

test/Web/JSON.vimspec

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,12 @@ Describe Web.JSON
3434
Assert Equals(JSON.decode('"\b\t\n\u000b\f\r\u000e\u000f"'), "\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f")
3535
Assert Equals(JSON.decode('"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"'), "\x10\x11\x12\x13\x14\x15\x16\x17")
3636
Assert Equals(JSON.decode('"\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"'), "\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f")
37-
" there should be iconv tests as well
37+
" multibyte
38+
Assert Equals(JSON.decode('"s¢cĴgё"'), "s¢cĴgё")
39+
" UTF-16 surrogate pair
40+
Assert Equals(JSON.decode('"\ud83c\udf63"'), "\xf0\x9f\x8d\xa3")
41+
" unpaired UTF-16 surrogate
42+
Assert Equals(JSON.decode('"\ud83c\u00a0"'), "\ud83c\u00a0")
3843
End
3944

4045
It decodes lists
@@ -101,7 +106,10 @@ Describe Web.JSON
101106
Assert Equals(JSON.encode("\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f"), '"\b\t\n\u000b\f\r\u000e\u000f"')
102107
Assert Equals(JSON.encode("\x10\x11\x12\x13\x14\x15\x16\x17"), '"\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017"')
103108
Assert Equals(JSON.encode("\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f"), '"\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f"')
104-
" there should be iconv tests as well
109+
" multibyte
110+
Assert Equals(JSON.encode("s¢cĴgё"), '"s¢cĴgё"')
111+
" UTF-16 surrogate pair
112+
Assert Equals(JSON.encode("\xf0\x9f\x8d\xa3"), "\"\xf0\x9f\x8d\xa3\"")
105113
End
106114

107115
It encodes lists

0 commit comments

Comments
 (0)