From ef825245b979d7c225ed2baacc0569b986e8abfd Mon Sep 17 00:00:00 2001 From: Raymond Hill Date: Tue, 25 Apr 2023 22:14:15 -0400 Subject: [PATCH] Simplify lz4 instance management --- src/js/lz4.js | 34 +++++++++++----------------------- 1 file changed, 11 insertions(+), 23 deletions(-) diff --git a/src/js/lz4.js b/src/js/lz4.js index 3c5bf3800..163ad5186 100644 --- a/src/js/lz4.js +++ b/src/js/lz4.js @@ -38,32 +38,21 @@ import µb from './background.js'; /******************************************************************************/ -let lz4CodecInstance; -let pendingInitialization; +let promisedInstance; let textEncoder, textDecoder; let ttlCount = 0; let ttlDelay = 60000; const init = function() { ttlDelay = µb.hiddenSettings.autoUpdateAssetFetchPeriod * 1000 + 15000; - if ( lz4CodecInstance === null ) { - return Promise.resolve(null); - } - if ( lz4CodecInstance !== undefined ) { - return Promise.resolve(lz4CodecInstance); - } - if ( pendingInitialization === undefined ) { + if ( promisedInstance === undefined ) { let flavor; if ( µb.hiddenSettings.disableWebAssembly === true ) { flavor = 'js'; } - pendingInitialization = lz4BlockCodec.createInstance(flavor) - .then(instance => { - lz4CodecInstance = instance; - pendingInitialization = undefined; - }); + promisedInstance = lz4BlockCodec.createInstance(flavor); } - return pendingInitialization; + return promisedInstance; }; // We can't shrink memory usage of lz4 codec instances, and in the @@ -80,7 +69,7 @@ const destroy = function() { // lz4CodecInstance.bytesInUse() >>> 10 // ); //} - lz4CodecInstance = undefined; + promisedInstance = undefined; textEncoder = textDecoder = undefined; ttlCount = 0; }; @@ -91,11 +80,10 @@ const ttlManage = function(count) { ttlTimer.off(); ttlCount += count; if ( ttlCount > 0 ) { return; } - if ( lz4CodecInstance === undefined ) { return; } ttlTimer.on(ttlDelay); }; -const encodeValue = function(dataIn) { +const encodeValue = function(lz4CodecInstance, dataIn) { if ( !lz4CodecInstance ) { return; } //let t0 = window.performance.now(); if ( textEncoder === undefined ) { @@ -123,7 +111,7 @@ const encodeValue = function(dataIn) { return outputArray; }; -const decodeValue = function(inputArray) { +const decodeValue = function(lz4CodecInstance, inputArray) { if ( !lz4CodecInstance ) { return; } //let t0 = window.performance.now(); if ( @@ -163,8 +151,8 @@ const lz4Codec = { return dataIn; } ttlManage(1); - await init(); - let dataOut = encodeValue(dataIn); + const lz4CodecInstance = await init(); + let dataOut = encodeValue(lz4CodecInstance, dataIn); ttlManage(-1); if ( serialize instanceof Function ) { dataOut = await serialize(dataOut); @@ -184,8 +172,8 @@ const lz4Codec = { return dataIn; } ttlManage(1); - await init(); - const dataOut = decodeValue(dataIn); + const lz4CodecInstance = await init(); + const dataOut = decodeValue(lz4CodecInstance, dataIn); ttlManage(-1); return dataOut || dataIn; },