6 * idtree_new - create an idr_context
7 * @mem_ctx: talloc parent to allocate from (may be NULL).
9 * Allocate an empty id tree. You can free it with talloc_free().
12 * static struct idtree *ids;
14 * static void init(void)
16 * ids = idtree_new(NULL);
18 * err(1, "Failed to allocate idtree");
21 struct idtree *idtree_new(void *mem_ctx);
24 * idtree_add - get lowest available id, and assign a pointer to it.
25 * @idtree: the tree to allocate from
26 * @ptr: the non-NULL pointer to associate with the id
27 * @limit: the maximum id to allocate (ie. INT_MAX means no limit).
29 * This returns a non-negative id number, or -1 if all are taken.
37 * // Create a new foo, assigning an id.
38 * static struct foo *new_foo(void)
41 * struct foo *foo = malloc(sizeof(*foo));
45 * id = idtree_add(ids, foo, INT_MAX);
54 int idtree_add(struct idtree *idtree, const void *ptr, int limit);
57 * idtree_add_above - get lowest available id, starting at a given value.
58 * @idtree: the tree to allocate from
59 * @ptr: the non-NULL pointer to associate with the id
60 * @starting_id: the minimum id value to consider.
61 * @limit: the maximum id to allocate (ie. INT_MAX means no limit).
64 * static int last_id = -1;
66 * // Create a new foo, assigning a consecutive id.
67 * // This maximizes the time before ids roll.
68 * static struct foo *new_foo_inc_id(void)
71 * struct foo *foo = malloc(sizeof(*foo));
75 * id = idtree_add_above(ids, foo, last_id+1, INT_MAX);
77 * id = idtree_add(ids, foo, INT_MAX);
88 int idtree_add_above(struct idtree *idtree, const void *ptr,
89 int starting_id, int limit);
92 * idtree_lookup - look up a given id
93 * @idtree: the tree to look in
94 * @id: the id to look up
96 * Returns NULL if the value is not found, otherwise the pointer value
97 * set with the idtree_add()/idtree_add_above().
100 * // Look up a foo for a given ID.
101 * static struct foo *find_foo(unsigned int id)
103 * return idtree_lookup(ids, id);
106 void *idtree_lookup(const struct idtree *idtree, int id);
109 * idtree_remove - remove a given id.
110 * @idtree: the tree to remove from
111 * @id: the id to remove.
113 * Returns false if the id was not in the tree.
116 * // Look up a foo for a given ID.
117 * static void free_foo(struct foo *foo)
119 * bool exists = idtree_remove(ids, foo->id);
124 bool idtree_remove(struct idtree *idtree, int id);
125 #endif /* CCAN_IDTREE_H */