Statistics
| Branch: | Revision:

grapes / som / PeerSet / peerset_ops.c @ fb76785c

History | View | Annotate | Download (1.88 KB)

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

    
4
#include "peerset_private.h"
5
#include "peer.h"
6
#include "peerset.h"
7
#include "chunkidset.h"
8
#include "net_helper.h"
9

    
10
#define DEFAULT_SIZE_INCREMENT 32
11

    
12
struct nodeID;
13

    
14
struct peerset *peerset_init(int size)
15
{
16
  struct peerset *p;
17

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

    
30
  return p;
31
}
32

    
33
int peerset_add_peer(struct peerset *h, const struct nodeID *id)
34
{
35
  struct peer *e;
36
  if (peerset_check(h, 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(struct peer));
44
    if (res == NULL) {
45
      return -1;
46
    }
47
    h->size += DEFAULT_SIZE_INCREMENT;
48
    h->elements = (struct peer*) res;
49
  }
50
  e = &(h->elements[h->n_elements++]);
51
  e->id = nodeid_dup(id);
52
  e->bmap = chunkID_set_init(0);
53

    
54
  return h->n_elements;
55
}
56

    
57
void peerset_add_peers(struct peerset *h, const struct nodeID **ids, int n)
58
{
59
  int i;
60

    
61
  for (i = 0; i < n; i++) {
62
    peerset_add_peer(h,ids[i]);
63
  }
64
}
65

    
66
int peerset_size(const struct peerset *h)
67
{
68
  return h->n_elements;
69
}
70

    
71
struct peer* peerset_get_peers(const struct peerset *h)
72
{
73
  return h->elements;
74
}
75

    
76
struct peer *peerset_get_peer(const struct peerset *h, struct nodeID *id)
77
{
78
  int i = peerset_check(h,id);
79
  return (i<0) ? NULL : &(h->elements[i]);
80
}
81

    
82
int peerset_check(const struct peerset *h, const struct nodeID *id)
83
{
84
  int i;
85

    
86
  for (i = 0; i < h->n_elements; i++) {
87
    if (nodeid_equal(h->elements[i].id, id)) {
88
      return i;
89
    }
90
  }
91

    
92
  return -1;
93
}
94

    
95
void peerset_clear(struct peerset *h, int size)
96
{
97
  h->n_elements = 0;
98
  h->size = size;
99
  h->elements = realloc(h->elements, size * sizeof(struct peer));
100
  if (h->elements == NULL) {
101
    h->size = 0;
102
  }
103
}