]> git.stg.codes - stg.git/blob - stglibs/smux.lib/asn_SET_OF.c
Produce debug output only if SMUX_DEBUG is defined
[stg.git] / stglibs / smux.lib / asn_SET_OF.c
1 /*-
2  * Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
3  * Redistribution and modifications are permitted subject to BSD license.
4  */
5 #include <asn_internal.h>
6 #include <asn_SET_OF.h>
7 #include <errno.h>
8
9 /*
10  * Add another element into the set.
11  */
12 int
13 asn_set_add(void *asn_set_of_x, void *ptr) {
14         asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
15
16         if(as == 0 || ptr == 0) {
17                 errno = EINVAL;         /* Invalid arguments */
18                 return -1;
19         }
20
21         /*
22          * Make sure there's enough space to insert an element.
23          */
24         if(as->count == as->size) {
25                 int _newsize = as->size ? (as->size << 1) : 4;
26                 void *_new_arr;
27                 _new_arr = REALLOC(as->array, _newsize * sizeof(as->array[0]));
28                 if(_new_arr) {
29                         as->array = (void **)_new_arr;
30                         as->size = _newsize;
31                 } else {
32                         /* ENOMEM */
33                         return -1;
34                 }
35         }
36
37         as->array[as->count++] = ptr;
38
39         return 0;
40 }
41
42 void
43 asn_set_del(void *asn_set_of_x, int number, int _do_free) {
44         asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
45
46         if(as) {
47                 void *ptr;
48                 if(number < 0 || number >= as->count)
49                         return;
50
51                 if(_do_free && as->free) {
52                         ptr = as->array[number];
53                 } else {
54                         ptr = 0;
55                 }
56
57                 as->array[number] = as->array[--as->count];
58
59                 /*
60                  * Invoke the third-party function only when the state
61                  * of the parent structure is consistent.
62                  */
63                 if(ptr) as->free(ptr);
64         }
65 }
66
67 /*
68  * Free the contents of the set, do not free the set itself.
69  */
70 void
71 asn_set_empty(void *asn_set_of_x) {
72         asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
73
74         if(as) {
75                 if(as->array) {
76                         if(as->free) {
77                                 while(as->count--)
78                                         as->free(as->array[as->count]);
79                         }
80                         FREEMEM(as->array);
81                         as->array = 0;
82                 }
83                 as->count = 0;
84                 as->size = 0;
85         }
86
87 }
88