-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjsonreader.cpp
More file actions
122 lines (102 loc) · 2.51 KB
/
jsonreader.cpp
File metadata and controls
122 lines (102 loc) · 2.51 KB
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
// Copyright 2013 MakerBot Industries
#include <string>
#include "cpp/jsonrpcprivate.h"
#include "cpp/jsonreader.h"
#include "jsonrpc/jsonrpc.h"
JsonReader::JsonReader(JsonRpcPrivate & jsonRpcPrivate)
: m_jsonRpcPrivate(jsonRpcPrivate)
, m_state(S0) {
}
void JsonReader::reset() {
m_state = S0;
m_buffer.str(std::string());
while (!m_stack.empty()) {
m_stack.pop();
}
}
void JsonReader::send() {
std::string const jsonText(m_buffer.str());
reset();
if (jsonText.empty())
return;
if(jsonText.size() == 1){
if( jsonText.find(" ") == 0
|| jsonText.find("\t") == 0
|| jsonText.find("\n") == 0
|| jsonText.find("\r") == 0
)
return;
}
if(jsonText.size() == 2 && jsonText.find("\r\n") == 0 )
return;
m_jsonRpcPrivate.jsonReaderCallback(jsonText);
}
void JsonReader::setDelimiter(char ch){
m_packetDelimiter = ch;
}
bool JsonReader::transition(char const ch) {
switch (m_state) {
case S0:
if ('{' == ch || '[' == ch) {
m_state = S1;
m_stack.push(ch);
} else if (' ' == ch || '\t' == ch || '\n' == ch || '\r' == ch) {
return true;
}
break;
case S1:
if ('\"' == ch) {
m_state = S2;
} else if ('{' == ch || '[' == ch) {
m_stack.push(ch);
} else if ('}' == ch || ']' == ch) {
bool send(false);
if (m_stack.empty()) {
send = true;
} else {
char const firstch(m_stack.top());
m_stack.pop();
if (('{' == firstch && '}' != ch)
||('[' == firstch && ']' != ch)) {
send = true;
} else {
send = m_stack.empty();
}
}
return send;
}
break;
case S2:
if ('\"' == ch) {
m_state = S1;
} else if ('\\' == ch) {
m_state = S3;
}
break;
case S3:
m_state = S2;
break;
}
return false;
}
void JsonReader::feed(char ch) {
m_buffer << ch;
if(transition(ch))
send();
else if(m_packetDelimiter == ch) //use delimiter as sync sequence. we assume that json is passed as minified string
return send();
}
void JsonReader::feed(char const * const buffer, std::size_t const length) {
for (std::size_t i(static_cast <std::size_t>(0u)); i < length; ++i) {
char const ch(buffer[i]);
feed(ch);
}
}
void JsonReader::feed(std::string const & str) {
for (std::string::const_iterator i(str.begin()); i != str.end(); ++i) {
feed(* i);
}
}
void JsonReader::feedeof() {
send();
}