diff --git a/lib/serializer.js b/lib/serializer.js index d92a4e32..31319ea4 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -1,5 +1,7 @@ 'use strict' +const findEscapeSequence = /["\b\t\n\v\f\r\/]/ + module.exports = class Serializer { constructor (options) { switch (options && options.rounding) { @@ -88,37 +90,10 @@ module.exports = class Serializer { } asString (str) { - const len = str.length - if (len < 42) { - // magically escape strings for json - // relying on their charCodeAt - // everything below 32 needs JSON.stringify() - // every string that contain surrogate needs JSON.stringify() - // 34 and 92 happens all the time, so we - // have a fast case for them - let result = '' - let last = -1 - let point = 255 - for (let i = 0; i < len; i++) { - point = str.charCodeAt(i) - if ( - point === 0x22 || // '"' - point === 0x5c // '\' - ) { - last === -1 && (last = 0) - result += str.slice(last, i) + '\\' - last = i - } 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()) { - // Only use the regular expression for shorter input. The overhead is otherwise too much. - return '"' + str + '"' - } else { + if (findEscapeSequence.test(str)) { return JSON.stringify(str) + } else { + return '"' + str + '"' } }