UNPKG

2.32 kBJavaScriptView Raw
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3exports.doKeysMatch = exports.matchingNibbleLength = exports.nibblesCompare = exports.nibblesToBuffer = exports.bufferToNibbles = void 0;
4/**
5 * Converts a buffer to a nibble array.
6 * @private
7 * @param key
8 */
9function bufferToNibbles(key) {
10 const bkey = Buffer.from(key);
11 const nibbles = [];
12 for (let i = 0; i < bkey.length; i++) {
13 let q = i * 2;
14 nibbles[q] = bkey[i] >> 4;
15 ++q;
16 nibbles[q] = bkey[i] % 16;
17 }
18 return nibbles;
19}
20exports.bufferToNibbles = bufferToNibbles;
21/**
22 * Converts a nibble array into a buffer.
23 * @private
24 * @param arr - Nibble array
25 */
26function nibblesToBuffer(arr) {
27 const buf = Buffer.alloc(arr.length / 2);
28 for (let i = 0; i < buf.length; i++) {
29 let q = i * 2;
30 buf[i] = (arr[q] << 4) + arr[++q];
31 }
32 return buf;
33}
34exports.nibblesToBuffer = nibblesToBuffer;
35/**
36 * Compare two nibble array.
37 * * `0` is returned if `n2` == `n1`.
38 * * `1` is returned if `n2` > `n1`.
39 * * `-1` is returned if `n2` < `n1`.
40 * @param n1 - Nibble array
41 * @param n2 - Nibble array
42 */
43function nibblesCompare(n1, n2) {
44 const cmpLength = Math.min(n1.length, n2.length);
45 let res = 0;
46 for (let i = 0; i < cmpLength; i++) {
47 if (n1[i] < n2[i]) {
48 res = -1;
49 break;
50 }
51 else if (n1[i] > n2[i]) {
52 res = 1;
53 break;
54 }
55 }
56 if (res === 0) {
57 if (n1.length < n2.length) {
58 res = -1;
59 }
60 else if (n1.length > n2.length) {
61 res = 1;
62 }
63 }
64 return res;
65}
66exports.nibblesCompare = nibblesCompare;
67/**
68 * Returns the number of in order matching nibbles of two give nibble arrays.
69 * @private
70 * @param nib1
71 * @param nib2
72 */
73function matchingNibbleLength(nib1, nib2) {
74 let i = 0;
75 while (nib1[i] === nib2[i] && nib1.length > i) {
76 i++;
77 }
78 return i;
79}
80exports.matchingNibbleLength = matchingNibbleLength;
81/**
82 * Compare two nibble array keys.
83 * @param keyA
84 * @param keyB
85 */
86function doKeysMatch(keyA, keyB) {
87 const length = matchingNibbleLength(keyA, keyB);
88 return length === keyA.length && length === keyB.length;
89}
90exports.doKeysMatch = doKeysMatch;
91//# sourceMappingURL=nibbles.js.map
\No newline at end of file