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->nr_entries;
  38. rblist->node_delete(rblist, rb_node);
  39. }
  40. struct rb_node *rblist__find(struct rblist *rblist, const void *entry)
  41. {
  42. struct rb_node **p = &rblist->entries.rb_node;
  43. struct rb_node *parent = NULL;
  44. while (*p != NULL) {
  45. int rc;
  46. parent = *p;
  47. rc = rblist->node_cmp(parent, entry);
  48. if (rc > 0)
  49. p = &(*p)->rb_left;
  50. else if (rc < 0)
  51. p = &(*p)->rb_right;
  52. else
  53. return parent;
  54. }
  55. return NULL;
  56. }
  57. void rblist__init(struct rblist *rblist)
  58. {
  59. if (rblist != NULL) {
  60. rblist->entries = RB_ROOT;
  61. rblist->nr_entries = 0;
  62. }
  63. return;
  64. }
  65. void rblist__delete(struct rblist *rblist)
  66. {
  67. if (rblist != NULL) {
  68. struct rb_node *pos, *next = rb_first(&rblist->entries);
  69. while (next) {
  70. pos = next;
  71. next = rb_next(pos);
  72. rblist__remove_node(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. }