BAVL.h 17 KB

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