Statistics
| Branch: | Revision:

grapes / som / ChunkIDSet / chunkids_ops.c @ f3480090

History | View | Annotate | Download (1.71 KB)

1
#include <stdlib.h>
2
#include <stdint.h>
3

    
4
#include "chunkids_private.h"
5
#include "chunkidset.h"
6

    
7
#define DEFAULT_SIZE_INCREMENT 32
8

    
9
struct chunkID_set *chunkID_set_init(int size)
10
{
11
  struct chunkID_set *p;
12

    
13
  p = malloc(sizeof(struct chunkID_set));
14
  if (p == NULL) {
15
    return NULL;
16
  }
17
  p->n_elements = 0;
18
  p->size = size;
19
  if (p->size) {
20
    p->elements = malloc(p->size * sizeof(int));
21
  } else {
22
    p->elements = NULL;
23
  }
24

    
25
  return p;
26
}
27

    
28
int chunkID_set_add_chunk(struct chunkID_set *h, int chunk_id)
29
{
30
  if (chunkID_set_check(h, chunk_id) >= 0) {
31
    return 0;
32
  }
33

    
34
  if (h->n_elements == h->size) {
35
    int *res;
36

    
37
    res = realloc(h->elements, (h->size + DEFAULT_SIZE_INCREMENT) * sizeof(int));
38
    if (res == NULL) {
39
      return -1;
40
    }
41
    h->size += DEFAULT_SIZE_INCREMENT;
42
    h->elements = res;
43
  }
44
  h->elements[h->n_elements++] = chunk_id;
45

    
46
  return h->n_elements;
47
}
48

    
49
int chunkID_set_size(const struct chunkID_set *h)
50
{
51
  return h->n_elements;
52
}
53

    
54
int chunkID_set_get_chunk(const struct chunkID_set *h, int i)
55
{
56
  if (i < h->n_elements) {
57
    return h->elements[i];
58
  }
59

    
60
  return -1;
61
}
62

    
63
int chunkID_set_check(const struct chunkID_set *h, int chunk_id)
64
{
65
  int i;
66

    
67
  for (i = 0; i < h->n_elements; i++) {
68
    if (h->elements[i] == chunk_id) {
69
      return i;
70
    }
71
  }
72

    
73
  return -1;
74
}
75

    
76
int chunkID_set_union(struct chunkID_set *h, struct chunkID_set *a)
77
{
78
  int i;
79

    
80
  for (i = 0; i < a->n_elements; i++) {
81
    int ret = chunkID_set_add_chunk(h,a->elements[i]);
82
    if (ret < 0) return ret;
83
  }
84
  return h->n_elements;
85
}
86

    
87
void chunkID_set_clear(struct chunkID_set *h, int size)
88
{
89
  h->n_elements = 0;
90
  h->size = size;
91
  h->elements = realloc(h->elements, size * sizeof(int));
92
  if (h->elements == NULL) {
93
    h->size = 0;
94
  }
95
}