1 /* netq.h -- Simple packet queue
2 *
3 * Copyright (C) 2010--2012 Olaf Bergmann <bergmann@tzi.org>
4 *
5 * This file is part of the library tinyDTLS. Please see the file
6 * LICENSE for terms of use.
7 */
8
9 #include "dtls_config.h"
10 #include "debug.h"
11 #include "netq.h"
12
13 #ifdef HAVE_ASSERT_H
14 #include <assert.h>
15 #else
16 #ifndef assert
17 #warning "assertions are disabled"
18 # define assert(x)
19 #endif
20 #endif
21
22 #include "t_list.h"
23
24 #ifndef WITH_CONTIKI
25 #include <stdlib.h>
26
27 static inline netq_t *
netq_malloc_node(size_t size)28 netq_malloc_node(size_t size) {
29 return (netq_t *)malloc(sizeof(netq_t) + size);
30 }
31
32 static inline void
netq_free_node(netq_t * node)33 netq_free_node(netq_t *node) {
34 free(node);
35 }
36
37 /* FIXME: implement Contiki's list functions using utlist.h */
38
39 #else /* WITH_CONTIKI */
40 #include "memb.h"
41
42 MEMB(netq_storage, netq_t, NETQ_MAXCNT);
43
44 static inline netq_t *
netq_malloc_node(size_t size)45 netq_malloc_node(size_t size) {
46 return (netq_t *)memb_alloc(&netq_storage);
47 }
48
49 static inline void
netq_free_node(netq_t * node)50 netq_free_node(netq_t *node) {
51 memb_free(&netq_storage, node);
52 }
53
54 void
netq_init()55 netq_init() {
56 memb_init(&netq_storage);
57 }
58 #endif /* WITH_CONTIKI */
59
60 int
netq_insert_node(list_t queue,netq_t * node)61 netq_insert_node(list_t queue, netq_t *node) {
62 netq_t *p;
63
64 assert(queue);
65 assert(node);
66
67 p = (netq_t *)list_head(queue);
68 while(p && p->t <= node->t && list_item_next(p))
69 p = list_item_next(p);
70
71 if (p)
72 list_insert(queue, p, node);
73 else
74 list_push(queue, node);
75
76 return 1;
77 }
78
79 netq_t *
netq_head(list_t queue)80 netq_head(list_t queue) {
81 if (!queue)
82 return NULL;
83
84 return list_head(queue);
85 }
86
87 netq_t *
netq_next(netq_t * p)88 netq_next(netq_t *p) {
89 if (!p)
90 return NULL;
91
92 return list_item_next(p);
93 }
94
95 void
netq_remove(list_t queue,netq_t * p)96 netq_remove(list_t queue, netq_t *p) {
97 if (!queue || !p)
98 return;
99
100 list_remove(queue, p);
101 }
102
netq_pop_first(list_t queue)103 netq_t *netq_pop_first(list_t queue) {
104 if (!queue)
105 return NULL;
106
107 return list_pop(queue);
108 }
109
110 netq_t *
netq_node_new(size_t size)111 netq_node_new(size_t size) {
112 netq_t *node;
113 node = netq_malloc_node(size);
114
115 #ifndef NDEBUG
116 if (!node)
117 dtls_warn("netq_node_new: malloc\n");
118 #endif
119
120 if (node)
121 memset(node, 0, sizeof(netq_t));
122
123 return node;
124 }
125
126 void
netq_node_free(netq_t * node)127 netq_node_free(netq_t *node) {
128 if (node)
129 netq_free_node(node);
130 }
131
132 void
netq_delete_all(list_t queue)133 netq_delete_all(list_t queue) {
134 netq_t *p;
135 if (queue) {
136 while((p = list_pop(queue)))
137 netq_free_node(p);
138 }
139 }
140
141