From f7bf1a40ec38ce079612c5ee639e1482131fff34 Mon Sep 17 00:00:00 2001 From: Kang Seonghoon Date: Sun, 22 Aug 2021 21:08:11 +0900 Subject: [PATCH] Make Packed.estimateLength more accurate. also fix tools/compare-size.js that was broken for quite a while. --- index.js | 8 +++++++- tools/compare-size.js | 2 +- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 465f761..ece0cfa 100644 --- a/index.js +++ b/index.js @@ -1093,7 +1093,13 @@ class Packed { } estimateLength() { - return this.firstLineLengthInBytes + estimateDeflatedSize(this.secondLine); + // the first line is mostly 6-bit code, but there are additional characters + // so one of the 6-bit code literal has to be encoded in 7 bits. + // if the original data is N bytes the first line will contain about 4/3 N codes, + // 1/64 of which will have to use one additional bit. + // therefore the estimated overhead is 4/3 N * 1/64 [bits] = N/384 [bytes]. + // the additional 35 bytes are experimentally derived from the Huffman tree coding. + return 35 + Math.ceil(this.firstLineLengthInBytes * (1 + 1/384)) + estimateDeflatedSize(this.secondLine); } } diff --git a/tools/compare-size.js b/tools/compare-size.js index c341f02..f55cf7e 100644 --- a/tools/compare-size.js +++ b/tools/compare-size.js @@ -36,7 +36,7 @@ function twoPartDeflate(buf1, buf2, options) { } function analyze(buf) { - console.log([...analyzeDeflate(1, buf)].map(i => i[0] / 8)); + console.log([...analyzeDeflate('zlib', buf)].map(i => [i[0] / 8, i.slice(1).reduce((x,[y]) => x + y, 0) / 8])); return buf.length; }