-
Notifications
You must be signed in to change notification settings - Fork 0
/
td_rebalance.c
58 lines (53 loc) · 1.13 KB
/
td_rebalance.c
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
/*
** Copyright 2015 K.J. Hermans (kees.jan.hermans@gmail.com)
** This code is part of simpledbm, an API to a dbm on a finite resource.
** License: BSD
*/
#ifdef __cplusplus
extern "C" {
#endif
#include "td_private.h"
#include <math.h>
/**
* Just having this function means that we don't have to link with libmath.
*/
static inline
unsigned td_log2
(unsigned n)
{
unsigned r = 0;
while (n) {
n >>= 1;
++r;
}
return r;
}
/**
* \ingroup btree_private
*
* Rebalances the tree a little bit:
* For every imbalance, the top is shifted one in the right direction,
* even when the imbalance is bigger.
*
* \param[in] td Non-NULL pointer to an initialized btree structure.
*
* \returns Zero on success, or a TDERR_* value on error.
*/
int td_rebalance
(td_t* td)
{
unsigned weight;
double depthfactor = (td_log2(td->header.nentries) * TD_DEPTHEXCESS);
if (td->header.top == 0 ||
td->header.nentries < 2 ||
(double)(td->maxdepth) < depthfactor)
{
return 0;
}
CHECK(td_rebalance_node(td, 0, 0, td->header.top, &weight));
td->maxdepth = (int)(depthfactor / 2);
return 0;
}
#ifdef __cplusplus
}
#endif