Imported Upstream version 0.9.1
[platform/upstream/iotivity.git] / resource / csdk / connectivity / lib / 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 int coap_insert(coap_list_t **queue, coap_list_t *node, int (*order)(void *, void *node))
19 {
20     coap_list_t *p, *q;
21     if (!queue || !node)
22         return 0;
23
24     /* set queue head if empty */
25     if (!*queue)
26     {
27         *queue = node;
28         return 1;
29     }
30
31     /* replace queue head if new node has to be added before the existing queue head */
32     q = *queue;
33     if (order(node->data, q->data) < 0)
34     {
35         node->next = q;
36         *queue = node;
37         return 1;
38     }
39
40     /* search for right place to insert */
41     do
42     {
43         p = q;
44         q = q->next;
45     } while (q && order(node->data, q->data) >= 0);
46
47     /* insert new item */
48     node->next = q;
49     p->next = node;
50     return 1;
51 }
52
53 int coap_delete(coap_list_t *node)
54 {
55     if (!node)
56         return 0;
57
58     if (node->delete_func)
59         node->delete_func(node->data);
60     coap_free( node->data);
61     coap_free( node);
62
63     return 1;
64 }
65
66 void coap_delete_list(coap_list_t *queue)
67 {
68     if (!queue)
69         return;
70
71     coap_delete_list(queue->next);
72     coap_delete(queue);
73 }
74
75 coap_list_t *
76 coap_new_listnode(void *data, void (*delete_func)(void *))
77 {
78     coap_list_t *node = (coap_list_t *) coap_malloc( sizeof(coap_list_t) );
79     if (!node)
80     {
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