Statistics
| Branch: | Revision:

grapes / som / PeerSet / peerset_ops.c @ 539f4a1a

History | View | Annotate | Download (2.19 KB)

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

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

    
11
#define DEFAULT_SIZE_INCREMENT 32
12

    
13
struct nodeID;
14

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

    
19
  p = malloc(sizeof(struct peerset));
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(struct peer));
27
  } else {
28
    p->elements = NULL;
29
  }
30

    
31
  return p;
32
}
33

    
34
int peerset_add_peer(struct peerset *h, const struct nodeID *id)
35
{
36
  struct peer *e;
37
  if (peerset_check(h, id) >= 0) {
38
    return 0;
39
  }
40

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

    
44
    res = realloc(h->elements, (h->size + DEFAULT_SIZE_INCREMENT) * sizeof(struct peer));
45
    if (res == NULL) {
46
      return -1;
47
    }
48
    h->size += DEFAULT_SIZE_INCREMENT;
49
    h->elements = (struct peer*) res;
50
  }
51
  e = &(h->elements[h->n_elements++]);
52
  e->id = nodeid_dup(id);
53
  e->bmap = chunkID_set_init(0);
54
  timerclear(&e->bmap_timestamp);
55

    
56
  return h->n_elements;
57
}
58

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

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

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

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

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

    
84
int peerset_remove_peer(struct peerset *h, const struct nodeID *id){
85
  int i = peerset_check(h,id);
86
  if (i >= 0) {
87
    memmove(&h->elements[i], &h->elements[i+1], ((h->n_elements--) - (i+1)) * sizeof(struct peer));
88
    return i;
89
  }
90
  return -1;
91
}
92

    
93
int peerset_check(const struct peerset *h, const struct nodeID *id)
94
{
95
  int i;
96

    
97
  for (i = 0; i < h->n_elements; i++) {
98
    if (nodeid_equal(h->elements[i].id, id)) {
99
      return i;
100
    }
101
  }
102

    
103
  return -1;
104
}
105

    
106
void peerset_clear(struct peerset *h, int size)
107
{
108
  h->n_elements = 0;
109
  h->size = size;
110
  h->elements = realloc(h->elements, size * sizeof(struct peer));
111
  if (h->elements == NULL) {
112
    h->size = 0;
113
  }
114
}