Contiki 3.x
buffer.c
1 /*
2  * buffer.c
3  *
4  * Created on: Oct 19, 2010
5  * Author: dogan
6  */
7 
8 #include <stdlib.h>
9 #include <string.h>
10 #include <stdint.h>
11 #include "buffer.h"
12 
13 uint8_t* data_buffer;
14 uint16_t buffer_size;
15 uint16_t buffer_index;
16 
17 void
18 delete_buffer(void)
19 {
20  if (data_buffer) {
21  free(data_buffer);
22  data_buffer = NULL;
23  buffer_index = 0;
24  buffer_size = 0;
25  }
26 }
27 
28 uint8_t*
29 init_buffer(uint16_t size)
30 {
31  delete_buffer();
32  data_buffer = (uint8_t*)malloc(size);
33  if (data_buffer) {
34  buffer_size = size;
35  }
36  buffer_index = 0;
37 
38  return data_buffer;
39 }
40 
41 uint8_t*
42 allocate_buffer(uint16_t size)
43 {
44  uint8_t* buffer = NULL;
45  int rem = 0;
46  /*To get rid of alignment problems, always allocate even size*/
47  rem = size % 4;
48  if (rem) {
49  size+=(4-rem);
50  }
51  if (buffer_index + size < buffer_size) {
52  buffer = data_buffer + buffer_index;
53  buffer_index += size;
54  }
55 
56  return buffer;
57 }
58 
59 uint8_t*
60 copy_to_buffer(void* data, uint16_t len)
61 {
62  uint8_t* buffer = allocate_buffer(len);
63  if (buffer) {
64  memcpy(buffer, data, len);
65  }
66 
67  return buffer;
68 }
69 
70 uint8_t*
71 copy_text_to_buffer(char* text)
72 {
73  uint8_t* buffer = allocate_buffer(strlen(text) + 1);
74  if (buffer) {
75  strcpy(buffer, text);
76  }
77 
78  return buffer;
79 }
#define NULL
The null pointer.