Files: 9e2c40485053fde8aca886b9e92447c51112f077 / index.js
7361 bytesRaw
1 | const Graph = require('ipld-graph-builder') |
2 | const cbor = require('borc') |
3 | const Uint1Array = require('uint1array') |
4 | const TextEncoder = require('text-encoding').TextEncoder |
5 | const DataStore = require('./datastore.js') |
6 | const treeNode = require('./treeNode.js') |
7 | |
8 | const encoder = new TextEncoder('utf-8') |
9 | |
10 | module.exports = class RadixTree { |
11 | /** |
12 | * @param opts |
13 | * @param opts.root {object} a merkle root to a radix tree. If none, RadixTree will create an new root. |
14 | * @param opts.db {object} a level db instance alternitly `opts.graph` can be used |
15 | * @param opts.graph {object} an instance of [ipld-graph-builder](https://github.com/ipld/js-ipld-graph-builder) alternitvly `opts.dag` can be used |
16 | * @param opts.dag {object} an instance if [ipfs.dag](https://github.com/ipfs/js-ipfs#dag). If there is no `opts.graph` this will be used to create a new graph instance. |
17 | */ |
18 | constructor (opts) { |
19 | this.root = opts.root || { |
20 | '/': RadixTree.emptyTreeState |
21 | } |
22 | |
23 | this.dag = opts.dag || new DataStore(opts.db) |
24 | this.graph = opts.graph || new Graph(this.dag) |
25 | } |
26 | |
27 | /** |
28 | * returns the state of an empty tree |
29 | */ |
30 | static get emptyTreeState () { |
31 | return [null, null, null] |
32 | } |
33 | |
34 | /** |
35 | * returns an Uint1Array constructir which is used to repersent keys |
36 | * @returns {object} |
37 | */ |
38 | static get ArrayConstructor () { |
39 | return Uint1Array |
40 | } |
41 | |
42 | /** |
43 | * returns a merkle link for some given data |
44 | * @param {Buffer} data - the data which you would like to hash |
45 | * @returns {Buffer} |
46 | */ |
47 | static getMerkleLink (data) { |
48 | return DataStore.getMerkleLink(data) |
49 | } |
50 | |
51 | async _get (key) { |
52 | let index = 0 |
53 | let root = this.root |
54 | let parent |
55 | |
56 | while (1) { |
57 | // load the root |
58 | const exNode = await this.graph.get(root, treeNode.EXTENSION, true) |
59 | if (exNode) { |
60 | let subKey = key.subarray(index) |
61 | |
62 | const {extensionIndex, extensionLen, extension} = findMatchBits(subKey, root) |
63 | index += extensionIndex |
64 | // check if we compelete travered the extension |
65 | if (extensionIndex !== extensionLen) { |
66 | return { |
67 | index: index, |
68 | root: root, |
69 | extension: extension, |
70 | extensionIndex: extensionIndex |
71 | } |
72 | } |
73 | } |
74 | |
75 | let keySegment = key[index] |
76 | if (keySegment !== undefined) { |
77 | const branch = treeNode.getBranch(root) |
78 | await this.graph.get(branch, keySegment, true) |
79 | // preseves the '/' |
80 | const nextRoot = branch[keySegment] |
81 | if (!nextRoot) { |
82 | return { |
83 | root: root, |
84 | index: index |
85 | } |
86 | } else { |
87 | parent = root |
88 | root = nextRoot |
89 | } |
90 | } else { |
91 | break |
92 | } |
93 | |
94 | index++ |
95 | } |
96 | |
97 | const value = treeNode.getValue(root) |
98 | |
99 | return { |
100 | value: value, |
101 | root: root, |
102 | parent: parent, |
103 | index: index |
104 | } |
105 | } |
106 | |
107 | /** |
108 | * gets a value given a key |
109 | * @param {*} key |
110 | * @return {Promise} |
111 | */ |
112 | async get (key, decode) { |
113 | key = RadixTree.formatKey(key) |
114 | let {root, value} = await this._get(key) |
115 | if (decode && Buffer.isBuffer(value)) { |
116 | value = cbor.decode(value) |
117 | treeNode.setValue(root, value) |
118 | } |
119 | return value |
120 | } |
121 | |
122 | /** |
123 | * stores a value at a given key |
124 | * @param {*} key |
125 | * @return {Promise} |
126 | */ |
127 | async set (key, value) { |
128 | key = RadixTree.formatKey(key) |
129 | |
130 | if (treeNode.isEmpty(this.root)) { |
131 | this.root['/'] = createNode(key, [null, null], value)['/'] |
132 | } else { |
133 | let {root, extensionIndex, extension, index, value: rValue} = await this._get(key) |
134 | |
135 | if (rValue) { |
136 | treeNode.setValue(root, value) |
137 | } else { |
138 | if (extensionIndex !== undefined) { |
139 | // split the extension node in two |
140 | const extensionKey = extension[extensionIndex] |
141 | const remExtension = extension.subarray(extensionIndex + 1) |
142 | extension = extension.subarray(0, extensionIndex) |
143 | |
144 | treeNode.setExtension(root, remExtension) |
145 | const branch = [null, null] |
146 | branch[extensionKey] = {'/': root['/']} |
147 | root['/'] = createNode(extension, branch)['/'] |
148 | } |
149 | |
150 | // if there are remaning key segments create an extension node |
151 | if (index < key.length) { |
152 | const keySegment = key[index] |
153 | const extension = key.subarray(index + 1, key.length) |
154 | const newNode = createNode(extension, [null, null], value) |
155 | const rootBranch = treeNode.getBranch(root) |
156 | rootBranch[keySegment] = newNode |
157 | treeNode.setBranch(root, rootBranch) |
158 | } else { |
159 | treeNode.setValue(root, value) |
160 | } |
161 | } |
162 | } |
163 | } |
164 | |
165 | /** |
166 | * deletes a value at a given key |
167 | * @param {*} key |
168 | * @return {Promise} |
169 | */ |
170 | async delete (key) { |
171 | key = RadixTree.formatKey(key) |
172 | const results = await this._get(key) |
173 | if (results.value !== undefined) { |
174 | const root = results.root |
175 | const parent = results.parent |
176 | |
177 | treeNode.deleteValue(root) |
178 | |
179 | const branch = treeNode.getBranch(root) |
180 | if (branch.some(el => el !== null)) { |
181 | joinNodes(root) |
182 | } else { |
183 | if (!parent) { |
184 | root['/'] = RadixTree.emptyTreeState |
185 | } else { |
186 | let branch = treeNode.getBranch(parent) |
187 | branch = branch.map(node => node === root ? null : node) |
188 | treeNode.setBranch(parent, branch) |
189 | await this.graph.tree(parent, 2) |
190 | |
191 | joinNodes(parent) |
192 | } |
193 | } |
194 | } |
195 | |
196 | function joinNodes (root) { |
197 | if (treeNode.getValue(root) === undefined) { |
198 | let index |
199 | const branch = treeNode.getBranch(root) |
200 | const nodes = branch.filter((node, i) => { |
201 | if (node) { |
202 | index = i |
203 | return true |
204 | } |
205 | }) |
206 | |
207 | if (nodes.length === 1) { |
208 | const child = nodes[0] |
209 | const pExtension = treeNode.getExtension(root) |
210 | const childExtension = treeNode.getExtension(child) |
211 | const newExtension = new RadixTree.ArrayConstructor(pExtension.length + childExtension.length + 1) |
212 | |
213 | newExtension.set(pExtension) |
214 | newExtension[pExtension.length] = index |
215 | newExtension.set(childExtension, pExtension.length + 1) |
216 | |
217 | treeNode.setExtension(child, newExtension) |
218 | root['/'] = child['/'] |
219 | } |
220 | } |
221 | } |
222 | } |
223 | |
224 | /** |
225 | * creates a merkle root for the current tree and stores the data perstantly |
226 | * @returns {Promise} |
227 | */ |
228 | flush () { |
229 | return this.graph.flush(this.root) |
230 | } |
231 | |
232 | static formatKey (key) { |
233 | if (typeof key === 'string') { |
234 | key = encoder.encode(key) |
235 | } |
236 | |
237 | if (key.constructor !== RadixTree.ArrayConstructor) { |
238 | return new RadixTree.ArrayConstructor(key.buffer) |
239 | } else { |
240 | return key |
241 | } |
242 | } |
243 | } |
244 | |
245 | function createNode (ex, branch, value) { |
246 | const node = { |
247 | '/': [] |
248 | } |
249 | |
250 | treeNode.setValue(node, value) |
251 | treeNode.setExtension(node, ex) |
252 | treeNode.setBranch(node, branch) |
253 | |
254 | return node |
255 | } |
256 | |
257 | function findMatchBits (key, node) { |
258 | let extensionIndex = 0 |
259 | const extension = treeNode.getExtension(node) |
260 | const extensionLen = extension.length |
261 | |
262 | // checks the extension against the key |
263 | while (extensionIndex < extensionLen && extension[extensionIndex] === key[extensionIndex]) { |
264 | extensionIndex++ |
265 | } |
266 | |
267 | return { |
268 | extensionIndex: extensionIndex, |
269 | extensionLen: extensionLen, |
270 | extension: extension |
271 | } |
272 | } |
273 |
Built with git-ssb-web