Simplify lz4 instance management

This commit is contained in:
Raymond Hill 2023-04-25 22:14:15 -04:00
parent 1ffdb7d948
commit ef825245b9
No known key found for this signature in database
GPG Key ID: 25E1490B761470C2
1 changed files with 11 additions and 23 deletions

View File

@ -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;
},