blob: 7aeafddb19a62358650ade5f0fc65c7e074b1560 [file] [log] [blame]
Lev Walkinf15320b2004-06-03 03:38:44 +00001/*-
2 * Copyright (c) 2003, 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
3 * Redistribution and modifications are permitted subject to BSD license.
4 */
Lev Walkina9cc46e2004-09-22 16:06:28 +00005#include <asn_internal.h>
Lev Walkinf15320b2004-06-03 03:38:44 +00006#include <asn_types.h> /* for MALLOC/REALLOC/FREEMEM */
7#include <asn_SET_OF.h>
8#include <errno.h>
9
10typedef A_SET_OF(void) asn_set;
11
12/*
13 * Add another element into the set.
14 */
15int
16asn_set_add(void *asn_set_of_x, void *ptr) {
Lev Walkinc2346572004-08-11 09:07:36 +000017 asn_set *as = (asn_set *)asn_set_of_x;
Lev Walkinf15320b2004-06-03 03:38:44 +000018
19 if(as == 0 || ptr == 0) {
20 errno = EINVAL; /* Invalid arguments */
21 return -1;
22 }
23
24 /*
25 * Make sure there's enough space to insert an element.
26 */
27 if(as->count == as->size) {
28 int _newsize = as->size ? (as->size << 1) : 4;
29 void *_new_arr;
30 _new_arr = REALLOC(as->array, _newsize * sizeof(as->array[0]));
31 if(_new_arr) {
Lev Walkinc2346572004-08-11 09:07:36 +000032 as->array = (void **)_new_arr;
Lev Walkinf15320b2004-06-03 03:38:44 +000033 as->size = _newsize;
34 } else {
35 /* ENOMEM */
36 return -1;
37 }
38 }
39
40 as->array[as->count++] = ptr;
41
42 return 0;
43}
44
45void
46asn_set_del(void *asn_set_of_x, int number, int _do_free) {
Lev Walkinc2346572004-08-11 09:07:36 +000047 asn_set *as = (asn_set *)asn_set_of_x;
Lev Walkinf15320b2004-06-03 03:38:44 +000048
49 if(as) {
50 void *ptr;
51 if(number < 0 || number >= as->count)
52 return;
53
54 if(_do_free && as->free) {
55 ptr = as->array[number];
56 } else {
57 ptr = 0;
58 }
59
60 as->array[number] = as->array[--as->count];
61
62 /*
63 * Invoke the third-party function only when the state
64 * of the parent structure is consistent.
65 */
66 if(ptr) as->free(ptr);
67 }
68}
69
70/*
71 * Free the contents of the set, do not free the set itself.
72 */
73void
74asn_set_empty(void *asn_set_of_x) {
Lev Walkinc2346572004-08-11 09:07:36 +000075 asn_set *as = (asn_set *)asn_set_of_x;
Lev Walkinf15320b2004-06-03 03:38:44 +000076
77 if(as) {
78 if(as->array) {
79 if(as->free) {
80 while(as->count--)
81 as->free(as->array[as->count]);
82 }
83 free(as->array);
Lev Walkin1473c6d2004-07-22 12:17:10 +000084 as->array = 0;
Lev Walkinf15320b2004-06-03 03:38:44 +000085 }
86 as->count = 0;
87 as->size = 0;
88 }
89
90}
91