Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions lib/serializer.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
'use strict'

// eslint-disable-next-line
const ASCII_ESCAPE = /[\u0000-\u001f\u0022\u005c]/

module.exports = class Serializer {
constructor (options) {
switch (options && options.rounding) {
Expand Down Expand Up @@ -89,9 +92,16 @@ module.exports = class Serializer {

asString (str) {
const len = str.length

if (len === 0) {
return '""'
} else if (len < 42) {
}

if (!str.isWellFormed()) {
return JSON.stringify(str)
}

if (len < 42) {
// magically escape strings for json
// relying on their charCodeAt
// everything below 32 needs JSON.stringify()
Expand All @@ -110,13 +120,13 @@ module.exports = class Serializer {
last === -1 && (last = 0)
result += str.slice(last, i) + '\\'
last = i
} else if (point < 32 || (point >= 0xD800 && point <= 0xDFFF)) {
} else if (point < 32) {
// The current character is non-printable characters or a surrogate.
return JSON.stringify(str)
}
}
return (last === -1 && ('"' + str + '"')) || ('"' + result + str.slice(last) + '"')
} else if (len < 5000 && str.isWellFormed()) {
} else if (len < 5000 && ASCII_ESCAPE.test(str) === false) {
// Only use the regular expression for shorter input. The overhead is otherwise too much.
return '"' + str + '"'
} else {
Expand Down
15 changes: 15 additions & 0 deletions test/string.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,21 @@ test('serialize short string', (t) => {
t.assert.equal(JSON.parse(output), input)
})

test('serialize medium string', (t) => {
t.plan(2)

const schema = {
type: 'string'
}

const input = new Array(150).fill('\x00').join('')
const stringify = build(schema)
const output = stringify(input)

t.assert.equal(output, `"${new Array(150).fill('\\u0000').join('')}"`)
t.assert.equal(JSON.parse(output), input)
})

test('serialize long string', (t) => {
t.plan(2)

Expand Down
Loading