Statistics
| Branch: | Revision:

grapes / som / ChunkTrading / chunk_encoding.c @ cb201402

History | View | Annotate | Download (1.73 KB)

1
#include <arpa/inet.h>
2
#include <stdlib.h>
3
#include <string.h>
4
#include <stdint.h>
5

    
6
#include "chunk.h"
7
#include "trade_msg_la.h"
8

    
9
static inline void int_cpy(uint8_t *p, int v)
10
{
11
  int tmp;
12
  
13
  tmp = htonl(v);
14
  memcpy(p, &tmp, 4);
15
}
16

    
17
static inline int int_rcpy(const uint8_t *p)
18
{
19
  int tmp;
20
  
21
  memcpy(&tmp, p, 4);
22
  tmp = ntohl(tmp);
23

    
24
  return tmp;
25
}
26

    
27
int encodeChunk(const struct chunk *c, uint8_t *buff, int buff_len)
28
{
29
  int64_t half_ts;
30

    
31
  if (buff_len < 20 + c->size + c->attributes_size) {
32
    /* Not enough space... */
33
    return -1;
34
  }
35

    
36
  int_cpy(buff, c->id);
37
  half_ts = c->timestamp >> 32;
38
  int_cpy(buff + 4, half_ts);
39
  half_ts = c->timestamp;
40
  int_cpy(buff + 8, half_ts);
41
  int_cpy(buff + 12, c->size);
42
  int_cpy(buff + 16, c->attributes_size);
43
  memcpy(buff + 20, c->data, c->size);
44
  if (c->attributes_size) {
45
    memcpy(buff + 20 + c->size, c->attributes, c->attributes_size);
46
  }
47

    
48
  return 20 + c->size + c->attributes_size;
49
}
50

    
51
int decodeChunk(struct chunk *c, const uint8_t *buff, int buff_len)
52
{
53
  if (buff_len < 20) {
54
    return -1;
55
  }
56
  c->id = int_rcpy(buff);
57
  c->timestamp = int_rcpy(buff + 4);
58
  c->timestamp = c->timestamp << 32;
59
  c->timestamp |= int_rcpy(buff + 8); 
60
  c->size = int_rcpy(buff + 12);
61
  c->attributes_size = int_rcpy(buff + 16);
62

    
63
  if (buff_len < c->size + 20) {
64
    return -2;
65
  }
66
  c->data = malloc(c->size);
67
  if (c->data == NULL) {
68
    return -3;
69
  }
70
  memcpy(c->data, buff + 20, c->size);
71

    
72
  if (c->attributes_size > 0) {
73
    if (buff_len < c->size + c->attributes_size) {
74
      return -4;
75
    }
76
    c->attributes = malloc(c->attributes_size);
77
    if (c->attributes == NULL) {
78
      return -5;
79
    }
80
    memcpy(c->attributes, buff + 20 + c->size, c->attributes_size);
81
  }
82

    
83
  return 20 + c->size + c->attributes_size;
84
}