git ssb

0+

wanderer🌟 / js-dfinity-radix-tree



Tree: c6deeb3aa229f07ddeaf41206fc74a0f9c97f5f0

Files: c6deeb3aa229f07ddeaf41206fc74a0f9c97f5f0 / treeNode.js

2259 bytesRaw
1const cbor = require('borc')
2const EMPTY_STATE_ROOT = Buffer.from('4cf812be9be2c6008325050f43d06676a08612c7', 'hex')
3
4const LINK_TAG = 42
5
6function insertTags (val) {
7 if (Array.isArray(val)) {
8 val = val.map(v => {
9 if (v && v.hasOwnProperty('/')) {
10 return new cbor.Tagged(LINK_TAG, v['/'])
11 } else {
12 return insertTags(v)
13 }
14 })
15 }
16 return val
17}
18
19// helper functions for nodes
20const EXTENSION = exports.EXTENSION = 0
21const LBRANCH = exports.LBRANCH = 1
22const RBRANCH = exports.RBRANCH = 2
23const VALUE = exports.VALUE = 3
24
25exports.setBranch = function (node, branch) {
26 node['/'][LBRANCH] = branch[0]
27 node['/'][RBRANCH] = branch[1]
28}
29
30exports.getBranch = function (node) {
31 return node['/'].slice(LBRANCH, LBRANCH + 2)
32}
33
34exports.getValue = function (node) {
35 return node['/'][VALUE]
36}
37
38exports.deleteValue = function (node) {
39 node['/'] = node['/'].slice(0, 3)
40}
41
42exports.getExtension = function (node) {
43 if (node['/'][EXTENSION]) {
44 const len = node['/'][EXTENSION][0]
45 const extension = exports.buffer2bits(node['/'][EXTENSION][1])
46 return extension.slice(0, len)
47 } else {
48 return []
49 }
50}
51
52exports.setExtension = function (node, ex) {
53 if (ex && ex.length) {
54 node['/'][EXTENSION] = [ex.length, exports.bit2buffer(ex)]
55 } else {
56 node['/'][EXTENSION] = null
57 }
58}
59
60exports.setValue = function (node, val) {
61 if (val !== undefined) {
62 node['/'][VALUE] = val
63 }
64}
65
66exports.isEmpty = function (node) {
67 if (Buffer.isBuffer(node['/'])) {
68 return !Buffer.compare(node['/'], EMPTY_STATE_ROOT)
69 } else {
70 return node['/'].every(el => !el)
71 }
72}
73
74exports.encodeNode = function (node) {
75 const val = insertTags(node)
76 const encoded = cbor.encode(val)
77 return encoded
78}
79
80exports.buffer2bits = function (buffer) {
81 const bitArray = []
82 for (const elem of buffer) {
83 for (let i = 7; i >= 0; i--) {
84 bitArray.push((elem & (1 << i)) >> i)
85 }
86 }
87 return bitArray
88}
89
90exports.bit2buffer = function (bits) {
91 bits = bits.slice(0)
92 const byteArray = []
93 for (const index in bits) {
94 const bit = bits[index]
95 const arrayIndex = Math.floor(index / 8)
96 byteArray[arrayIndex] = byteArray[arrayIndex] | bit << (7 - (index % 8))
97 }
98 return Buffer.from(byteArray)
99}
100

Built with git-ssb-web