Statistics
| Branch: | Revision:

grapes / som / ChunkTrading / chunk_encoding.c @ 8ab58ec7

History | View | Annotate | Download (1.87 KB)

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

    
9
#include <arpa/inet.h>
10
#include <stdlib.h>
11
#include <string.h>
12
#include <stdint.h>
13

    
14
#include "chunk.h"
15
#include "trade_msg_la.h"
16

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

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

    
32
  return tmp;
33
}
34

    
35
int encodeChunk(const struct chunk *c, uint8_t *buff, int buff_len)
36
{
37
  int64_t half_ts;
38

    
39
  if (buff_len < 20 + c->size + c->attributes_size) {
40
    /* Not enough space... */
41
    return -1;
42
  }
43

    
44
  int_cpy(buff, c->id);
45
  half_ts = c->timestamp >> 32;
46
  int_cpy(buff + 4, half_ts);
47
  half_ts = c->timestamp;
48
  int_cpy(buff + 8, half_ts);
49
  int_cpy(buff + 12, c->size);
50
  int_cpy(buff + 16, c->attributes_size);
51
  memcpy(buff + 20, c->data, c->size);
52
  if (c->attributes_size) {
53
    memcpy(buff + 20 + c->size, c->attributes, c->attributes_size);
54
  }
55

    
56
  return 20 + c->size + c->attributes_size;
57
}
58

    
59
int decodeChunk(struct chunk *c, const uint8_t *buff, int buff_len)
60
{
61
  if (buff_len < 20) {
62
    return -1;
63
  }
64
  c->id = int_rcpy(buff);
65
  c->timestamp = int_rcpy(buff + 4);
66
  c->timestamp = c->timestamp << 32;
67
  c->timestamp |= int_rcpy(buff + 8); 
68
  c->size = int_rcpy(buff + 12);
69
  c->attributes_size = int_rcpy(buff + 16);
70

    
71
  if (buff_len < c->size + 20) {
72
    return -2;
73
  }
74
  c->data = malloc(c->size);
75
  if (c->data == NULL) {
76
    return -3;
77
  }
78
  memcpy(c->data, buff + 20, c->size);
79

    
80
  if (c->attributes_size > 0) {
81
    if (buff_len < c->size + c->attributes_size) {
82
      return -4;
83
    }
84
    c->attributes = malloc(c->attributes_size);
85
    if (c->attributes == NULL) {
86
      return -5;
87
    }
88
    memcpy(c->attributes, buff + 20 + c->size, c->attributes_size);
89
  }
90

    
91
  return 20 + c->size + c->attributes_size;
92
}