summaryrefslogtreecommitdiff
path: root/src/memidb/aatree.ts
blob: 50c4f0aaeb6dd8b757304436d64551c518313657 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
/*
 This file is part of TALER
 (C) 2017 Inria and GNUnet e.V.

 TALER is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 TALER is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 TALER; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */


/**
 * Implementation of AA trees (Arne Andersson, 1993) as a persistent data
 * structure (Prabhakar Ragde, 2014).
 *
 * AA trees were chosen since they balance efficiency and a simple
 * implementation.
 */


/**
 * An AA tree, either a node or 'undefined' as sentinel element.
 */
export type AATree = AATreeNode | undefined;


interface AATreeNode {
  left: AATree;
  right: AATree;
  level: number;
  key: any;
}


/**
 * Check AA tree invariants.  Useful for testing.
 */
export function checkInvariants(t: AATree): boolean {
  // No invariants for the sentinel.
  if (!t) {
    return true;
  }

  // AA1: The left child of a node x has level one less than x.
  if (level(t.left) != level(t) - 1) {
    console.log("violated AA1");

    console.log(JSON.stringify(t, undefined, 2));
    return false;
  }

  // AA2: The right child of x has the same level (x is a "double" node) or one less (x is a "single" node).
  if (!(level(t.right) === level(t) || level(t.right) === level(t) - 1)) {
    console.log("violated AA2");
    console.log("level(t.right)", level(t.right));
    console.log("level(t)", level(t));
    return false;
  }

  // AA3: The right child of the right child of x has level less than x.
  if (t.right && t.right.right) {
    if (level(t.right.right) >= level(t)) {
      console.log("violated AA3");
      console.log(JSON.stringify(t, undefined, 2));
      return false;
    }
  }

  // AA4: All internal nodes have two children.
  // This invariant follows from how we defined "level"
  return true;
}


/**
 * Fix a violation of invariant AA1 by reversing a link.
 *
 * ```
 *    y <--- t    =>     y ---> t
 *   / \      \   =>    /      / \
 *  a   b      c  =>   a      b   c
 * ```
 */
function skew(t: AATreeNode) {
  if (t.left && t.left.level === t.level) {
    return { ...t.left, right: { ...t, left: t.left.right } };
  }
  return t;
}


/**
 * Fix a violation of invariant AA3 by pulling up the middle node.
 *
 * ```
 *                    =>      y
 *                    =>     / \
 *    t --> y --> z   =>    t   z
 *   /     /          =>   / \
 *  a     b           =>  a   b
 * ```
 */
function split(t: AATreeNode) {
  if (t.right && t.right.right && 
      t.level === t.right.level &&
      t.right.level === t.right.right.level) {
    return {
      level: t.level + 1,
      key: t.right.key,
      left: { ...t, right: t.right.left },
      right: t.right.right,
    }
  }
  return t;
}


/**
 * Non-destructively insert a new key into an AA tree.
 */
export function treeInsert(t: AATree, k: any, cmpFn: (k1: any, k2: any) => number): AATreeNode {
  if (!t) {
    return {
      level: 1,
      key: k,
      left: undefined,
      right: undefined,
    }
  }
  const cmp = cmpFn(k, t.key);
  if (cmp === 0) {
    return t;
  } else if (cmp < 0) {
    return split(skew({ ...t, left: treeInsert(t.left, k, cmpFn)}));
  } else {
    return split(skew({ ...t, right: treeInsert(t.right, k, cmpFn)}));
  }
}


/**
 * Level of an AA tree node, or zero if it's a sentinel.
 */
function level(t: AATree) {
  if (!t) {
    return 0;
  }
  return t.level;
}


/**
 * Check if a node is single, i.e. doens't have a right child
 * on the same level.
 */
function isSingle(t: AATree) {
  if (t && t.right && t.right.level === t.level) {
    return false;
  }
  return true;
}


/**
 * Restore invariants that were broken by deleting a node.
 *
 * Assumes that invariants for t.left and t.right are already adjusted.
 */
