From aa21f463fecd100247a58eb2612f572c49a30b17 Mon Sep 17 00:00:00 2001 From: Daniel Huigens Date: Fri, 29 Jun 2018 15:22:18 +0200 Subject: [PATCH] Heap & asm pooling --- src/aes/aes.js | 40 +++++++++++++++++++++++++++++++++++----- 1 file changed, 35 insertions(+), 5 deletions(-) diff --git a/src/aes/aes.js b/src/aes/aes.js index a52d90a..71474ba 100644 --- a/src/aes/aes.js +++ b/src/aes/aes.js @@ -2,18 +2,40 @@ import { AES_asm } from './aes.asm'; import { _heap_init, _heap_write, is_bytes, is_number } from '../utils'; import { IllegalArgumentError, SecurityError } from '../errors'; +const heap_pool = []; +const asm_pool = []; + export class AES { constructor(key, iv, padding, heap, asm) { this.nonce = null; this.counter = 0; this.counterSize = 0; - this.heap = _heap_init(Uint8Array, heap).subarray(AES_asm.HEAP_DATA); - this.asm = asm || AES_asm(null, this.heap.buffer); this.mode = null; - this.key = null; - this.AES_reset(key, iv, padding); + this.key = key; + this.iv = iv; + this.padding = padding; + + this.acquireResources(heap, asm); + } + + acquireResources(heap, asm) { + if (!this.heap && !this.asm) { + console.log(heap, heap_pool.slice(-1)); + this.heap = _heap_init(Uint8Array, heap || heap_pool.pop()).subarray(AES_asm.HEAP_DATA); + this.asm = asm || asm_pool.pop() || AES_asm(null, this.heap.buffer); + this.AES_reset(this.key, this.iv, this.padding); + } + } + + releaseResources() { + if (this.heap.buffer.byteLength !== 0x100000) { // shared asm.js heap + heap_pool.push(new Uint8Array(this.heap.buffer)); + asm_pool.push(this.asm); + this.heap = undefined; + this.asm = undefined; + } } /** @@ -114,7 +136,7 @@ export class AES { this.iv = iv; this.asm.set_iv(ivview.getUint32(0), ivview.getUint32(4), ivview.getUint32(8), ivview.getUint32(12)); } else { - this.iv = null; + this.iv = undefined; this.asm.set_iv(0, 0, 0, 0); } } @@ -198,6 +220,8 @@ export class AES { * @param {Uint8Array} data */ AES_Encrypt_finish(data) { + this.acquireResources(); + var presult = null, prlen = 0; @@ -239,6 +263,8 @@ export class AES { this.pos = 0; this.len = 0; + this.releaseResources(); + return this; } @@ -299,6 +325,8 @@ export class AES { * @param {Uint8Array} data */ AES_Decrypt_finish(data) { + this.acquireResources(); + var presult = null, prlen = 0; @@ -352,6 +380,8 @@ export class AES { this.pos = 0; this.len = 0; + this.releaseResources(); + return this; } }