Skip to content

Commit 43b2dd7

Browse files
committed
fix: isWellFormed
1 parent 3389996 commit 43b2dd7

File tree

2 files changed

+20
-1
lines changed

2 files changed

+20
-1
lines changed

lib/serializer.js

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
'use strict'
22

3+
// eslint-disable-next-line
4+
const ASCII_ESCAPE = /[\u0000-\u001f\u0022\u005c]/
5+
36
module.exports = class Serializer {
47
constructor (options) {
58
switch (options && options.rounding) {
@@ -89,6 +92,7 @@ module.exports = class Serializer {
8992

9093
asString (str) {
9194
const len = str.length
95+
9296
if (len === 0) {
9397
return '""'
9498
} else if (len < 42) {
@@ -116,7 +120,7 @@ module.exports = class Serializer {
116120
}
117121
}
118122
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
119-
} else if (len < 5000 && str.isWellFormed()) {
123+
} else if (len < 5000 && str.isWellFormed() && ASCII_ESCAPE.test(str) === false) {
120124
// Only use the regular expression for shorter input. The overhead is otherwise too much.
121125
return '"' + str + '"'
122126
} 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)