function adjust(t: AATreeNode): AATreeNode {
  // First check if left or right subtree are at the right level.  Note that
  // they can't be both at the wrong level, since only one node is deleted
  // before calling adjust.
  const leftOkay = level(t.left) === level(t) - 1;
  const rightOkay = (level(t.right) === level(t) || level(t.right) === level(t) - 1);
  if (leftOkay && rightOkay) {
    return t;
  }
  if (!rightOkay) {
    if (isSingle(t.left)) {
      return skew({ ...t, level: t.level - 1 });
    }
    /*
     *      ( t )       =>      ( b )
     *     /     \      =>     /     \
     *    x -> b  \     =>    x       t
     *   /    / \  \    =>   / \     / \
     *  a    d   e  c   =>  a   d   e   c
     */
    const b = t.left!.right!;
    return {
      level: b.level + 1,
      key: b.key,
      left: { ...t.left, right: b.left },
      right: { ...t, level: t.level - 1, left: b.right },
    };
  }
  if (!leftOkay) {
    if (isSingle(t)) {
      return split({ ...t, level: t.level - 1 });
    }
    /*
     *      t -> ( r )    =>       ( a ) -> r   
     *     /    /     \   =>      /        / \  
     *    /    a -> d  b  =>     t        d   b 
     *   /    /           =>    / \            
     *  x    c            =>   l   c           
     *
     *      t -> r    =>       ( a )
     *     /    / \   =>      /     \
     *    /    a   b  =>     t       r -> b
     *   /    / \     =>    / \     /    
     *  x    c   d    =>   l   c   d
     *
     *  Only Level of r differs, depending on whether a is single or double.
     *  Node 'r' must be split, as node 'b' might be double.
     */
    const a = t.right!.left!;
    const n = isSingle(a) ? a.level : a.level + 1;
    return {
      key: a.key,
      left: { ...t, level: a.level, right: a.left },
      level: a.level + 1,
      right: split({
        level: n,
        left: a.right,
        right: t.right!.right,
        key: t.right!.key,
      }),
    };
  }
  throw Error("not reached");
}


function treeDeleteLargest(t: AATreeNode): { key: any, tree: AATree } {
  if (!t.right) {
    return { key: t.key, tree: t.left };
  }
  const d = treeDeleteLargest(t.right);
  return {
    key: d.key,
    tree: adjust({ ...t, right: d.tree}),
  };
}


/**
 * Count the number of elements stored in the tree.
 */
export function treeSize(t: AATree): number {
  if (!t) {
    return 0;
  }
  return treeSize(t.left) + treeSize(t.right) + 1;
}


/**
 * Get an array of (sorted) keys from an AA tree.
 */
export function treeToArray(t: AATree, accum: any[] = []) {
  if (!t) {
    return accum;
  }
  treeToArray(t.left, accum);
  accum.push(t.key);
  treeToArray(t.right, accum);
  return accum;
}


/**
 * Check if a key can be found in a tree.
 */
export function treeFind(t: AATree, k: any, cmpFn: (k1: any, k2: any) => number): boolean {
  if (!t) {
    return false;
  }
  const cmp = cmpFn(k, t.key);
  if (cmp < 0) {
    return treeFind(t.left, k, cmpFn);
  }
  if (cmp > 0) {
    return treeFind(t.right, k, cmpFn);
  }
  return true;
}


/**
 * Get the largest key in the tree.
 */
export function treeBiggest(t: AATree): any {
  if (!t) {
    return undefined;
  }
  if (!t.right) {
    return t.key;
  }
  return treeBiggest(t);
}


/**
 * Get the smallest key in the tree.
 */
export function treeSmallest(t: AATree): any {
  if (!t) {
    return undefined;
  }
  if (!t.left) {
    return t.key;
  }
  return treeSmallest(t);
}


/**
 * Get the smallest key from the tree that is larger than the given key.
 * Returns 'undefined' if the given key is the largest key.
 */
export function treeNextKey(t: AATree, k: any, cmpFn: (k1: any, k2: any) => number): any {
  if (!t) {
    return undefined;
  }
  const cmp = cmpFn(k, t.key);
  if (cmp === 0) {
    return treeSmallest(t.right);
  }
  if (cmp < 0) {
    const r = treeNextKey(t.left, k, cmpFn);
    if (r) {
      return r;
    }
    return t.key;
  }
  if (cmp < 0) {
    return treeNextKey(t.right, k, cmpFn);
  }
}


/**
 * Get the largest tree from the tree that is smaller than the given key.
 * Returns 'undefined' if the given key is the smallest key.
 */
export function treePreviousKey(t: AATree, k: any, cmpFn: (k1: any, k2: any) => number): any {
  return treeNextKey(t, k, (k1, k2) => -cmpFn(k1, k2));
}


/**
 * Returns a new tree without the given key.
 */
export function treeDelete(t: AATree, k: any, cmpFn: (k1: any, k2: any) => number): AATree {
  if (!t) {
    return t;
  }
  const cmp = cmpFn(k, t.key);
  if (cmp === 0) {
    if (!t.left) {
      return t.right;
    }
    if (!t.right) {
      return t.left;
    }
    const d = treeDeleteLargest(t.left);
    return adjust({
      key: d.key,
      left: d.tree,
      right: t.right,
      level: t.level,
    });
  }
  if (cmp < 0) {
    return adjust({ ...t, left: treeDelete(t.left, k, cmpFn) });
  }
  if (cmp > 0) {
    return adjust({ ...t, right: treeDelete(t.right, k, cmpFn) });
  }
  throw Error("not reached");
}