forked from argandas/ardubson
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ardubsonDocument.cpp
106 lines (94 loc) · 2.18 KB
/
ardubsonDocument.cpp
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
98
99
100
101
102
103
104
105
106
/*
ardubson.h - Library for the BSON (Binary-JSON) format.
Created by Hugo Arganda (argandas), April 6, 2016.
Released into the public domain.
*/
#include "ardubsonDocument.h"
#include "ardubsonTypes.h"
#include "ardubsonConfig.h"
// Private Methods //////////////////////////////////////////////////////////////
char* BSONDocument::index(void)
{
return (char *) _doc + _idx;
}
void BSONDocument::reset(void)
{
memset(&_doc, BSON_NULL_BYTE, BSON_DOC_SIZE);
_done = false;
_idx = 4;
return;
}
uint8_t BSONDocument::appendNum(char value)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + sizeof(char)))
{
*(char *) index() = value;
_idx += sizeof(char);
ret = true;
}
return ret;
}
uint8_t BSONDocument::appendBSONElement(BSONElement element)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + element.len()))
{
memcpy(index(), element.rawData(), element.len());
_idx += element.len();
ret = true;
}
return ret;
}
uint8_t BSONDocument::appendNum(uint32_t value)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + sizeof(uint32_t)))
{
*(uint32_t *) index() = value;
_idx += sizeof(uint32_t);
ret = true;
}
return ret;
}
uint8_t BSONDocument::appendNum(int32_t value)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + sizeof(int32_t)))
{
*(int32_t *) index() = value;
_idx += sizeof(int32_t);
ret = true;
}
return ret;
}
uint8_t BSONDocument::appendNum(int64_t value)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + sizeof(int64_t)))
{
*(int64_t *) index() = value;
_idx += sizeof(int64_t);
ret = true;
}
return ret;
}
uint8_t BSONDocument::appendStr(const char *data)
{
uint8_t ret = false;
if (BSON_DOC_SIZE > (_idx + strlen(data) + 1))
{
ret = true;
for (; (*data != BSON_NULL_BYTE) && (ret); data++)
{
/* Append chars */
ret &= appendNum((char) *data);
}
if (ret)
{
/* Add NULL terminator */
ret &= appendNum((char) BSON_NULL_BYTE);
}
}
return ret;
}