rbtree-utils.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright (C) 2014 Facebook. All rights reserved.
  3. *
  4. * This program is free software; you can redistribute it and/or
  5. * modify it under the terms of the GNU General Public
  6. * License v2 as published by the Free Software Foundation.
  7. *
  8. * This program is distributed in the hope that it will be useful,
  9. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  11. * General Public License for more details.
  12. *
  13. * You should have received a copy of the GNU General Public
  14. * License along with this program; if not, write to the
  15. * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
  16. * Boston, MA 021110-1307, USA.
  17. */
  18. #include <linux/errno.h>
  19. #include "rbtree-utils.h"
  20. int rb_insert(struct rb_root *root, struct rb_node *node,
  21. rb_compare_nodes comp)
  22. {
  23. struct rb_node **p = &root->rb_node;
  24. struct rb_node *parent = NULL;
  25. int ret;
  26. while(*p) {
  27. parent = *p;
  28. ret = comp(parent, node);
  29. if (ret < 0)
  30. p = &(*p)->rb_left;
  31. else if (ret > 0)
  32. p = &(*p)->rb_right;
  33. else
  34. return -EEXIST;
  35. }
  36. rb_link_node(node, parent, p);
  37. rb_insert_color(node, root);
  38. return 0;
  39. }
  40. struct rb_node *rb_search(struct rb_root *root, void *key, rb_compare_keys comp,
  41. struct rb_node **next_ret)
  42. {
  43. struct rb_node *n = root->rb_node;
  44. struct rb_node *parent = NULL;
  45. int ret = 0;
  46. while(n) {
  47. parent = n;
  48. ret = comp(n, key);
  49. if (ret < 0)
  50. n = n->rb_left;
  51. else if (ret > 0)
  52. n = n->rb_right;
  53. else
  54. return n;
  55. }
  56. if (!next_ret)
  57. return NULL;
  58. if (parent && ret > 0)
  59. parent = rb_next(parent);
  60. *next_ret = parent;
  61. return NULL;
  62. }
  63. void rb_free_nodes(struct rb_root *root, rb_free_node free_node)
  64. {
  65. struct rb_node *node;
  66. while ((node = rb_first(root))) {
  67. rb_erase(node, root);
  68. free_node(node);
  69. }
  70. }