-
Notifications
You must be signed in to change notification settings - Fork 0
/
StructureToFromBuffer.c
97 lines (82 loc) · 2.71 KB
/
StructureToFromBuffer.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <stdint.h>
#include <string.h> // for memcpy()
#include "StructureToFromBuffer.h"
/*---------------------------------------------------------------------------*/
// Structure to Buffer
/*---------------------------------------------------------------------------*/
int StructureToBuffer (void *bufferPtr, unsigned int bufferSize,
void *structurePtr, ElementOffsetStruct *elementOffsetTablePtr)
{
int dataSize = 0;
unsigned int offset = 0;
if ((bufferPtr == NULL) || (bufferSize == 0))
{
// No destination buffer.
dataSize = NO_INPUT_BUFFER;
}
else if ((structurePtr == NULL) || (elementOffsetTablePtr == NULL))
{
// No payload structure.
dataSize = NO_PAYLOAD_STRUCTURE;
}
else
{
offset = 0;
for (int idx = 0; elementOffsetTablePtr[idx].size != 0; idx++)
{
if ((offset + elementOffsetTablePtr[idx].size) > bufferSize)
{
// Not enough room in output buffer.
dataSize = NO_ROOM_IN_OUTPUT_BUFFER;
break;
}
// Copy bytes from structure element to output buffer.
memcpy(((uint8_t*)bufferPtr + offset),
((uint8_t*)structurePtr + elementOffsetTablePtr[idx].offset),
elementOffsetTablePtr[idx].size);
offset += elementOffsetTablePtr[idx].size;
}
dataSize = offset;
}
return dataSize;
}
/*---------------------------------------------------------------------------*/
// Buffer to Structure
/*---------------------------------------------------------------------------*/
int BufferToStructure (void *bufferPtr, unsigned int bufferSize,
void *structurePtr, ElementOffsetStruct *elementOffsetTablePtr)
{
int dataSize = 0;
unsigned int offset = 0;
if ((bufferPtr == NULL) || (bufferSize == 0))
{
// No input buffer.
dataSize = NO_INPUT_BUFFER;
}
else if ((structurePtr == NULL) || (elementOffsetTablePtr == NULL))
{
// No payload structure.
dataSize = NO_PAYLOAD_STRUCTURE;
}
else
{
offset = 0;
for (int idx = 0; elementOffsetTablePtr[idx].size != 0; idx++)
{
if ((offset + elementOffsetTablePtr[idx].size) > bufferSize)
{
// Not enough room in input buffer.
dataSize = NO_ROOM_IN_INPUT_BUFFER;
break;
}
// Copy bytes from input buffer to structure element.
memcpy (((uint8_t*)structurePtr + elementOffsetTablePtr[idx].offset),
(bufferPtr + offset),
elementOffsetTablePtr[idx].size);
offset += elementOffsetTablePtr[idx].size;
}
dataSize = offset;
}
return dataSize;
}
// End of StructureToBuffer.c