Skip to content
Closed
Show file tree
Hide file tree
Changes from 4 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
7 changes: 7 additions & 0 deletions benchmark/bench.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,13 @@ for (let i = 0; i < SHORT_ARRAY_SIZE; i++) {
}

const benchmarks = [
{
name: 'empty string',
schema: {
type: 'string'
},
input: ''
},
{
name: 'short string',
schema: {
Expand Down
8 changes: 6 additions & 2 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,6 +92,7 @@ module.exports = class Serializer {

asString (str) {
const len = str.length

if (len === 0) {
return '""'
} else if (len < 42) {
Expand All @@ -110,13 +114,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 || (point >= 0xd800 && point <= 0xdfff)) {
// 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 && str.isWellFormed() && 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