Statistics
| Branch: | Revision:

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

History | View | Annotate | Download (1.71 KB)

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

    
7
#include <arpa/inet.h>
8
#include <stdlib.h>
9
#include <string.h>
10
#include <stdint.h>
11

    
12
#include "chunkids_private.h"
13
#include "chunkidset.h"
14
#include "trade_sig_la.h"
15

    
16
static inline void int_cpy(uint8_t *p, int v)
17
{
18
  int tmp;
19
  
20
  tmp = htonl(v);
21
  memcpy(p, &tmp, 4);
22
}
23

    
24
static inline int int_rcpy(const uint8_t *p)
25
{
26
  int tmp;
27
  
28
  memcpy(&tmp, p, 4);
29
  tmp = ntohl(tmp);
30

    
31
  return tmp;
32
}
33

    
34
int encodeChunkSignaling(const struct chunkID_set *h, const void *meta, int meta_len, uint8_t *buff, int buff_len)
35
{
36
  int i;
37

    
38
  if (buff_len < h->n_elements * 4 + 12 + meta_len) {
39
    return -1;
40
  }
41
  int_cpy(buff, h->n_elements);
42
  int_cpy(buff + 4, 0);
43
  int_cpy(buff + 8, meta_len);
44
  
45
  for (i = 0; i < h->n_elements; i++) {
46
    int_cpy(buff + 12 + i * 4, h->elements[i]);
47
  }
48
  if (meta_len) {
49
    memcpy(buff + h->n_elements * 4 + 12, meta, meta_len);
50
  }
51

    
52
  return h->n_elements * 4 + 12 + meta_len;
53
}
54

    
55
struct chunkID_set *decodeChunkSignaling(void **meta, int *meta_len, const uint8_t *buff, int buff_len)
56
{
57
  int i, val, size;
58
  struct chunkID_set *h;
59

    
60
  size = int_rcpy(buff);
61
  val = int_rcpy(buff + 4);
62
  *meta_len = int_rcpy(buff + 8);
63
  if (buff_len != size * 4 + 12 + *meta_len) {
64
    return NULL;
65
  }
66
  h = chunkID_set_init(size);
67
  if (h == NULL) {
68
    return NULL;
69
  }
70
  if (val) {
71
    return h;        /* Not supported yet! */
72
  }
73

    
74
  for (i = 0; i < size; i++) {
75
    h->elements[i] = int_rcpy(buff + 12 + i * 4);
76
  }
77
  h->n_elements = size;
78

    
79
  if (*meta_len) {
80
    *meta = malloc(*meta_len);
81
    if (*meta != NULL) {
82
      memcpy(*meta, buff + 12 + size * 4, *meta_len);
83
    } else {
84
      *meta_len = 0;
85
    }
86
  } else {
87
    *meta = NULL;
88
  }
89

    
90
  return h;
91
}