Statistics
| Branch: | Revision:

grapes / src / ChunkTrading / chunk_encoding.c @ 729826c9

History | View | Annotate | Download (1.78 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 <stdlib.h>
10
#include <string.h>
11
#include <stdint.h>
12

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

    
17

    
18
int encodeChunk(const struct chunk *c, uint8_t *buff, int buff_len)
19
{
20
  uint32_t half_ts;
21

    
22
  if (buff_len < CHUNK_HEADER_SIZE + c->size + c->attributes_size) {
23
    /* Not enough space... */
24
    return -1;
25
  }
26

    
27
  int_cpy(buff, c->id);
28
  half_ts = c->timestamp >> 32;
29
  int_cpy(buff + 4, half_ts);
30
  half_ts = c->timestamp;
31
  int_cpy(buff + 8, half_ts);
32
  int_cpy(buff + 12, c->size);
33
  int_cpy(buff + 16, c->attributes_size);
34
  memcpy(buff + CHUNK_HEADER_SIZE, c->data, c->size);
35
  if (c->attributes_size) {
36
    memcpy(buff + CHUNK_HEADER_SIZE + c->size, c->attributes, c->attributes_size);
37
  }
38

    
39
  return CHUNK_HEADER_SIZE + c->size + c->attributes_size;
40
}
41

    
42
int decodeChunk(struct chunk *c, const uint8_t *buff, int buff_len)
43
{
44
  if (buff_len < CHUNK_HEADER_SIZE) {
45
    return -1;
46
  }
47
  c->id = int_rcpy(buff);
48
  c->timestamp = int_rcpy(buff + 4);
49
  c->timestamp = c->timestamp << 32;
50
  c->timestamp |= int_rcpy(buff + 8); 
51
  c->size = int_rcpy(buff + 12);
52
  c->attributes_size = int_rcpy(buff + 16);
53

    
54
  if (buff_len < c->size + CHUNK_HEADER_SIZE) {
55
    return -2;
56
  }
57
  c->data = malloc(c->size);
58
  if (c->data == NULL) {
59
    return -3;
60
  }
61
  memcpy(c->data, buff + CHUNK_HEADER_SIZE, c->size);
62

    
63
  if (c->attributes_size > 0) {
64
    if (buff_len < c->size + c->attributes_size) {
65
      return -4;
66
    }
67
    c->attributes = malloc(c->attributes_size);
68
    if (c->attributes == NULL) {
69
      return -5;
70
    }
71
    memcpy(c->attributes, buff + CHUNK_HEADER_SIZE + c->size, c->attributes_size);
72
  }
73

    
74
  return CHUNK_HEADER_SIZE + c->size + c->attributes_size;
75
}