d71a8f7489f411a38c164c047efe770f6978d0ee
[project/netifd.git] / utils.h
1 #ifndef __NETIFD_UTILS_H
2 #define __NETIFD_UTILS_H
3
4 #include <libubox/list.h>
5 #include <libubox/avl.h>
6
7 #ifdef DEBUG
8 #define DPRINTF(format, ...) fprintf(stderr, "%s(%d): " format, __func__, __LINE__, ## __VA_ARGS__)
9 #else
10 #define DPRINTF(format, ...) no_debug(format, ## __VA_ARGS__)
11 #endif
12
13 static inline void no_debug(const char *fmt, ...)
14 {
15 }
16
17 #define __init __attribute__((constructor))
18
19 struct vlist_tree;
20 struct vlist_node;
21
22 typedef void (*vlist_update_cb)(struct vlist_tree *tree,
23 struct vlist_node *node_new,
24 struct vlist_node *node_old);
25
26 struct vlist_tree {
27 struct avl_tree avl;
28
29 vlist_update_cb update;
30 int key_offset;
31 bool keep_old;
32
33 int version;
34 };
35
36 struct vlist_node {
37 struct avl_node avl;
38 int version;
39 };
40
41 void __vlist_init(struct vlist_tree *tree, avl_tree_comp cmp, vlist_update_cb update, int offset);
42
43 #define vlist_init(tree, cmp, update, type, node, key) \
44 __vlist_init(tree, cmp, update, offsetof(type, key) - offsetof(type, node))
45
46 void vlist_add(struct vlist_tree *tree, struct vlist_node *node);
47 void vlist_delete(struct vlist_tree *tree, struct vlist_node *node);
48 void vlist_flush(struct vlist_tree *tree);
49 void vlist_flush_all(struct vlist_tree *tree);
50
51 #define vlist_for_each_element(tree, element, node_member) \
52 avl_for_each_element(&(tree)->avl, element, node_member.avl)
53
54 #ifdef __linux__
55 static inline int fls(int x)
56 {
57 int r = 32;
58
59 if (!x)
60 return 0;
61 if (!(x & 0xffff0000u)) {
62 x <<= 16;
63 r -= 16;
64 }
65 if (!(x & 0xff000000u)) {
66 x <<= 8;
67 r -= 8;
68 }
69 if (!(x & 0xf0000000u)) {
70 x <<= 4;
71 r -= 4;
72 }
73 if (!(x & 0xc0000000u)) {
74 x <<= 2;
75 r -= 2;
76 }
77 if (!(x & 0x80000000u)) {
78 x <<= 1;
79 r -= 1;
80 }
81 return r;
82 }
83 #endif
84
85 int avl_strcmp(const void *k1, const void *k2, void *ptr);
86
87 #endif