blob: 944f2cb8ad70a166e65dbb3536ef62fc34a8e74c [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_SET_OF.h>
7#include <errno.h>
8
Lev Walkinf15320b2004-06-03 03:38:44 +00009/*
10 * Add another element into the set.
11 */
12int
13asn_set_add(void *asn_set_of_x, void *ptr) {
Lev Walkin7e033b52005-07-02 08:19:17 +000014 asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
Lev Walkinf15320b2004-06-03 03:38:44 +000015
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) {
Lev Walkinc2346572004-08-11 09:07:36 +000029 as->array = (void **)_new_arr;
Lev Walkinf15320b2004-06-03 03:38:44 +000030 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
42void
43asn_set_del(void *asn_set_of_x, int number, int _do_free) {
Lev Walkin7e033b52005-07-02 08:19:17 +000044 asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
Lev Walkinf15320b2004-06-03 03:38:44 +000045
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 */
70void
71asn_set_empty(void *asn_set_of_x) {
Lev Walkin7e033b52005-07-02 08:19:17 +000072 asn_anonymous_set_ *as = _A_SET_FROM_VOID(asn_set_of_x);
Lev Walkinf15320b2004-06-03 03:38:44 +000073
74 if(as) {
75 if(as->array) {
76 if(as->free) {
77 while(as->count--)
78 as->free(as->array[as->count]);
79 }
Lev Walkin419f6752006-09-13 04:02:00 +000080 FREEMEM(as->array);
Lev Walkin1473c6d2004-07-22 12:17:10 +000081 as->array = 0;
Lev Walkinf15320b2004-06-03 03:38:44 +000082 }
83 as->count = 0;
84 as->size = 0;
85 }
86
87}
88