Skip to content

Commit fd43c2e

Browse files
authored
Merge pull request #33 from fiserro/master
Allow parse escaped surrogate pairs
2 parents 69f02ca + e6a8f0e commit fd43c2e

2 files changed

Lines changed: 40 additions & 1 deletion

File tree

jsonparse.js

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,7 @@ function Parser() {
5959
this.stringBuffer = Buffer.alloc ? Buffer.alloc(STRING_BUFFER_SIZE) : new Buffer(STRING_BUFFER_SIZE);
6060
this.stringBufferOffset = 0;
6161
this.unicode = undefined; // unicode escapes
62+
this.highSurrogate = undefined;
6263

6364
this.key = undefined;
6465
this.mode = undefined;
@@ -217,8 +218,20 @@ proto.write = function (buffer) {
217218
if ((n >= 0x30 && n < 0x40) || (n > 0x40 && n <= 0x46) || (n > 0x60 && n <= 0x66)) {
218219
this.unicode += String.fromCharCode(n);
219220
if (this.tState++ === STRING6) {
220-
this.appendStringBuf(Buffer(String.fromCharCode(parseInt(this.unicode, 16))));
221+
var intVal = parseInt(this.unicode, 16);
221222
this.unicode = undefined;
223+
if (this.highSurrogate !== undefined && intVal >= 0xDC00 && intVal < (0xDFFF + 1)) { //<56320,57343> - lowSurrogate
224+
this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate, intVal)));
225+
this.highSurrogate = undefined;
226+
} else if (this.highSurrogate === undefined && intVal >= 0xD800 && intVal < (0xDBFF + 1)) { //<55296,56319> - highSurrogate
227+
this.highSurrogate = intVal;
228+
} else {
229+
if (this.highSurrogate !== undefined) {
230+
this.appendStringBuf(new Buffer(String.fromCharCode(this.highSurrogate)));
231+
this.highSurrogate = undefined;
232+
}
233+
this.appendStringBuf(new Buffer(String.fromCharCode(intVal)));
234+
}
222235
this.tState = STRING1;
223236
}
224237
} else {

test/surrogate.js

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
var test = require('tape');
2+
var Parser = require('../');
3+
4+
test('parse surrogate pair', function (t) {
5+
t.plan(1);
6+
7+
var p = new Parser();
8+
p.onValue = function (value) {
9+
t.equal(value, '😋');
10+
};
11+
12+
p.write('"\\uD83D\\uDE0B"');
13+
});
14+
15+
test('parse chunked surrogate pair', function (t) {
16+
t.plan(1);
17+
18+
var p = new Parser();
19+
p.onValue = function (value) {
20+
t.equal(value, '😋');
21+
};
22+
23+
p.write('"\\uD83D');
24+
p.write('\\uDE0B"');
25+
});
26+

0 commit comments

Comments
 (0)