Statistics
| Branch: | Revision:

grapes / som / PeerSet / peerset_ops.c @ a4f059a8

History | View | Annotate | Download (1.79 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 "net_helper.h"
8

    
9
#define DEFAULT_SIZE_INCREMENT 32
10

    
11
struct nodeID;
12

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

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

    
29
  return p;
30
}
31

    
32
int peerset_add_peer(struct peerset *h, const struct nodeID *id)
33
{
34
  if (peerset_check(h, id) >= 0) {
35
    return 0;
36
  }
37

    
38
  if (h->n_elements == h->size) {
39
    int *res;
40

    
41
    res = realloc(h->elements, (h->size + DEFAULT_SIZE_INCREMENT) * sizeof(struct peer));
42
    if (res == NULL) {
43
      return -1;
44
    }
45
    h->size += DEFAULT_SIZE_INCREMENT;
46
    h->elements = (struct peer*) res;
47
  }
48
  h->elements[h->n_elements++].id = id;
49

    
50
  return h->n_elements;
51
}
52

    
53
void peerset_add_peers(struct peerset *h, const struct nodeID **ids, int n)
54
{
55
  int i;
56

    
57
  for (i = 0; i < n; i++) {
58
    peerset_add_peer(h,ids[i]);
59
  }
60
}
61

    
62
int peerset_size(const struct peerset *h)
63
{
64
  return h->n_elements;
65
}
66

    
67
struct peer* peerset_get_peers(const struct peerset *h)
68
{
69
  return h->elements;
70
}
71

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

    
78
int peerset_check(const struct peerset *h, const struct nodeID *id)
79
{
80
  int i;
81

    
82
  for (i = 0; i < h->n_elements; i++) {
83
    if (nodeid_equal(h->elements[i].id, id)) {
84
      return i;
85
    }
86
  }
87

    
88
  return -1;
89
}
90

    
91
void peerset_clear(struct peerset *h, int size)
92
{
93
  h->n_elements = 0;
94
  h->size = size;
95
  h->elements = realloc(h->elements, size * sizeof(struct peer));
96
  if (h->elements == NULL) {
97
    h->size = 0;
98
  }
99
}