rblist.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. /*
  2. * Based on strlist.c by:
  3. * (c) 2009 Arnaldo Carvalho de Melo <acme@redhat.com>
  4. *
  5. * Licensed under the GPLv2.
  6. */
  7. #include <errno.h>
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include "rblist.h"
  11. int rblist__add_node(struct rblist *rblist, const void *new_entry)
  12. {
  13. struct rb_node **p = &rblist->entries.rb_node;
  14. struct rb_node *parent = NULL, *new_node;
  15. while (*p != NULL) {
  16. int rc;
  17. parent = *p;
  18. rc = rblist->node_cmp(parent, new_entry);
  19. if (rc > 0)
  20. p = &(*p)->rb_left;
  21. else if (rc < 0)
  22. p = &(*p)->rb_right;
  23. else
  24. return -EEXIST;
  25. }
  26. new_node = rblist->node_new(rblist, new_entry);
  27. if (new_node == NULL)
  28. return -ENOMEM;
  29. rb_link_node(new_node, parent, p);
  30. rb_insert_color(new_node, &rblist->entries);
  31. ++rblist->nr_entries;
  32. return 0;
  33. }
  34. void rblist__remove_node(struct rblist *rblist, struct rb_node *rb_node)
  35. {
  36. rb_erase(rb_node, &rblist->entries);
  37. rblist->node_delete(rblist, rb_node);
  38. }
  39. struct rb_node *rblist__find(struct rblist *rblist, const void *entry)
  40. {
  41. struct rb_node **p = &rblist->entries.rb_node;
  42. struct rb_node *parent = NULL;
  43. while (*p != NULL) {
  44. int rc;
  45. parent = *p;
  46. rc = rblist->node_cmp(parent, entry);
  47. if (rc > 0)
  48. p = &(*p)->rb_left;
  49. else if (rc < 0)
  50. p = &(*p)->rb_right;
  51. else
  52. return parent;
  53. }
  54. return NULL;
  55. }
  56. void rblist__init(struct rblist *rblist)
  57. {
  58. if (rblist != NULL) {
  59. rblist->entries = RB_ROOT;
  60. rblist->nr_entries = 0;
  61. }
  62. return;
  63. }
  64. void rblist__delete(struct rblist *rblist)
  65. {
  66. if (rblist != NULL) {
  67. struct rb_node *pos, *next = rb_first(&rblist->entries);
  68. while (next) {
  69. pos = next;
  70. next = rb_next(pos);
  71. rb_erase(pos, &rblist->entries);
  72. rblist->node_delete(rblist, pos);
  73. }
  74. free(rblist);
  75. }
  76. }
  77. struct rb_node *rblist__entry(const struct rblist *rblist, unsigned int idx)
  78. {
  79. struct rb_node *node;
  80. for (node = rb_first(&rblist->entries); node; node = rb_next(node)) {
  81. if (!idx--)
  82. return node;
  83. }
  84. return NULL;
  85. }