iotivity 0.9.0
[platform/upstream/iotivity.git] / resource / csdk / libcoap-4.1.1 / coap_list.c
1 /* coap_list.c -- CoAP list structures
2  *
3  * Copyright (C) 2010,2011 Olaf Bergmann <bergmann@tzi.org>
4  *
5  * This file is part of the CoAP library libcoap. Please see
6  * README for terms of use.
7  */
8
9 #include "config.h"
10
11 #include <stdio.h>
12 #include <string.h>
13
14 #include "debug.h"
15 #include "mem.h"
16 #include "coap_list.h"
17
18 #ifdef __cplusplus
19 extern "C" {
20 #endif
21
22 int
23 coap_insert(coap_list_t **queue, coap_list_t *node,
24             int (*order)(void *, void *node) ) {
25   coap_list_t *p, *q;
26   if ( !queue || !node )
27     return 0;
28
29   /* set queue head if empty */
30   if ( !*queue ) {
31     *queue = node;
32     return 1;
33   }
34
35   /* replace queue head if new node has to be added before the existing queue head */
36   q = *queue;
37   if ( order( node->data, q->data ) < 0) {
38     node->next = q;
39     *queue = node;
40     return 1;
41   }
42
43   /* search for right place to insert */
44   do {
45     p = q;
46     q = q->next;
47   } while ( q && order( node->data, q->data ) >= 0);
48
49   /* insert new item */
50   node->next = q;
51   p->next = node;
52   return 1;
53 }
54
55 int
56 coap_delete(coap_list_t *node) {
57   if ( !node )
58     return 0;
59
60   if ( node->delete_func )
61     node->delete_func( node->data );
62   coap_free( node->data );
63   coap_free( node );
64
65   return 1;
66 }
67
68 void
69 coap_delete_list(coap_list_t *queue) {
70   if ( !queue )
71     return;
72
73   coap_delete_list( queue->next );
74   coap_delete( queue );
75 }
76
77 coap_list_t *
78 coap_new_listnode(void *data, void (*delete_func)(void *) ) {
79   coap_list_t *node = (coap_list_t*)coap_malloc( sizeof(coap_list_t) );
80   if ( ! node ) {
81 #ifndef NDEBUG
82     coap_log(LOG_CRIT, "coap_new_listnode: malloc\n");
83 #endif
84     return NULL;
85   }
86
87   memset(node, 0, sizeof(coap_list_t));
88   node->data = data;
89   node->delete_func = delete_func;
90   return node;
91 }
92
93 #ifdef __cplusplus
94 }
95 #endif
96