Statistics
| Branch: | Revision:

grapes / src / ChunkTrading / chunk_encoding.c @ 2050b9b0

History | View | Annotate | Download (1.81 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
#define CHUNK_HEADER_SIZE 20
18

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

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

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

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

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

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

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

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