BAVL.h 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597
  1. /**
  2. * @file BAVL.h
  3. * @author Ambroz Bizjak <ambrop7@gmail.com>
  4. *
  5. * @section LICENSE
  6. *
  7. * This file is part of BadVPN.
  8. *
  9. * BadVPN is free software: you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License version 2
  11. * as published by the Free Software Foundation.
  12. *
  13. * BadVPN is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License along
  19. * with this program; if not, write to the Free Software Foundation, Inc.,
  20. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  21. *
  22. * @section DESCRIPTION
  23. *
  24. * AVL tree.
  25. */
  26. #ifndef BADVPN_STRUCTURE_BAVL_H
  27. #define BADVPN_STRUCTURE_BAVL_H
  28. //#define BAVL_DEBUG
  29. #include <stdint.h>
  30. #include <stddef.h>
  31. #include <misc/debug.h>
  32. /**
  33. * Handler function called by tree algorithms to compare two values.
  34. * For any two values, the comparator must always return the same result.
  35. * The <= relation defined by the comparator must be a total order.
  36. * Values are obtained like that:
  37. * - The value of a node in the tree, or a node that is being inserted is:
  38. * (uint8_t *)node + offset.
  39. * - The value being looked up is the same as given to the lookup function.
  40. *
  41. * @param user as in {@link BAVL_Init}
  42. * @param val1 first value
  43. * @param val2 second value
  44. * @return -1 if val1 < val2, 0 if val1 = val2, 1 if val1 > val2
  45. */
  46. typedef int (*BAVL_comparator) (void *user, void *val1, void *val2);
  47. struct BAVLNode;
  48. /**
  49. * AVL tree.
  50. */
  51. typedef struct {
  52. int offset;
  53. BAVL_comparator comparator;
  54. void *user;
  55. struct BAVLNode *root;
  56. #ifndef NDEBUG
  57. int in_handler;
  58. #endif
  59. } BAVL;
  60. /**
  61. * AVL tree node.
  62. */
  63. typedef struct BAVLNode {
  64. struct BAVLNode *parent;
  65. struct BAVLNode *link[2];
  66. int balance;
  67. } BAVLNode;
  68. /**
  69. * Initializes the tree.
  70. *
  71. * @param o tree to initialize
  72. * @param offset offset of a value from its node
  73. * @param comparator value comparator handler function
  74. * @param user value to pass to comparator
  75. */
  76. static void BAVL_Init (BAVL *o, int offset, BAVL_comparator comparator, void *user);
  77. /**
  78. * Inserts a node into the tree.
  79. * Must not be called from comparator.
  80. *
  81. * @param o the tree
  82. * @param node uninitialized node to insert. Must have a valid value (its value
  83. * may be passed to the comparator during insertion).
  84. * @param ref if not NULL, will return (regardless if insertion succeeded):
  85. * - the greatest node lesser than the inserted value, or (not in order)
  86. * - the smallest node greater than the inserted value, or
  87. * - NULL meaning there were no nodes in the tree.
  88. * @param 1 on success, 0 if an element with an equal value is already in the tree
  89. */
  90. static int BAVL_Insert (BAVL *o, BAVLNode *node, BAVLNode **ref);
  91. /**
  92. * Removes a node from the tree.
  93. * Must not be called from comparator.
  94. *
  95. * @param o the tree
  96. * @param node node to remove
  97. */
  98. static void BAVL_Remove (BAVL *o, BAVLNode *node);
  99. /**
  100. * Checks if the tree is empty.
  101. * Must not be called from comparator.
  102. *
  103. * @param o the tree
  104. * @return 1 if empty, 0 if not
  105. */
  106. static int BAVL_IsEmpty (BAVL *o);
  107. /**
  108. * Looks for a value in the tree.
  109. * Must not be called from comparator.
  110. *
  111. * @param o the tree
  112. * @param val value to look for
  113. * @return If a node is in the thee with an equal value, that node.
  114. * Else if the tree is not empty:
  115. * - the greatest node lesser than the given value, or (not in order)
  116. * - the smallest node greater than the given value.
  117. * NULL if the tree is empty.
  118. */
  119. static BAVLNode * BAVL_Lookup (BAVL *o, void *val);
  120. /**
  121. * Looks for a value in the tree.
  122. * Must not be called from comparator.
  123. *
  124. * @param o the tree
  125. * @param val value to look for
  126. * @return If a node is in the thee with an equal value, that node.
  127. * Else NULL.
  128. */
  129. static BAVLNode * BAVL_LookupExact (BAVL *o, void *val);
  130. #define BAVL_MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b))
  131. #define BAVL_OPTNEG(_a, _neg) ((_neg) ? -(_a) : (_a))
  132. static void * _BAVL_node_value (BAVL *o, BAVLNode *n)
  133. {
  134. return ((uint8_t *)n + o->offset);
  135. }
  136. static int _BAVL_compare_values (BAVL *o, void *v1, void *v2)
  137. {
  138. #ifndef NDEBUG
  139. o->in_handler = 1;
  140. #endif
  141. int res = o->comparator(o->user, v1, v2);
  142. #ifndef NDEBUG
  143. o->in_handler = 0;
  144. #endif
  145. ASSERT(res == -1 || res == 0 || res == 1)
  146. return res;
  147. }
  148. static int _BAVL_compare_nodes (BAVL *o, BAVLNode *n1, BAVLNode *n2)
  149. {
  150. return _BAVL_compare_values(o, _BAVL_node_value(o, n1), _BAVL_node_value(o, n2));
  151. }
  152. #ifdef BAVL_DEBUG
  153. #define BAVL_ASSERT(_h) _BAVL_assert(_h);
  154. #else
  155. #define BAVL_ASSERT(_h)
  156. #endif
  157. #ifdef BAVL_DEBUG
  158. static int _BAVL_assert_recurser (BAVL *o, BAVLNode *n)
  159. {
  160. ASSERT(n->balance >= -1 && n->balance <= 1)
  161. int height_left = 0;
  162. int height_right = 0;
  163. // check left subtree
  164. if (n->link[0]) {
  165. // check parent link
  166. ASSERT(n->link[0]->parent == n)
  167. // check binary search tree
  168. ASSERT(_BAVL_compare_nodes(o, n->link[0], n) == -1)
  169. // recursively calculate height
  170. height_left = _BAVL_assert_recurser(o, n->link[0]);
  171. }
  172. // check right subtree
  173. if (n->link[1]) {
  174. // check parent link
  175. ASSERT(n->link[1]->parent == n)
  176. // check binary search tree
  177. ASSERT(_BAVL_compare_nodes(o, n->link[1], n) == 1)
  178. // recursively calculate height
  179. height_right = _BAVL_assert_recurser(o, n->link[1]);
  180. }
  181. // check balance factor
  182. ASSERT(n->balance == height_right - height_left)
  183. return (BAVL_MAX(height_left, height_right) + 1);
  184. }
  185. static void _BAVL_assert (BAVL *o)
  186. {
  187. if (o->root) {
  188. ASSERT(!o->root->parent)
  189. _BAVL_assert_recurser(o, o->root);
  190. }
  191. }
  192. #endif
  193. static void _BAVL_rotate (BAVL *tree, BAVLNode *r, int dir)
  194. {
  195. BAVLNode *nr = r->link[!dir];
  196. r->link[!dir] = nr->link[dir];
  197. if (r->link[!dir]) {
  198. r->link[!dir]->parent = r;
  199. }
  200. nr->link[dir] = r;
  201. nr->parent = r->parent;
  202. if (nr->parent) {
  203. nr->parent->link[r == r->parent->link[1]] = nr;
  204. } else {
  205. tree->root = nr;
  206. }
  207. r->parent = nr;
  208. }
  209. static BAVLNode * _BAVL_subtree_max (BAVLNode *n)
  210. {
  211. ASSERT(n)
  212. while (n->link[1]) {
  213. n = n->link[1];
  214. }
  215. return n;
  216. }
  217. static void _BAVL_replace_subtree (BAVL *tree, BAVLNode *dest, BAVLNode *n)
  218. {
  219. ASSERT(dest)
  220. if (dest->parent) {
  221. dest->parent->link[dest == dest->parent->link[1]] = n;
  222. } else {
  223. tree->root = n;
  224. }
  225. if (n) {
  226. n->parent = dest->parent;
  227. }
  228. }
  229. static void _BAVL_swap_nodes (BAVL *tree, BAVLNode *n1, BAVLNode *n2)
  230. {
  231. if (n2->parent == n1 || n1->parent == n2) {
  232. // when the nodes are directly connected we need special handling
  233. // make sure n1 is above n2
  234. if (n1->parent == n2) {
  235. BAVLNode *t = n1;
  236. n1 = n2;
  237. n2 = t;
  238. }
  239. int side = (n2 == n1->link[1]);
  240. BAVLNode *c = n1->link[!side];
  241. if (n1->link[0] = n2->link[0]) {
  242. n1->link[0]->parent = n1;
  243. }
  244. if (n1->link[1] = n2->link[1]) {
  245. n1->link[1]->parent = n1;
  246. }
  247. if (n2->parent = n1->parent) {
  248. n2->parent->link[n1 == n1->parent->link[1]] = n2;
  249. } else {
  250. tree->root = n2;
  251. }
  252. n2->link[side] = n1;
  253. n1->parent = n2;
  254. if (n2->link[!side] = c) {
  255. c->parent = n2;
  256. }
  257. } else {
  258. BAVLNode *temp;
  259. // swap parents
  260. temp = n1->parent;
  261. if (n1->parent = n2->parent) {
  262. n1->parent->link[n2 == n2->parent->link[1]] = n1;
  263. } else {
  264. tree->root = n1;
  265. }
  266. if (n2->parent = temp) {
  267. n2->parent->link[n1 == temp->link[1]] = n2;
  268. } else {
  269. tree->root = n2;
  270. }
  271. // swap left children
  272. temp = n1->link[0];
  273. if (n1->link[0] = n2->link[0]) {
  274. n1->link[0]->parent = n1;
  275. }
  276. if (n2->link[0] = temp) {
  277. n2->link[0]->parent = n2;
  278. }
  279. // swap right children
  280. temp = n1->link[1];
  281. if (n1->link[1] = n2->link[1]) {
  282. n1->link[1]->parent = n1;
  283. }
  284. if (n2->link[1] = temp) {
  285. n2->link[1]->parent = n2;
  286. }
  287. }
  288. // swap balance factors
  289. int b = n1->balance;
  290. n1->balance = n2->balance;
  291. n2->balance = b;
  292. }
  293. static void _BAVL_rebalance (BAVL *o, BAVLNode *node, int side, int deltac)
  294. {
  295. ASSERT(side == 0 || side == 1)
  296. ASSERT(deltac >= -1 && deltac <= 1)
  297. ASSERT(node->balance >= -1 && node->balance <= 1)
  298. // if no subtree changed its height, no more rebalancing is needed
  299. if (deltac == 0) {
  300. return;
  301. }
  302. // calculate how much our height changed
  303. int delta = BAVL_MAX(deltac, BAVL_OPTNEG(node->balance, side)) - BAVL_MAX(0, BAVL_OPTNEG(node->balance, side));
  304. ASSERT(delta >= -1 && delta <= 1)
  305. // update our balance factor
  306. node->balance -= BAVL_OPTNEG(deltac, side);
  307. BAVLNode *child;
  308. BAVLNode *gchild;
  309. // perform transformations if the balance factor is wrong
  310. if (node->balance == 2 || node->balance == -2) {
  311. int bside;
  312. int bsidef;
  313. if (node->balance == 2) {
  314. bside = 1;
  315. bsidef = 1;
  316. } else {
  317. bside = 0;
  318. bsidef = -1;
  319. }
  320. ASSERT(node->link[bside])
  321. child = node->link[bside];
  322. switch (child->balance * bsidef) {
  323. case 1:
  324. _BAVL_rotate(o, node, !bside);
  325. node->balance = 0;
  326. child->balance = 0;
  327. node = child;
  328. delta -= 1;
  329. break;
  330. case 0:
  331. _BAVL_rotate(o, node, !bside);
  332. node->balance = 1 * bsidef;
  333. child->balance = -1 * bsidef;
  334. node = child;
  335. break;
  336. case -1:
  337. ASSERT(child->link[!bside])
  338. gchild = child->link[!bside];
  339. _BAVL_rotate(o, child, bside);
  340. _BAVL_rotate(o, node, !bside);
  341. node->balance = -BAVL_MAX(0, gchild->balance * bsidef) * bsidef;
  342. child->balance = BAVL_MAX(0, -gchild->balance * bsidef) * bsidef;
  343. gchild->balance = 0;
  344. node = gchild;
  345. delta -= 1;
  346. break;
  347. default:
  348. ASSERT(0);
  349. }
  350. }
  351. ASSERT(delta >= -1 && delta <= 1)
  352. // Transformations above preserve this. Proof:
  353. // - if a child subtree gained 1 height and rebalancing was needed,
  354. // it was the heavier subtree. Then delta was was originally 1, because
  355. // the heaviest subtree gained one height. If the transformation reduces
  356. // delta by one, it becomes 0.
  357. // - if a child subtree lost 1 height and rebalancing was needed, it
  358. // was the lighter subtree. Then delta was originally 0, because
  359. // the height of the heaviest subtree was unchanged. If the transformation
  360. // reduces delta by one, it becomes -1.
  361. if (node->parent) {
  362. _BAVL_rebalance(o, node->parent, node == node->parent->link[1], delta);
  363. }
  364. }
  365. void BAVL_Init (BAVL *o, int offset, BAVL_comparator comparator, void *user)
  366. {
  367. o->offset = offset;
  368. o->comparator = comparator;
  369. o->user = user;
  370. o->root = NULL;
  371. #ifndef NDEBUG
  372. o->in_handler = 0;
  373. #endif
  374. BAVL_ASSERT(o)
  375. }
  376. int BAVL_Insert (BAVL *o, BAVLNode *node, BAVLNode **ref)
  377. {
  378. ASSERT(!o->in_handler)
  379. // insert to root?
  380. if (!o->root) {
  381. o->root = node;
  382. node->parent = NULL;
  383. node->link[0] = NULL;
  384. node->link[1] = NULL;
  385. node->balance = 0;
  386. BAVL_ASSERT(o)
  387. if (ref) {
  388. *ref = NULL;
  389. }
  390. return 1;
  391. }
  392. // find node to insert to
  393. BAVLNode *c = o->root;
  394. int side;
  395. while (1) {
  396. // compare
  397. int comp = _BAVL_compare_nodes(o, node, c);
  398. // have we found a node that compares equal?
  399. if (comp == 0) {
  400. if (ref) {
  401. *ref = c;
  402. }
  403. return 0;
  404. }
  405. side = (comp == 1);
  406. // have we reached a leaf?
  407. if (!c->link[side]) {
  408. break;
  409. }
  410. c = c->link[side];
  411. }
  412. // insert
  413. c->link[side] = node;
  414. node->parent = c;
  415. node->link[0] = NULL;
  416. node->link[1] = NULL;
  417. node->balance = 0;
  418. // rebalance
  419. _BAVL_rebalance(o, c, side, 1);
  420. BAVL_ASSERT(o)
  421. if (ref) {
  422. *ref = c;
  423. }
  424. return 1;
  425. }
  426. void BAVL_Remove (BAVL *o, BAVLNode *node)
  427. {
  428. ASSERT(!o->in_handler)
  429. // if we have both subtrees, swap the node and the largest node
  430. // in the left subtree, so we have at most one subtree
  431. if (node->link[0] && node->link[1]) {
  432. // find the largest node in the left subtree
  433. BAVLNode *max = _BAVL_subtree_max(node->link[0]);
  434. // swap the nodes
  435. _BAVL_swap_nodes(o, node, max);
  436. }
  437. // have at most one child now
  438. ASSERT(!(node->link[0] && node->link[1]))
  439. BAVLNode *parent = node->parent;
  440. BAVLNode *child = (node->link[0] ? node->link[0] : node->link[1]);
  441. if (parent) {
  442. // remember on which side node is
  443. int side = (node == parent->link[1]);
  444. // replace node with child
  445. _BAVL_replace_subtree(o, node, child);
  446. // rebalance
  447. _BAVL_rebalance(o, parent, side, -1);
  448. } else {
  449. // replace node with child
  450. _BAVL_replace_subtree(o, node, child);
  451. }
  452. BAVL_ASSERT(o)
  453. }
  454. int BAVL_IsEmpty (BAVL *o)
  455. {
  456. ASSERT(!o->in_handler)
  457. return (!o->root);
  458. }
  459. BAVLNode * BAVL_Lookup (BAVL *o, void *val)
  460. {
  461. ASSERT(!o->in_handler)
  462. if (!o->root) {
  463. return NULL;
  464. }
  465. BAVLNode *c = o->root;
  466. while (1) {
  467. // compare
  468. int comp = _BAVL_compare_values(o, val, _BAVL_node_value(o, c));
  469. // have we found a node that compares equal?
  470. if (comp == 0) {
  471. return c;
  472. }
  473. int side = (comp == 1);
  474. // have we reached a leaf?
  475. if (!c->link[side]) {
  476. return c;
  477. }
  478. c = c->link[side];
  479. }
  480. }
  481. BAVLNode * BAVL_LookupExact (BAVL *o, void *val)
  482. {
  483. ASSERT(!o->in_handler)
  484. if (!o->root) {
  485. return NULL;
  486. }
  487. BAVLNode *c = o->root;
  488. while (1) {
  489. // compare
  490. int comp = _BAVL_compare_values(o, val, _BAVL_node_value(o, c));
  491. // have we found a node that compares equal?
  492. if (comp == 0) {
  493. return c;
  494. }
  495. int side = (comp == 1);
  496. // have we reached a leaf?
  497. if (!c->link[side]) {
  498. return NULL;
  499. }
  500. c = c->link[side];
  501. }
  502. }
  503. #endif