From 3ef01dbd081d28603438202501867a8f9806629a Mon Sep 17 00:00:00 2001 From: Alex Victoor Date: Tue, 21 Jul 2020 21:53:00 +0200 Subject: [PATCH] Synchronous WASM init --- README.md | 7 ++++++- src/Histogram.spec.ts | 4 ++-- src/index.ts | 3 ++- src/wasm/index.ts | 5 +++++ 4 files changed, 15 insertions(+), 4 deletions(-) diff --git a/README.md b/README.md index ea3a2f7..e967c5f 100644 --- a/README.md +++ b/README.md @@ -198,9 +198,14 @@ The code fragment below shows how to instantiate a resizable 32 bits WebAssembly ``` import * as hdr from "hdr-histogram-js" -// load HdrHistogramJS WASM module +// If you are on the browser side, you need to +// load asynchronously HdrHistogramJS WASM module await hdr.initWebAssembly(); +// If you are on the server side, you can +// load synchronously HdrHistogramJS WASM module +hdr.initWebAssemblySync(); + const histogram = hdr.build({ useWebAssembly: true }); // you can now use your histogram the same way you would do diff --git a/src/Histogram.spec.ts b/src/Histogram.spec.ts index 92cf9ab..00a89e1 100644 --- a/src/Histogram.spec.ts +++ b/src/Histogram.spec.ts @@ -2,7 +2,7 @@ import { build } from "."; import JsHistogram from "./JsHistogram"; import { NO_TAG } from "./Histogram"; import Int32Histogram from "./Int32Histogram"; -import { initWebAssembly, WasmHistogram } from "./wasm"; +import { initWebAssembly, WasmHistogram, initWebAssemblySync } from "./wasm"; import Int8Histogram from "./Int8Histogram"; import Histogram from "./Histogram"; @@ -309,7 +309,7 @@ describe("WASM Histogram not initialized", () => { }); describe("WASM Histogram not happy path", () => { - beforeEach(initWebAssembly); + beforeEach(initWebAssemblySync); it("should throw a clear error message when used after destroy", () => { const destroyedHistogram = build({ useWebAssembly: true }); destroyedHistogram.destroy(); diff --git a/src/index.ts b/src/index.ts index 1d958e3..ad40a6d 100644 --- a/src/index.ts +++ b/src/index.ts @@ -19,11 +19,12 @@ import Int8Histogram from "./Int8Histogram"; import JsHistogram from "./JsHistogram"; import PackedHistogram from "./PackedHistogram"; import Recorder from "./Recorder"; -import { initWebAssembly, WasmHistogram } from "./wasm"; +import { initWebAssembly, initWebAssemblySync, WasmHistogram } from "./wasm"; import { build } from "./HistogramBuilder"; export { initWebAssembly, + initWebAssemblySync, Int8Histogram, Int16Histogram, Int32Histogram, diff --git a/src/wasm/index.ts b/src/wasm/index.ts index ef66efd..2e4dc5a 100644 --- a/src/wasm/index.ts +++ b/src/wasm/index.ts @@ -43,6 +43,11 @@ export const initWebAssembly = async (): Promise => { .then((w: any) => (wasm = w.exports || w)); }; +export const initWebAssemblySync = () => { + const w = loader.instantiateSync(pako.inflate(base64.toByteArray(BINARY))); + wasm = w.exports || w; +}; + export const webAssemblyReady = () => !!wasm; const defaultRequest: BuildRequest = {