From 3b10d18b61bf56e01834d2da5ae731c6b00f6034 Mon Sep 17 00:00:00 2001 From: Nodari Chkuaselidze Date: Thu, 13 Jun 2024 19:53:47 +0400 Subject: [PATCH] bdb-key: add multi-byte strings/buffers as keys. --- lib/db.js | 13 +++++++++++++ lib/key.js | 5 ++--- test/key-test.js | 15 +++++++++++++++ 3 files changed, 30 insertions(+), 3 deletions(-) diff --git a/lib/db.js b/lib/db.js index 2ff2450..3bd40ed 100644 --- a/lib/db.js +++ b/lib/db.js @@ -852,6 +852,7 @@ class Batch { /** * Get bucket. + * @param {Buffer} prefix * @returns {Batch} */ @@ -1907,6 +1908,12 @@ function wrap(resolve, reject) { }; } +/** + * @param {Buffer|null} prefix + * @param {Buffer|null} key + * @returns {Buffer?} + */ + function slice(prefix, key) { if (key == null) return key; @@ -1925,6 +1932,12 @@ function slice(prefix, key) { return key.slice(prefix.length); } +/** + * @param {Buffer} prefix + * @param {Buffer} key + * @returns {Buffer} + */ + function concat(prefix, key) { assert(Buffer.isBuffer(key), 'Key must be a buffer.'); diff --git a/lib/key.js b/lib/key.js index eb4b659..66eb14b 100644 --- a/lib/key.js +++ b/lib/key.js @@ -575,11 +575,10 @@ class Key { */ function makeID(id) { - if (typeof id === 'string') { - assert(id.length === 1); + if (typeof id === 'string') id = Buffer.from(id, 'ascii'); - } + // Number is not supported for multi-byte ids. if (typeof id === 'number') { assert((id & 0xff) === id); assert(id !== 0xff); diff --git a/test/key-test.js b/test/key-test.js index ca14cf9..3605484 100644 --- a/test/key-test.js +++ b/test/key-test.js @@ -21,6 +21,16 @@ const KEY_IDS = [{ num: 0x7a, // 'z' buf: Buffer.from('z', 'ascii'), expected: Buffer.from('z', 'ascii') +}, { + str: 'aa', + num: null, // does not support. + buf: Buffer.from('aa', 'ascii'), + expected: Buffer.from('aa', 'ascii') +}, { + str: 'abcd', + num: null, // does not support. + buf: Buffer.from('abcd', 'ascii'), + expected: Buffer.from('abcd', 'ascii') }]; const KEY_OPS = [{ @@ -69,6 +79,11 @@ describe('Key', function() { }); it(`should create key for ${KEY_ID.str} (num)`, () => { + if (KEY_ID.num == null) { + this.skip(); + return; + } + const key = bdb.key(KEY_ID.num); assert.bufferEqual(key.encode(), KEY_ID.expected);