BAVL.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703
  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. /**
  131. * Returns the smallest node in the tree, or NULL if the tree is empty.
  132. *
  133. * @param o the tree
  134. * @return smallest node or NULL
  135. */
  136. static BAVLNode * BAVL_GetFirst (BAVL *o);
  137. /**
  138. * Returns the greatest node in the tree, or NULL if the tree is empty.
  139. *
  140. * @param o the tree
  141. * @return greatest node or NULL
  142. */
  143. static BAVLNode * BAVL_GetLast (BAVL *o);
  144. /**
  145. * Returns the node that follows the given node, or NULL if it's the
  146. * last node.
  147. *
  148. * @param o the tree
  149. * @param n node
  150. * @return next node, or NULL
  151. */
  152. static BAVLNode * BAVL_GetNext (BAVL *o, BAVLNode *n);
  153. /**
  154. * Returns the node that precedes the given node, or NULL if it's the
  155. * first node.
  156. *
  157. * @param o the tree
  158. * @param n node
  159. * @return previous node, or NULL
  160. */
  161. static BAVLNode * BAVL_GetPrev (BAVL *o, BAVLNode *n);
  162. #define BAVL_MAX(_a, _b) ((_a) > (_b) ? (_a) : (_b))
  163. #define BAVL_OPTNEG(_a, _neg) ((_neg) ? -(_a) : (_a))
  164. static void * _BAVL_node_value (BAVL *o, BAVLNode *n)
  165. {
  166. return ((uint8_t *)n + o->offset);
  167. }
  168. static int _BAVL_compare_values (BAVL *o, void *v1, void *v2)
  169. {
  170. #ifndef NDEBUG
  171. o->in_handler = 1;
  172. #endif
  173. int res = o->comparator(o->user, v1, v2);
  174. #ifndef NDEBUG
  175. o->in_handler = 0;
  176. #endif
  177. ASSERT(res == -1 || res == 0 || res == 1)
  178. return res;
  179. }
  180. static int _BAVL_compare_nodes (BAVL *o, BAVLNode *n1, BAVLNode *n2)
  181. {
  182. return _BAVL_compare_values(o, _BAVL_node_value(o, n1), _BAVL_node_value(o, n2));
  183. }
  184. #ifdef BAVL_DEBUG
  185. #define BAVL_ASSERT(_h) _BAVL_assert(_h);
  186. #else
  187. #define BAVL_ASSERT(_h)
  188. #endif
  189. #ifdef BAVL_DEBUG
  190. static int _BAVL_assert_recurser (BAVL *o, BAVLNode *n)
  191. {
  192. ASSERT(n->balance >= -1 && n->balance <= 1)
  193. int height_left = 0;
  194. int height_right = 0;
  195. // check left subtree
  196. if (n->link[0]) {
  197. // check parent link
  198. ASSERT(n->link[0]->parent == n)
  199. // check binary search tree
  200. ASSERT(_BAVL_compare_nodes(o, n->link[0], n) == -1)
  201. // recursively calculate height
  202. height_left = _BAVL_assert_recurser(o, n->link[0]);
  203. }
  204. // check right subtree
  205. if (n->link[1]) {
  206. // check parent link
  207. ASSERT(n->link[1]->parent == n)
  208. // check binary search tree
  209. ASSERT(_BAVL_compare_nodes(o, n->link[1], n) == 1)
  210. // recursively calculate height
  211. height_right = _BAVL_assert_recurser(o, n->link[1]);
  212. }
  213. // check balance factor
  214. ASSERT(n->balance == height_right - height_left)
  215. return (BAVL_MAX(height_left, height_right) + 1);
  216. }
  217. static void _BAVL_assert (BAVL *o)
  218. {
  219. if (o->root) {
  220. ASSERT(!o->root->parent)
  221. _BAVL_assert_recurser(o, o->root);
  222. }
  223. }
  224. #endif
  225. static void _BAVL_rotate (BAVL *tree, BAVLNode *r, int dir)
  226. {
  227. BAVLNode *nr = r->link[!dir];
  228. r->link[!dir] = nr->link[dir];
  229. if (r->link[!dir]) {
  230. r->link[!dir]->parent = r;
  231. }
  232. nr->link[dir] = r;
  233. nr->parent = r->parent;
  234. if (nr->parent) {
  235. nr->parent->link[r == r->parent->link[1]] = nr;
  236. } else {
  237. tree->root = nr;
  238. }
  239. r->parent = nr;
  240. }
  241. static BAVLNode * _BAVL_subtree_max (BAVLNode *n)
  242. {
  243. ASSERT(n)
  244. while (n->link[1]) {
  245. n = n->link[1];
  246. }
  247. return n;
  248. }
  249. static void _BAVL_replace_subtree (BAVL *tree, BAVLNode *dest, BAVLNode *n)
  250. {
  251. ASSERT(dest)
  252. if (dest->parent) {
  253. dest->parent->link[dest == dest->parent->link[1]] = n;
  254. } else {
  255. tree->root = n;
  256. }
  257. if (n) {
  258. n->parent = dest->parent;
  259. }
  260. }
  261. static void _BAVL_swap_nodes (BAVL *tree, BAVLNode *n1, BAVLNode *n2)
  262. {
  263. if (n2->parent == n1 || n1->parent == n2) {
  264. // when the nodes are directly connected we need special handling
  265. // make sure n1 is above n2
  266. if (n1->parent == n2) {
  267. BAVLNode *t = n1;
  268. n1 = n2;
  269. n2 = t;
  270. }
  271. int side = (n2 == n1->link[1]);
  272. BAVLNode *c = n1->link[!side];
  273. if (n1->link[0] = n2->link[0]) {
  274. n1->link[0]->parent = n1;
  275. }
  276. if (n1->link[1] = n2->link[1]) {
  277. n1->link[1]->parent = n1;
  278. }
  279. if (n2->parent = n1->parent) {
  280. n2->parent->link[n1 == n1->parent->link[1]] = n2;
  281. } else {
  282. tree->root = n2;
  283. }
  284. n2->link[side] = n1;
  285. n1->parent = n2;
  286. if (n2->link[!side] = c) {
  287. c->parent = n2;
  288. }
  289. } else {
  290. BAVLNode *temp;
  291. // swap parents
  292. temp = n1->parent;
  293. if (n1->parent = n2->parent) {
  294. n1->parent->link[n2 == n2->parent->link[1]] = n1;
  295. } else {
  296. tree->root = n1;
  297. }
  298. if (n2->parent = temp) {
  299. n2->parent->link[n1 == temp->link[1]] = n2;
  300. } else {
  301. tree->root = n2;
  302. }
  303. // swap left children
  304. temp = n1->link[0];
  305. if (n1->link[0] = n2->link[0]) {
  306. n1->link[0]->parent = n1;
  307. }
  308. if (n2->link[0] = temp) {
  309. n2->link[0]->parent = n2;
  310. }
  311. // swap right children
  312. temp = n1->link[1];
  313. if (n1->link[1] = n2->link[1]) {
  314. n1->link[1]->parent = n1;
  315. }
  316. if (n2->link[1] = temp) {
  317. n2->link[1]->parent = n2;
  318. }
  319. }
  320. // swap balance factors
  321. int b = n1->balance;
  322. n1->balance = n2->balance;
  323. n2->balance = b;
  324. }
  325. static void _BAVL_rebalance (BAVL *o, BAVLNode *node, int side, int deltac)
  326. {
  327. ASSERT(side == 0 || side == 1)
  328. ASSERT(deltac >= -1 && deltac <= 1)
  329. ASSERT(node->balance >= -1 && node->balance <= 1)
  330. // if no subtree changed its height, no more rebalancing is needed
  331. if (deltac == 0) {
  332. return;
  333. }
  334. // calculate how much our height changed
  335. int delta = BAVL_MAX(deltac, BAVL_OPTNEG(node->balance, side)) - BAVL_MAX(0, BAVL_OPTNEG(node->balance, side));
  336. ASSERT(delta >= -1 && delta <= 1)
  337. // update our balance factor
  338. node->balance -= BAVL_OPTNEG(deltac, side);
  339. BAVLNode *child;
  340. BAVLNode *gchild;
  341. // perform transformations if the balance factor is wrong
  342. if (node->balance == 2 || node->balance == -2) {
  343. int bside;
  344. int bsidef;
  345. if (node->balance == 2) {
  346. bside = 1;
  347. bsidef = 1;
  348. } else {
  349. bside = 0;
  350. bsidef = -1;
  351. }
  352. ASSERT(node->link[bside])
  353. child = node->link[bside];
  354. switch (child->balance * bsidef) {
  355. case 1:
  356. _BAVL_rotate(o, node, !bside);
  357. node->balance = 0;
  358. child->balance = 0;
  359. node = child;
  360. delta -= 1;
  361. break;
  362. case 0:
  363. _BAVL_rotate(o, node, !bside);
  364. node->balance = 1 * bsidef;
  365. child->balance = -1 * bsidef;
  366. node = child;
  367. break;
  368. case -1:
  369. ASSERT(child->link[!bside])
  370. gchild = child->link[!bside];
  371. _BAVL_rotate(o, child, bside);
  372. _BAVL_rotate(o, node, !bside);
  373. node->balance = -BAVL_MAX(0, gchild->balance * bsidef) * bsidef;
  374. child->balance = BAVL_MAX(0, -gchild->balance * bsidef) * bsidef;
  375. gchild->balance = 0;
  376. node = gchild;
  377. delta -= 1;
  378. break;
  379. default:
  380. ASSERT(0);
  381. }
  382. }
  383. ASSERT(delta >= -1 && delta <= 1)
  384. // Transformations above preserve this. Proof:
  385. // - if a child subtree gained 1 height and rebalancing was needed,
  386. // it was the heavier subtree. Then delta was was originally 1, because
  387. // the heaviest subtree gained one height. If the transformation reduces
  388. // delta by one, it becomes 0.
  389. // - if a child subtree lost 1 height and rebalancing was needed, it
  390. // was the lighter subtree. Then delta was originally 0, because
  391. // the height of the heaviest subtree was unchanged. If the transformation
  392. // reduces delta by one, it becomes -1.
  393. if (node->parent) {
  394. _BAVL_rebalance(o, node->parent, node == node->parent->link[1], delta);
  395. }
  396. }
  397. void BAVL_Init (BAVL *o, int offset, BAVL_comparator comparator, void *user)
  398. {
  399. o->offset = offset;
  400. o->comparator = comparator;
  401. o->user = user;
  402. o->root = NULL;
  403. #ifndef NDEBUG
  404. o->in_handler = 0;
  405. #endif
  406. BAVL_ASSERT(o)
  407. }
  408. int BAVL_Insert (BAVL *o, BAVLNode *node, BAVLNode **ref)
  409. {
  410. ASSERT(!o->in_handler)
  411. // insert to root?
  412. if (!o->root) {
  413. o->root = node;
  414. node->parent = NULL;
  415. node->link[0] = NULL;
  416. node->link[1] = NULL;
  417. node->balance = 0;
  418. BAVL_ASSERT(o)
  419. if (ref) {
  420. *ref = NULL;
  421. }
  422. return 1;
  423. }
  424. // find node to insert to
  425. BAVLNode *c = o->root;
  426. int side;
  427. while (1) {
  428. // compare
  429. int comp = _BAVL_compare_nodes(o, node, c);
  430. // have we found a node that compares equal?
  431. if (comp == 0) {
  432. if (ref) {
  433. *ref = c;
  434. }
  435. return 0;
  436. }
  437. side = (comp == 1);
  438. // have we reached a leaf?
  439. if (!c->link[side]) {
  440. break;
  441. }
  442. c = c->link[side];
  443. }
  444. // insert
  445. c->link[side] = node;
  446. node->parent = c;
  447. node->link[0] = NULL;
  448. node->link[1] = NULL;
  449. node->balance = 0;
  450. // rebalance
  451. _BAVL_rebalance(o, c, side, 1);
  452. BAVL_ASSERT(o)
  453. if (ref) {
  454. *ref = c;
  455. }
  456. return 1;
  457. }
  458. void BAVL_Remove (BAVL *o, BAVLNode *node)
  459. {
  460. ASSERT(!o->in_handler)
  461. // if we have both subtrees, swap the node and the largest node
  462. // in the left subtree, so we have at most one subtree
  463. if (node->link[0] && node->link[1]) {
  464. // find the largest node in the left subtree
  465. BAVLNode *max = _BAVL_subtree_max(node->link[0]);
  466. // swap the nodes
  467. _BAVL_swap_nodes(o, node, max);
  468. }
  469. // have at most one child now
  470. ASSERT(!(node->link[0] && node->link[1]))
  471. BAVLNode *parent = node->parent;
  472. BAVLNode *child = (node->link[0] ? node->link[0] : node->link[1]);
  473. if (parent) {
  474. // remember on which side node is
  475. int side = (node == parent->link[1]);
  476. // replace node with child
  477. _BAVL_replace_subtree(o, node, child);
  478. // rebalance
  479. _BAVL_rebalance(o, parent, side, -1);
  480. } else {
  481. // replace node with child
  482. _BAVL_replace_subtree(o, node, child);
  483. }
  484. BAVL_ASSERT(o)
  485. }
  486. int BAVL_IsEmpty (BAVL *o)
  487. {
  488. ASSERT(!o->in_handler)
  489. return (!o->root);
  490. }
  491. BAVLNode * BAVL_Lookup (BAVL *o, void *val)
  492. {
  493. ASSERT(!o->in_handler)
  494. if (!o->root) {
  495. return NULL;
  496. }
  497. BAVLNode *c = o->root;
  498. while (1) {
  499. // compare
  500. int comp = _BAVL_compare_values(o, val, _BAVL_node_value(o, c));
  501. // have we found a node that compares equal?
  502. if (comp == 0) {
  503. return c;
  504. }
  505. int side = (comp == 1);
  506. // have we reached a leaf?
  507. if (!c->link[side]) {
  508. return c;
  509. }
  510. c = c->link[side];
  511. }
  512. }
  513. BAVLNode * BAVL_LookupExact (BAVL *o, void *val)
  514. {
  515. ASSERT(!o->in_handler)
  516. if (!o->root) {
  517. return NULL;
  518. }
  519. BAVLNode *c = o->root;
  520. while (1) {
  521. // compare
  522. int comp = _BAVL_compare_values(o, val, _BAVL_node_value(o, c));
  523. // have we found a node that compares equal?
  524. if (comp == 0) {
  525. return c;
  526. }
  527. int side = (comp == 1);
  528. // have we reached a leaf?
  529. if (!c->link[side]) {
  530. return NULL;
  531. }
  532. c = c->link[side];
  533. }
  534. }
  535. BAVLNode * BAVL_GetFirst (BAVL *o)
  536. {
  537. ASSERT(!o->in_handler)
  538. if (!o->root) {
  539. return NULL;
  540. }
  541. BAVLNode *n = o->root;
  542. while (n->link[0]) {
  543. n = n->link[0];
  544. }
  545. return n;
  546. }
  547. BAVLNode * BAVL_GetLast (BAVL *o)
  548. {
  549. ASSERT(!o->in_handler)
  550. if (!o->root) {
  551. return NULL;
  552. }
  553. BAVLNode *n = o->root;
  554. while (n->link[1]) {
  555. n = n->link[1];
  556. }
  557. return n;
  558. }
  559. BAVLNode * BAVL_GetNext (BAVL *o, BAVLNode *n)
  560. {
  561. ASSERT(!o->in_handler)
  562. if (n->link[1]) {
  563. n = n->link[1];
  564. while (n->link[0]) {
  565. n = n->link[0];
  566. }
  567. } else {
  568. while (n->parent && n == n->parent->link[1]) {
  569. n = n->parent;
  570. }
  571. n = n->parent;
  572. }
  573. return n;
  574. }
  575. BAVLNode * BAVL_GetPrev (BAVL *o, BAVLNode *n)
  576. {
  577. ASSERT(!o->in_handler)
  578. if (n->link[0]) {
  579. n = n->link[0];
  580. while (n->link[1]) {
  581. n = n->link[1];
  582. }
  583. } else {
  584. while (n->parent && n == n->parent->link[0]) {
  585. n = n->parent;
  586. }
  587. n = n->parent;
  588. }
  589. return n;
  590. }
  591. #endif