Statistics
| Branch: | Revision:

grapes / som / ChunkIDSet / chunkids_ops.c @ 8ab58ec7

History | View | Annotate | Download (1.79 KB)

1
/*
2
 *  Copyright (c) 2010 Luca Abeni
3
 *
4
 *  This is free software; see lgpl-2.1.txt
5
 */
6

    
7
#include <stdlib.h>
8
#include <stdint.h>
9

    
10
#include "chunkids_private.h"
11
#include "chunkidset.h"
12

    
13
#define DEFAULT_SIZE_INCREMENT 32
14

    
15
struct chunkID_set *chunkID_set_init(int size)
16
{
17
  struct chunkID_set *p;
18

    
19
  p = malloc(sizeof(struct chunkID_set));
20
  if (p == NULL) {
21
    return NULL;
22
  }
23
  p->n_elements = 0;
24
  p->size = size;
25
  if (p->size) {
26
    p->elements = malloc(p->size * sizeof(int));
27
  } else {
28
    p->elements = NULL;
29
  }
30

    
31
  return p;
32
}
33

    
34
int chunkID_set_add_chunk(struct chunkID_set *h, int chunk_id)
35
{
36
  if (chunkID_set_check(h, chunk_id) >= 0) {
37
    return 0;
38
  }
39

    
40
  if (h->n_elements == h->size) {
41
    int *res;
42

    
43
    res = realloc(h->elements, (h->size + DEFAULT_SIZE_INCREMENT) * sizeof(int));
44
    if (res == NULL) {
45
      return -1;
46
    }
47
    h->size += DEFAULT_SIZE_INCREMENT;
48
    h->elements = res;
49
  }
50
  h->elements[h->n_elements++] = chunk_id;
51

    
52
  return h->n_elements;
53
}
54

    
55
int chunkID_set_size(const struct chunkID_set *h)
56
{
57
  return h->n_elements;
58
}
59

    
60
int chunkID_set_get_chunk(const struct chunkID_set *h, int i)
61
{
62
  if (i < h->n_elements) {
63
    return h->elements[i];
64
  }
65

    
66
  return -1;
67
}
68

    
69
int chunkID_set_check(const struct chunkID_set *h, int chunk_id)
70
{
71
  int i;
72

    
73
  for (i = 0; i < h->n_elements; i++) {
74
    if (h->elements[i] == chunk_id) {
75
      return i;
76
    }
77
  }
78

    
79
  return -1;
80
}
81

    
82
int chunkID_set_union(struct chunkID_set *h, struct chunkID_set *a)
83
{
84
  int i;
85

    
86
  for (i = 0; i < a->n_elements; i++) {
87
    int ret = chunkID_set_add_chunk(h,a->elements[i]);
88
    if (ret < 0) return ret;
89
  }
90
  return h->n_elements;
91
}
92

    
93
void chunkID_set_clear(struct chunkID_set *h, int size)
94
{
95
  h->n_elements = 0;
96
  h->size = size;
97
  h->elements = realloc(h->elements, size * sizeof(int));
98
  if (h->elements == NULL) {
99
    h->size = 0;
100
  }
101
}