Linux 5.1.15
[linux/fpc-iii.git] / tools / perf / util / rblist.c
blob11e07fab20dc17f91c8005b77b6585648f78862c
1 /*
2 * Based on strlist.c by:
3 * (c) 2009 Arnaldo Carvalho de Melo <acme@redhat.com>
5 * Licensed under the GPLv2.
6 */
8 #include <errno.h>
9 #include <stdio.h>
10 #include <stdlib.h>
12 #include "rblist.h"
14 int rblist__add_node(struct rblist *rblist, const void *new_entry)
16 struct rb_node **p = &rblist->entries.rb_root.rb_node;
17 struct rb_node *parent = NULL, *new_node;
18 bool leftmost = true;
20 while (*p != NULL) {
21 int rc;
23 parent = *p;
25 rc = rblist->node_cmp(parent, new_entry);
26 if (rc > 0)
27 p = &(*p)->rb_left;
28 else if (rc < 0) {
29 p = &(*p)->rb_right;
30 leftmost = false;
32 else
33 return -EEXIST;
36 new_node = rblist->node_new(rblist, new_entry);
37 if (new_node == NULL)
38 return -ENOMEM;
40 rb_link_node(new_node, parent, p);
41 rb_insert_color_cached(new_node, &rblist->entries, leftmost);
42 ++rblist->nr_entries;
44 return 0;
47 void rblist__remove_node(struct rblist *rblist, struct rb_node *rb_node)
49 rb_erase_cached(rb_node, &rblist->entries);
50 --rblist->nr_entries;
51 rblist->node_delete(rblist, rb_node);
54 static struct rb_node *__rblist__findnew(struct rblist *rblist,
55 const void *entry,
56 bool create)
58 struct rb_node **p = &rblist->entries.rb_root.rb_node;
59 struct rb_node *parent = NULL, *new_node = NULL;
60 bool leftmost = true;
62 while (*p != NULL) {
63 int rc;
65 parent = *p;
67 rc = rblist->node_cmp(parent, entry);
68 if (rc > 0)
69 p = &(*p)->rb_left;
70 else if (rc < 0) {
71 p = &(*p)->rb_right;
72 leftmost = false;
74 else
75 return parent;
78 if (create) {
79 new_node = rblist->node_new(rblist, entry);
80 if (new_node) {
81 rb_link_node(new_node, parent, p);
82 rb_insert_color_cached(new_node,
83 &rblist->entries, leftmost);
84 ++rblist->nr_entries;
88 return new_node;
91 struct rb_node *rblist__find(struct rblist *rblist, const void *entry)
93 return __rblist__findnew(rblist, entry, false);
96 struct rb_node *rblist__findnew(struct rblist *rblist, const void *entry)
98 return __rblist__findnew(rblist, entry, true);
101 void rblist__init(struct rblist *rblist)
103 if (rblist != NULL) {
104 rblist->entries = RB_ROOT_CACHED;
105 rblist->nr_entries = 0;
108 return;
111 void rblist__exit(struct rblist *rblist)
113 struct rb_node *pos, *next = rb_first_cached(&rblist->entries);
115 while (next) {
116 pos = next;
117 next = rb_next(pos);
118 rblist__remove_node(rblist, pos);
122 void rblist__delete(struct rblist *rblist)
124 if (rblist != NULL) {
125 rblist__exit(rblist);
126 free(rblist);
130 struct rb_node *rblist__entry(const struct rblist *rblist, unsigned int idx)
132 struct rb_node *node;
134 for (node = rb_first_cached(&rblist->entries); node;
135 node = rb_next(node)) {
136 if (!idx--)
137 return node;
140 return NULL;