Merge pull request #12002 from Snuffleupagus/cff-encodeNumber

Small improvements in `CFFCompiler.encodeNumber` and `CFFCompiler.encodeFloat`
This commit is contained in:
Tim van der Meij 2020-06-15 23:49:14 +02:00 committed by GitHub
commit 6bb64da1c3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1366,6 +1366,8 @@ var CFFOffsetTracker = (function CFFOffsetTrackerClosure() {
// Takes a CFF and converts it to the binary representation. // Takes a CFF and converts it to the binary representation.
var CFFCompiler = (function CFFCompilerClosure() { var CFFCompiler = (function CFFCompilerClosure() {
let EncodeFloatRegExp = null; // Lazily initialized by `encodeFloat`.
// eslint-disable-next-line no-shadow // eslint-disable-next-line no-shadow
function CFFCompiler(cff) { function CFFCompiler(cff) {
this.cff = cff; this.cff = cff;
@ -1483,8 +1485,7 @@ var CFFCompiler = (function CFFCompilerClosure() {
return output.data; return output.data;
}, },
encodeNumber: function CFFCompiler_encodeNumber(value) { encodeNumber: function CFFCompiler_encodeNumber(value) {
if (parseFloat(value) === parseInt(value, 10) && !isNaN(value)) { if (Number.isInteger(value)) {
// isInt
return this.encodeInteger(value); return this.encodeInteger(value);
} }
return this.encodeFloat(value); return this.encodeFloat(value);
@ -1492,8 +1493,11 @@ var CFFCompiler = (function CFFCompilerClosure() {
encodeFloat: function CFFCompiler_encodeFloat(num) { encodeFloat: function CFFCompiler_encodeFloat(num) {
var value = num.toString(); var value = num.toString();
// rounding inaccurate doubles if (!EncodeFloatRegExp) {
var m = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/.exec(value); EncodeFloatRegExp = /\.(\d*?)(?:9{5,20}|0{5,20})\d{0,2}(?:e(.+)|$)/;
}
// Rounding inaccurate doubles.
var m = EncodeFloatRegExp.exec(value);
if (m) { if (m) {
var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length)); var epsilon = parseFloat("1e" + ((m[2] ? +m[2] : 0) + m[1].length));
value = (Math.round(num * epsilon) / epsilon).toString(); value = (Math.round(num * epsilon) / epsilon).toString();