1
+ #include " Buffer.h"
2
+
3
+ Buffer::Buffer (int data)
4
+ {
5
+ uint8_t * buffer = BufferConverter::intToBuffer (data);
6
+ this ->length = 2 ;
7
+ this ->type = INT;
8
+ this ->packetStack = new Stack<Packet *>(1 );
9
+ this ->packetStack ->add (new Packet (buffer, this ->length ));
10
+ delete buffer;
11
+ }
12
+
13
+ Buffer::Buffer (unsigned long data)
14
+ {
15
+ uint8_t * buffer = BufferConverter::longToBuffer (data);
16
+ this ->length = 4 ;
17
+ this ->type = LONG;
18
+ this ->packetStack = new Stack<Packet*>(1 );
19
+ this ->packetStack ->add (new Packet (buffer, this ->length ));
20
+ delete buffer;
21
+ }
22
+
23
+ Buffer::Buffer (char *data)
24
+ {
25
+ this ->length = strlen (data);
26
+ this ->init ((uint8_t *)data);
27
+ this ->type = STRING;
28
+ }
29
+
30
+ Buffer::Buffer (uint8_t *data, int size)
31
+ {
32
+ this ->length = size;
33
+ this ->init (data);
34
+ this ->type = BUFFER;
35
+ }
36
+
37
+ Buffer::Buffer (Buffer * input){
38
+ this ->length = input->size ();
39
+ this ->packetStack = input->packetStack ;
40
+ this ->type = BUFFER;
41
+ }
42
+ Buffer::Buffer (Packet * data){
43
+ this ->length = data->size ;
44
+ this ->init (data->data );
45
+ this ->type = BUFFER;
46
+ }
47
+
48
+
49
+ Buffer::~Buffer ()
50
+ {
51
+ delete this ->packetStack ;
52
+ }
53
+
54
+ void Buffer::init (uint8_t *data)
55
+ {
56
+ this ->makePacketStack (data);
57
+ }
58
+
59
+ void Buffer::makePacketStack (uint8_t * data)
60
+ {
61
+ int numPackets = ceil (this ->length / MAX_PACKET_SIZE);
62
+ this ->packetStack = new Stack<Packet *>(numPackets);
63
+ int byteCount = 0 ;
64
+ for (int i = 0 ; i < numPackets; i++)
65
+ {
66
+ int remaining = this ->length - byteCount;
67
+ int nextPackSize = (remaining > MAX_PACKET_SIZE) ? MAX_PACKET_SIZE : remaining;
68
+ uint8_t buf[nextPackSize];
69
+ for (int j = 0 ; j < nextPackSize; j++)
70
+ {
71
+ buf[j] = data[byteCount];
72
+ byteCount++;
73
+ }
74
+ this ->packetStack ->add (new Packet (buf, nextPackSize));
75
+ }
76
+ }
77
+
78
+ char * Buffer::toString ()
79
+ {
80
+ char * str = (char *) malloc (this ->length +1 );
81
+ int byteCount = 0 ;
82
+ int numPackets = ceil (this ->length / MAX_PACKET_SIZE);
83
+ for (int i = 0 ; i < numPackets; i++)
84
+ {
85
+ Packet *incoming = this ->packetStack ->get (i);
86
+ int remaining = this ->length - byteCount;
87
+ int nextPackSize = (remaining > MAX_PACKET_SIZE) ? MAX_PACKET_SIZE : remaining;
88
+ for (int j = 0 ; j < nextPackSize; j++)
89
+ {
90
+ str[byteCount] = (char ) incoming->data [j];
91
+ byteCount++;
92
+ }
93
+ }
94
+ str[byteCount] = ' \0 ' ;
95
+ return str;
96
+ }
97
+
98
+ int Buffer::toInt (){
99
+ return BufferConverter::bufferToInt (this ->packetStack ->get (0 )->data );
100
+ }
101
+
102
+ unsigned long Buffer::toLong (){
103
+ return BufferConverter::bufferToLong (this ->packetStack ->get (0 )->data );
104
+ }
105
+
106
+ int Buffer::size (){
107
+ return this ->length ;
108
+ }
0 commit comments