diff --git a/javascript/lib.cpp b/javascript/lib.cpp index 3f576533..03307a1a 100644 --- a/javascript/lib.cpp +++ b/javascript/lib.cpp @@ -131,6 +131,8 @@ void CompiledIndex::Load(Napi::CallbackInfo const& ctx) { auto result = native_->load(path.c_str()); if (!result) Napi::TypeError::New(ctx.Env(), result.error.release()).ThrowAsJavaScriptException(); + if (!native_->try_reserve(ceil2(native_->size()))) + Napi::Error::New(ctx.Env(), "Failed to reserve memory").ThrowAsJavaScriptException(); } catch (...) { Napi::TypeError::New(ctx.Env(), "Loading failed").ThrowAsJavaScriptException(); @@ -144,6 +146,8 @@ void CompiledIndex::View(Napi::CallbackInfo const& ctx) { auto result = native_->view(path.c_str()); if (!result) Napi::TypeError::New(ctx.Env(), result.error.release()).ThrowAsJavaScriptException(); + if (!native_->try_reserve(ceil2(native_->size()))) + Napi::Error::New(ctx.Env(), "Failed to reserve memory").ThrowAsJavaScriptException(); } catch (...) { Napi::TypeError::New(ctx.Env(), "Memory-mapping failed").ThrowAsJavaScriptException(); diff --git a/javascript/usearch.test.js b/javascript/usearch.test.js index 80747763..952cd926 100644 --- a/javascript/usearch.test.js +++ b/javascript/usearch.test.js @@ -1,5 +1,8 @@ const test = require('node:test'); const assert = require('node:assert'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); const usearch = require('./dist/cjs/usearch.js'); function assertAlmostEqual(actual, expected, tolerance = 1e-6) { @@ -122,3 +125,50 @@ test('Invalid operations', async (t) => { ); }); }); + + +test('Serialization', async (t) => { + const indexPath = path.join(os.tmpdir(), 'usearch.test.index') + + t.beforeEach(() => { + const index = new usearch.Index({ + metric: "l2sq", + connectivity: 16, + dimensions: 3, + }); + index.add(42n, new Float32Array([0.2, 0.6, 0.4])); + index.save(indexPath); + }); + + t.afterEach(() => { + fs.unlinkSync(indexPath); + }); + + await t.test('load', () => { + const index = new usearch.Index({ + metric: "l2sq", + connectivity: 16, + dimensions: 3, + }); + index.load(indexPath); + const results = index.search(new Float32Array([0.2, 0.6, 0.4]), 10); + + assert.equal(index.size(), 1); + assert.deepEqual(results.keys, new BigUint64Array([42n])); + assertAlmostEqual(results.distances[0], new Float32Array([0])); + }); + + await t.test('view', () => { + const index = new usearch.Index({ + metric: "l2sq", + connectivity: 16, + dimensions: 3, + }); + index.view(indexPath); + const results = index.search(new Float32Array([0.2, 0.6, 0.4]), 10); + + assert.equal(index.size(), 1); + assert.deepEqual(results.keys, new BigUint64Array([42n])); + assertAlmostEqual(results.distances[0], new Float32Array([0])); + }); +});