Skip to content

Commit

Permalink
bdb-key: add multi-byte strings/buffers as keys.
Browse files Browse the repository at this point in the history
  • Loading branch information
nodech committed Jun 13, 2024
1 parent 8d96c56 commit 3b10d18
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
13 changes: 13 additions & 0 deletions lib/db.js
Original file line number Diff line number Diff line change
Expand Up @@ -852,6 +852,7 @@ class Batch {

/**
* Get bucket.
* @param {Buffer} prefix
* @returns {Batch}
*/

Expand Down Expand Up @@ -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;
Expand All @@ -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.');

Expand Down
5 changes: 2 additions & 3 deletions lib/key.js
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
15 changes: 15 additions & 0 deletions test/key-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -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 = [{
Expand Down Expand Up @@ -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);
Expand Down

0 comments on commit 3b10d18

Please sign in to comment.