Skip to content

Commit 75f24ea

Browse files
authored
Merge branch 'is-well-formed' into master
Signed-off-by: Nigro Simone <[email protected]>
2 parents cc14cc8 + 2403bdd commit 75f24ea

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

benchmark/bench.js

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,13 @@ for (let i = 0; i < SHORT_ARRAY_SIZE; i++) {
4040
}
4141

4242
const benchmarks = [
43+
{
44+
name: 'empty string',
45+
schema: {
46+
type: 'string'
47+
},
48+
input: ''
49+
},
4350
{
4451
name: 'short string',
4552
schema: {

lib/serializer.js

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
'use strict'
22

33
// eslint-disable-next-line
4-
const STR_ESCAPE = /[\u0000-\u001f\u0022\u005c\ud800-\udfff]/
4+
const ASCII_ESCAPE = /[\u0000-\u001f\u0022\u005c]/
55

66
module.exports = class Serializer {
77
constructor (options) {
@@ -92,6 +92,7 @@ module.exports = class Serializer {
9292

9393
asString (str) {
9494
const len = str.length
95+
9596
if (len === 0) {
9697
return '""'
9798
} else if (len < 42) {
@@ -113,13 +114,13 @@ module.exports = class Serializer {
113114
last === -1 && (last = 0)
114115
result += str.slice(last, i) + '\\'
115116
last = i
116-
} else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
117+
} else if (point < 32 || (point >= 0xd800 && point <= 0xdfff)) {
117118
// The current character is non-printable characters or a surrogate.
118119
return JSON.stringify(str)
119120
}
120121
}
121122
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
122-
} else if (len < 5000 && STR_ESCAPE.test(str) === false) {
123+
} else if (len < 5000 && str.isWellFormed() && ASCII_ESCAPE.test(str) === false) {
123124
// Only use the regular expression for shorter input. The overhead is otherwise too much.
124125
return '"' + str + '"'
125126
} else {

test/string.test.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,21 @@ test('serialize short string', (t) => {
3434
t.assert.equal(JSON.parse(output), input)
3535
})
3636

37+
test('serialize medium string', (t) => {
38+
t.plan(2)
39+
40+
const schema = {
41+
type: 'string'
42+
}
43+
44+
const input = new Array(150).fill('\x00').join('')
45+
const stringify = build(schema)
46+
const output = stringify(input)
47+
48+
t.assert.equal(output, `"${new Array(150).fill('\\u0000').join('')}"`)
49+
t.assert.equal(JSON.parse(output), input)
50+
})
51+
3752
test('serialize long string', (t) => {
3853
t.plan(2)
3954

0 commit comments

Comments
 (0)