Debian Codegraph @

protolib/src/common/protoJson.cpp

raw
1 #include "protoJson.h"
2 #include "protoDebug.h"
3 #include <ctype.h> // for tolower()
4 #include <string.h>
5
6 //#include "protoCheck.h"
7
8 ProtoJson::Item::Item(Type theType, Item* theParent)
9 : type(theType), parent(theParent), level((NULL == theParent) ? 0 : theParent->level + 1)
10 {
11 }
12
13 ProtoJson::Item::~Item()
14 {
15 }
16
17 const char* ProtoJson::Item::GetTypeString(Type type)
18 {
19 switch (type)
20 {
21 case INVALID:
22 return "INVALID";
23 case ENTRY:
24 return "ENTRY";
25 case STRING:
26 return "STRING";
27 case NUMBER:
28 return "NUMBER";
29 case OBJECT:
30 return "OBJECT";
31 case ARRAY:
32 return "ARRAY";
33 case TRUE:
34 return "TRUE";
35 case FALSE:
36 return "FALSE";
37 case NONE:
38 return "NULL";
39 }
40 ASSERT(0);
41 return NULL;
42 } // end ProtoJson::Parser::GetTypeString()
43
44 ProtoJson::String::String(Item* theParent)
45 : Item(STRING, theParent), text(NULL)
46 {
47 }
48
49 ProtoJson::String::~String()
50 {
51 if (NULL != text)
52 {
53 delete[] text;
54 text = NULL;
55 }
56 }
57
58 bool ProtoJson::String::SetText(const char* theText)
59 {
60 if (NULL != text) delete[] text;
61 if (NULL == (text = new char[strlen(theText)+1]))
62 {
63 PLOG(PL_ERROR, "ProtoJson::String::Set() new char[] error: %s\n", GetErrorString());
64 return false;
65 }
66 strcpy(text, theText);
67 return true;
68 } // end ProtoJson::String::SetTezt()
69
70 void ProtoJson::String::SetTextPtr(char* textPtr)
71 {
72 if (NULL != text) delete[] text;
73 text = textPtr;
74 } // end ProtoJson::String::SetTextPtr()
75
76 ProtoJson::Number::Number(Item* theParent)
77 : Item(NUMBER, theParent), is_float(false), integer(0)
78 {
79 }
80
81
82 ProtoJson::Number::Number(int value, Item* theParent)
83 : Item(NUMBER, theParent), is_float(false), integer(value)
84 {
85 SetValue(value);
86 }
87
88 ProtoJson::Number::Number(double value, Item* theParent)
89 : Item(NUMBER, theParent), is_float(true), floating(value)
90 {
91 }
92
93 ProtoJson::Number::~Number()
94 {
95 }
96
97 // A null-terminated string MUST be supplied here
98 bool ProtoJson::Number::SetValue(const char* text)
99 {
100 // If the text contains a '.' or 'e', or 'E', it could be a float
101 bool isFloat = false;
102 const char* ptr = text;
103 while (!isFloat && ('\0' != *ptr))
104 {
105 switch (*ptr++)
106 {
107 case '.':
108 case 'E':
109 case 'e':
110 isFloat = true;
111 break;
112 default:
113 break;
114 }
115 }
116 if (isFloat)
117 {
118 double value;
119 if (1 != sscanf(text, "%lf", &value))
120 {
121 PLOG(PL_ERROR, "ProtoJson::Number::SetValue() error: invalid floating point number text\n");
122 return false;
123 }
124 SetValue(value);
125 }
126 else
127 {
128 int value;
129 if (1 != sscanf(text, "%d", &value))
130 {
131 PLOG(PL_ERROR, "ProtoJson::Number::SetValue() error: invalid integer number text\n");
132 return false;
133 }
134 SetValue(value);
135 }
136 return true;
137 } // end ProtoJson::Number::SetValue(text)
138
139 ProtoJson::Array::Array(Item* theParent)
140 : Item(ARRAY, theParent), array_buf(NULL), array_len(0)
141 {
142 }
143
144 ProtoJson::Array::~Array()
145 {
146 Destroy();
147 }
148
149 void ProtoJson::Array::Destroy()
150 {
151 for (unsigned int i = 0; i < array_len; i++)
152 {
153 Item* item = array_buf[i];
154 if (NULL != item) delete item;
155 }
156 if (NULL != array_buf)
157 {
158 delete[] array_buf;
159 array_buf = NULL;
160 }
161 array_len = 0;
162 } // end ProtoJson::Array::Destroy()
163
164 bool ProtoJson::Array::AppendString(const char* text)
165 {
166 ProtoJson::String* string = new ProtoJson::String();
167 if ((NULL == string) || !string->SetText(text) || !AppendValue(*string))
168 {
169 PLOG(PL_ERROR, "ProtoJson::Array::AppendString() error: %s\n", GetErrorString());
170 if (NULL != string) delete string;
171 return false;
172 }
173 return true;
174 } // end ProtoJson::Array::AppendString()
175
176 const char* ProtoJson::Array::GetString(unsigned int index)
177 {
178 const ProtoJson::Value* value = GetValue(index);
179 if ((NULL != value) && (Item::STRING == value->GetType()))
180 return static_cast<const ProtoJson::String*>(value)->GetText();
181 else
182 return NULL;
183 } // end ProtoJson::Array::GetString()
184
185 bool ProtoJson::Array::AppendValue(Value& value)
186 {
187 // TBD - should we do more clever memory mgmnt for better performance
188 // at expense of a little extra memory usage?
189 unsigned int len = array_len + 1;
190 Value** buf = new Value*[len];
191 if (NULL == buf)
192 {
193 PLOG(PL_ERROR, "ProtoJson::Array::AppendValue() new array buffer error: %s\n", GetErrorString());
194 return false;
195 }
196 if (NULL != array_buf)
197 {
198 memcpy(buf, array_buf, array_len*sizeof(Value*));
199 delete[] array_buf;
200 }
201 buf[array_len] = &value;
202 array_buf = buf;
203 array_len = len;
204 value.SetParent(this);
205 return true;
206 } // end ProtoJson::Array::AppendValue()
207
208 // "index" MUST be in existing array range for now
209 void ProtoJson::Array::SetValue(unsigned int index, Value& value)
210 {
211 ClearValue(index);
212 if (index < array_len)
213 {
214 array_buf[index] = &value;
215 value.SetParent(this);
216 }
217 else
218 {
219 PLOG(PL_ERROR, "ProtoJson::Array::SetValue() error: out-of-bounds index!\n");
220 }
221 } // end ProtoJson::Array::SetValue()
222
223 void ProtoJson::Array::ClearValue(unsigned int index)
224 {
225 if (index < array_len)
226 {
227 Value* value = array_buf[index];
228 array_buf[index] = NULL;
229 delete value;
230 }
231 } // end ProtoJson::Array::ClearValue()
232
233
234 const ProtoJson::Value* ProtoJson::Array::GetValue(unsigned int index) const
235 {
236 if (index < array_len)
237 {
238 return array_buf[index];
239 }
240 else
241 {
242 PLOG(PL_WARN, "ProtoJson::Array::GetValue() warning: out-of-bounds index!\n");
243 return NULL;
244 }
245 } // end ProtoJson::Array::GetValue()
246
247 ProtoJson::Value* ProtoJson::Array::AccessValue(unsigned int index)
248 {
249 if (index < array_len)
250 {
251 return array_buf[index];
252 }
253 else
254 {
255 PLOG(PL_WARN, "ProtoJson::Array::GetValue() warning: out-of-bounds index!\n");
256 return NULL;
257 }
258 } // end ProtoJson::Array::GetValue()
259
260 ProtoJson::Object::Object(ProtoJson::Item* theParent)
261 : ProtoJson::Item(OBJECT, theParent)
262 {
263 }
264
265 ProtoJson::Object::~Object()
266 {
267 Destroy();
268 }
269
270 void ProtoJson::Object::Destroy()
271 {
272 ProtoSortedTreeTemplate<Entry>::Destroy();
273 } // end ProtoJson::Object::Destroy()
274
275 bool ProtoJson::Object::InsertEntry(const char* key, Value& value)
276 {
277 Entry* entry = new Entry();
278 if ((NULL == entry) || !entry->SetKey(key) || !InsertEntry(*entry))
279 {
280 PLOG(PL_ERROR, "ProtoJson::Object::InsertEntry() error inserting new Entry: %s\n", GetErrorString());
281 if (NULL != entry) delete entry;
282 return false;
283 }
284 entry->SetValue(&value);
285 return true;
286 } // end ProtoJson::Object::InsertEntry()
287
288 bool ProtoJson::Object::InsertString(const char* key, const char* text)
289 {
290 ProtoJson::String* string = new ProtoJson::String();
291 if ((NULL == string) || !string->SetText(text) || !InsertEntry(key, *string))
292 {
293 PLOG(PL_ERROR, "ProtoJson::Object::InsertString() error inserting new String: %s\n", GetErrorString());
294 if (NULL != string) delete string;
295 return false;
296 }
297 return true;
298 } // end ProtoJson:::Object::InsertString()
299
300 bool ProtoJson::Object::InsertBoolean(const char* key, bool state)
301 {
302 ProtoJson::Boolean* boolean = new ProtoJson::Boolean(state);
303 if ((NULL == boolean) || !InsertEntry(key, *boolean))
304 {
305 PLOG(PL_ERROR, "ProtoJson::Object::InsertString() error inserting new Boolean: %s\n", GetErrorString());
306 if (NULL != boolean) delete boolean;
307 return false;
308 }
309 return true;
310 } // end ProtoJson:::Object::InsertBoolean()
311
312 bool ProtoJson::Object::InsertEntry(Entry& entry)
313 {
314 if (Insert(entry))
315 {
316 entry.SetParent(this);
317 return true;
318 }
319 else
320 {
321 PLOG(PL_ERROR, "ProtoJson::Object::InsertEntry() error: %s\n", GetErrorString());
322 return false;
323 }
324 } // end ProtoJson::Object::InsertEntry()
325
326 // Returns first String text matching "key"
327 const char* ProtoJson::Object::GetString(const char* key)
328 {
329 Iterator iterator(*this);
330 if (!iterator.Reset(false, key)) return NULL;
331 ProtoJson::Entry* entry;
332 while (NULL != (entry = iterator.GetNextEntry()))
333 {
334 const ProtoJson::Value* value = entry->GetValue();
335 if ((NULL != value) && STRING == value->GetType())
336 return static_cast<const ProtoJson::String*>(value)->GetText();
337 }
338 return NULL;
339 } // end ProtoJson::Object::GetString()
340
341 // Returns first Boolean value matching "key"
342 bool ProtoJson::Object::GetBoolean(const char* key)
343 {
344 Iterator iterator(*this);
345 if (!iterator.Reset(false, key)) return false;
346 ProtoJson::Entry* entry;
347 while (NULL != (entry = iterator.GetNextEntry()))
348 {
349 const ProtoJson::Value* value = entry->GetValue();
350 if (NULL != value)
351 {
352 if (TRUE == value->GetType())
353 return true;
354 else if (FALSE == value->GetType())
355 return false;
356 }
357 }
358 return false;
359 } // end ProtoJson::Object::GetBoolean()
360
361 // Returns first Boolean value matching "key"
362 ProtoJson::Array* ProtoJson::Object::GetArray(const char* key)
363 {
364 Iterator iterator(*this);
365 if (!iterator.Reset(false, key)) return NULL;
366 ProtoJson::Entry* entry;
367 while (NULL != (entry = iterator.GetNextEntry()))
368 {
369 ProtoJson::Value* value = entry->AccessValue();
370 if ((NULL != value) && (ARRAY == value->GetType()))
371 return static_cast<ProtoJson::Array*>(value);
372 }
373 return NULL;
374 } // end ProtoJson::Object::GetArray()
375
376
377 ProtoJson::Object::Iterator::Iterator(Object& object)
378 : ProtoSortedTreeTemplate<Entry>::Iterator(object), match_key(NULL)
379 {
380 }
381
382 ProtoJson::Object::Iterator::~Iterator()
383 {
384 if (NULL != match_key)
385 {
386 delete[] match_key;
387 match_key = NULL;
388 }
389 }
390
391 bool ProtoJson::Object::Iterator::Reset(bool reverse, const char* key)
392 {
393 if (NULL != key)
394 {
395 if ((NULL == match_key) || (0 != strcmp(match_key, key)))
396 {
397 if (NULL != match_key) delete[] match_key;
398 if (NULL == (match_key = new char[strlen(key)+1]))
399 {
400 PLOG(PL_ERROR, "ProtoJson::Object::Iterator::Reset() new match_key error: %s\n", GetErrorString());
401 return false;
402 }
403 strcpy(match_key, key);
404 }
405 }
406 else if (NULL != match_key)
407 {
408 delete[] match_key;
409 match_key = NULL;
410 }
411 ProtoSortedTreeTemplate<Entry>::Iterator::Reset(reverse, key, (unsigned int)((NULL != key) ? 8*(strlen(key)+1) : 0));
412 return true;
413 } // end ProtoJson::Object::Iterator::Reset()
414
415 ProtoJson::Entry* ProtoJson::Object::Iterator::GetNextEntry()
416 {
417 ProtoJson::Entry* nextEntry = ProtoSortedTreeTemplate<Entry>::Iterator::GetNextItem();
418 if ((NULL != nextEntry) && (NULL != match_key))
419 {
420 if (0 != strncmp(match_key, nextEntry->GetKey(), strlen(match_key)))
421 return NULL;
422 }
423 return nextEntry;
424 } // end ProtoJson::Object::Iterator::GetNextEntry()
425
426 ProtoJson::Entry* ProtoJson::Object::Iterator::GetPrevEntry()
427 {
428 ProtoJson::Entry* nextEntry = ProtoSortedTreeTemplate<Entry>::Iterator::GetPrevItem();
429 if (NULL != match_key)
430 {
431 if (0 != strncmp(match_key, nextEntry->GetKey(), strlen(match_key)))
432 return NULL;
433 }
434 return nextEntry;
435 } // end ProtoJson::Object::Iterator::GetPrevEntry()
436
437 ProtoJson::Entry::Entry(ProtoJson::Item* theParent)
438 : ProtoJson::Item(ENTRY, theParent), key(NULL), keysize(0), value(NULL)
439 {
440 }
441
442 ProtoJson::Entry::~Entry()
443 {
444 if (NULL != value)
445 {
446 delete value;
447 value = NULL;
448 }
449 if (NULL != key)
450 {
451 delete[] key;
452 key = NULL;
453 }
454 keysize = 0;
455 }
456
457 bool ProtoJson::Entry::SetKey(const char* text)
458 {
459 if (NULL != key) delete[] key;
460 keysize = (unsigned int)strlen(text) + 1; // include null termination
461 if (NULL == (key = new char[keysize]))
462 {
463 keysize = 0;
464 return false;
465 }
466 strcpy(key, text);
467 keysize = keysize << 3; // convert bytes to bits
468 return true;
469 } // end ProtoJson::Entry::SetKey()
470
471 void ProtoJson::Entry::SetValue(Value* theValue)
472 {
473 if (NULL != value) delete value;
474 if (NULL != theValue) theValue->SetParent(this);
475 value = theValue;
476 } // end ProtoJson::Entry::SetValue()
477
478
479 ProtoJson::Document::Document()
480 : item_count(0)
481 {
482 }
483
484 ProtoJson::Document::~Document()
485 {
486 item_list.Destroy();
487 item_count = 0;
488 }
489
490 bool ProtoJson::Document::AddItem(ProtoJson::Item& item)
491 {
492 if (item_list.Append(item))
493 {
494 item.SetParent(NULL);
495 item_count++;
496 return true;
497 }
498 else
499 {
500 PLOG(PL_ERROR, "ProtoJson::Document::AddItem() error: %s\n", GetErrorString());
501 return false;
502 }
503 } // end ProtoJson::Document::AddItem()
504
505 void ProtoJson::Document::RemoveItem(ProtoJson::Item& item)
506 {
507 if (item_list.Contains(item))
508 {
509 item_list.Remove(item);
510 item_count--;
511 }
512 } // end ProtoJson::Document::RemoveItem()
513
514
515 void ProtoJson::Document::Print(FILE* filePtr)
516 {
517 ItemList stack;
518 unsigned int stackDepth = 0;
519 const char* indent = " "; // 4 spaces
520 Iterator iterator(*this);
521 ProtoJson::Value* prevValue = NULL;
522 ProtoJson::Value* value;
523
524 if (item_count > 1)
525 {
526 // If document has multiple top level items, we
527 // present them as a top level array
528 fprintf(filePtr, "[\n %s", indent);
529 stackDepth = 1;
530 }
531 while (NULL != (value = iterator.GetNextItem()))
532 {
533 if (NULL != prevValue)
534 {
535 ProtoJson::Value* savePrev = prevValue;
536 while (value->GetParent() != stack.GetHead())
537 {
538 prevValue = stack.RemoveHead();
539 switch (prevValue->GetType())
540 {
541 case Value::OBJECT:
542 stackDepth--;
543 if(Value::OBJECT != savePrev->GetType())
544 {
545 fprintf(filePtr, "\n");
546 for (unsigned int i = 0; i < stackDepth; i++)
547 fprintf(filePtr, " %s", indent);
548 }
549 // else was an NONE object
550 fprintf(filePtr, "}");
551 break;
552 case Value::ARRAY:
553 stackDepth--;
554 if(Value::ARRAY != savePrev->GetType())
555 {
556 fprintf(filePtr, "\n");
557 for (unsigned int i = 0; i < stackDepth; i++)
558 fprintf(filePtr, " %s", indent);
559 }
560 // else was an NONE array
561 fprintf(filePtr, "]");
562 break;
563
564 case Value::ENTRY:
565 {
566 Item::Type etype = static_cast<Entry*>(prevValue)->GetValue()->GetType();
567 if ((Value::ARRAY != etype) && (Value::OBJECT != etype))
568 stackDepth--;
569 break;
570 }
571 default:
572 // should never occur
573 ASSERT(0);
574 break;
575 }
576 }
577 // Note this does _not_ comma delimit top level document items (is that correct???)
578 //if ((NULL != value->GetParent()) && (value->GetParent() == prevValue->GetParent()))
579 if (value->GetParent() == prevValue->GetParent())
580 fprintf(filePtr, ",");
581
582 if ((Value::ENTRY != savePrev->GetType()) ||
583 (Value::OBJECT == value->GetType()) ||
584 (Value::ARRAY == value->GetType()))
585 {
586 fprintf(filePtr, "\n");
587 for (unsigned int i = 0; i < stackDepth; i++)
588 fprintf(filePtr, " %s", indent);
589 }
590 }
591
592 PrintValue(filePtr, *value);
593
594 switch (value->GetType())
595 {
596 case Value::OBJECT:
597 case Value::ARRAY:
598 stack.Prepend(*value);
599 stackDepth++;
600 break;
601 case Value::ENTRY:
602 {
603 stack.Prepend(*value);
604 Item::Type etype = static_cast<Entry*>(value)->GetValue()->GetType();
605 if ((Value::ARRAY != etype) && (Value::OBJECT != etype))
606 stackDepth++;
607 break;
608 }
609 default:
610 break;
611 }
612
613 prevValue = value;
614
615 }
616 while (NULL != prevValue)
617 {
618 switch (prevValue->GetType())
619 {
620 case Value::OBJECT:
621 fprintf(filePtr, "\n");
622 for (unsigned int i = 0; i < stackDepth; i++)
623 fprintf(filePtr, " %s", indent);
624 fprintf(filePtr, "}");
625 break;
626 case Value::ARRAY:
627 fprintf(filePtr, "\n");
628 for (unsigned int i = 0; i < stackDepth; i++)
629 fprintf(filePtr, " %s", indent);
630 fprintf(filePtr, "]");
631 break;
632 default:
633 // should be an ENTRY?
634 break;
635 }
636 prevValue = stack.RemoveHead();
637 if (NULL != prevValue)
638 {
639 if (Value::ENTRY == prevValue->GetType())
640 {
641 Item::Type etype = static_cast<Entry*>(prevValue)->GetValue()->GetType();
642 if ((Value::ARRAY != etype) && (Value::OBJECT != etype))
643 stackDepth--;
644 }
645 else //if (0 != stackDepth)
646 {
647 stackDepth--;
648 }
649 }
650 }
651 fprintf(filePtr, "\n");
652 if (item_count > 1) fprintf(filePtr, "]\n");
653
654 } // end ProtoJson::Document::Print()
655
656 void ProtoJson::Document::PrintValue(FILE* filePtr, const Value& value)
657 {
658 switch (value.GetType())
659 {
660 case Value::ENTRY:
661 {
662 const Entry& entry = static_cast<const Entry&>(value);
663 fprintf(filePtr, "\"%s\" : ", entry.GetKey());
664 break;
665 }
666 case Value::STRING:
667 {
668 const char* text = static_cast<const String&>(value).GetText();
669 //fprintf(filePtr, "\"%s\"", (NULL != text) ? text : "");
670 PrintString(filePtr, text);
671 break;
672 }
673 case Value::NUMBER:
674 {
675 const Number& number = static_cast<const Number&>(value);
676 if (number.IsFloat())
677 fprintf(filePtr, "%f", number.GetDouble());
678 else
679 fprintf(filePtr, "%d", number.GetInteger());
680 break;
681 }
682 case Value::OBJECT:
683 fprintf(filePtr, "{");
684 break;
685 case Value::ARRAY:
686 fprintf(filePtr, "[");
687 break;
688 case Value::TRUE:
689 fprintf(filePtr, "true");
690 break;
691 case Value::FALSE:
692 fprintf(filePtr, "false");
693 break;
694 case Value::NONE:
695 fprintf(filePtr, "null");
696 break;
697 default:
698 ASSERT(0);
699 break;
700 }
701 } // end ProtoJson::Document::PrintValue()
702
703 void ProtoJson::Document::PrintString(FILE* filePtr, const char* text)
704 {
705 // Converts any escapable characters to corresponding sequence
706 fprintf(filePtr, "\"");
707 const char* ptr = text;
708 while ('\0' != *ptr)
709 {
710 char escape = Parser::GetEscapeCode(*ptr);
711 if (0 != escape)
712 fprintf(filePtr, "\\%c", escape);
713 else
714 fprintf(filePtr, "%c", *ptr);
715 ptr++;
716 }
717 fprintf(filePtr, "\"");
718 } // end ProtoJson::Document::PrintString()
719
720 ProtoJson::Document::Iterator::Iterator(Document& document, bool depthFirst)
721 : list_iterator(document.item_list), depth_first(depthFirst)
722 {
723 }
724
725 ProtoJson::Document::Iterator::~Iterator()
726 {
727 }
728
729 ProtoJson::Item* ProtoJson::Document::Iterator::GetNextItem()
730 {
731 Value* currentItem = pending_list.RemoveHead();
732 if (NULL == currentItem)
733 currentItem = list_iterator.GetNextItem();
734 if (NULL != currentItem)
735 {
736 if (Value::ARRAY == currentItem->GetType())
737 {
738 // Put array items into pending_list
739 Array* array = static_cast<Array*>(currentItem);
740 unsigned arrayLength = array->GetLength();
741 for (unsigned int i = 0; i < arrayLength; i++)
742 {
743 unsigned int index = arrayLength - i - 1;
744 Value* value = array->AccessValue(index);
745 if (NULL == value)
746 {
747 if (NULL == (value = new NullValue(value)))
748 {
749 PLOG(PL_ERROR, "ProtoJson::Document::Iterator::GetNextItem() new NullValue() error: %s\n",
750 GetErrorString());
751 return NULL;
752 }
753 array->SetValue(index, *value);
754 }
755 bool result = depth_first ? pending_list.Prepend(*value) : pending_list.Append(*value);
756 if (!result)
757 {
758 PLOG(PL_ERROR, "ProtoJson::Document::Iterator::GetNextItem() error: unable to update pending_list\n");
759 return NULL;
760 }
761 }
762 }
763 else if (Value::OBJECT == currentItem->GetType())
764 {
765 // Put object entries into pending_list
766 Object* object = static_cast<Object*>(currentItem);
767 Object::Iterator iterator(*object);
768 iterator.Reset(true); // reverse to make pending_list order right
769 Entry* entry;
770 while (NULL != (entry = iterator.GetPrevEntry()))
771 {
772 bool result = depth_first ? pending_list.Prepend(*entry) : pending_list.Append(*entry);
773 if (!result)
774 {
775 PLOG(PL_ERROR, "ProtoJson::Document::Iterator::GetNextItem() error: unable to update pending_list\n");
776 return NULL;
777 }
778 }
779 }
780 else if (Value::ENTRY == currentItem->GetType())
781 {
782 // Put entry value into pending_list
783 Entry* entry = static_cast<Entry*>(currentItem);
784 Value* value = entry->AccessValue();
785 if (NULL == value)
786 {
787 if (NULL == (value = new NullValue(entry)))
788 {
789 PLOG(PL_ERROR, "ProtoJson::Document::Iterator::GetNextItem() new NullValue() error: %s\n",
790 GetErrorString());
791 return NULL;
792 }
793 entry->SetValue(value);
794 }
795 bool result = depth_first ? pending_list.Prepend(*value) : pending_list.Append(*value);
796 if (!result)
797 {
798 PLOG(PL_ERROR, "ProtoJson::Document::Iterator::GetNextItem() error: unable to update pending_list\n");
799 return NULL;
800 }
801 }
802 }
803 return currentItem;
804 } // end ProtoJson::Document::Iterator::GetNextItem()
805
806 // Delimiters for parsing
807 const char ProtoJson::Parser::OBJECT_START = '{';
808 const char ProtoJson::Parser::OBJECT_END = '}';
809 const char ProtoJson::Parser::ARRAY_START = '[';
810 const char ProtoJson::Parser::ARRAY_END = ']';
811 const char ProtoJson::Parser::QUOTE ='\"';
812 const char ProtoJson::Parser::COLON = ':';
813 const char ProtoJson::Parser::COMMA = ',';
814 const char ProtoJson::Parser::ESCAPE = '\\';
815 const char ProtoJson::Parser::TRUE_START = 't';
816 const char ProtoJson::Parser::FALSE_START = 'f';
817 const char ProtoJson::Parser::NULL_START = 'n';
818
819 ProtoJson::Parser::Parser()
820 : current_document(NULL), current_item(NULL), input_offset(0),
821 input_escape_pending(false), is_escaped(false),
822 seek_colon(false), temp_buffer(NULL),
823 temp_buffer_max(0), temp_buffer_len(0)
824 {
825 }
826
827 ProtoJson::Parser::~Parser()
828 {
829 Destroy();
830 }
831
832 void ProtoJson::Parser::Destroy()
833 {
834 if (NULL != current_document)
835 {
836 current_document->Destroy();
837 delete current_document;
838 current_document = NULL;
839 }
840 if (NULL != current_item)
841 {
842 delete current_item;
843 current_item = NULL;
844 }
845 input_offset = 0;
846 input_escape_pending = false;
847 is_escaped = false;
848 seek_colon = false;
849 if (NULL != temp_buffer)
850 {
851 delete[] temp_buffer;
852 temp_buffer = NULL;
853 }
854 temp_buffer_len = temp_buffer_max = 0;
855 } // end ProtoJson::Parser::Destroy()
856
857 bool ProtoJson::Parser::LoadDocument(const char *path, Document* document)
858 {
859 FILE* infile = fopen(path, "r");
860 if (NULL == infile)
861 {
862 PLOG(PL_ERROR, "ProtoJson::Parser::LoadDocument() error opening file: %s\n", GetErrorString());
863 return false;
864 }
865 if (NULL != document)
866 {
867 if (NULL != current_document)
868 delete current_document;
869 current_document = document;
870 }
871 Status status = PARSE_MORE;
872 size_t result;
873 char buffer[1024];
874 while (0 != (result = fread(buffer, sizeof(char), 1024, infile)))
875 {
876 status = ProcessInput(buffer, (unsigned int)result);
877 if (PARSE_ERROR == status)
878 {
879 PLOG(PL_ERROR, "ProtoJson::Parser::LoadDocument() error: invalid JSON document!\n");
880 if (NULL != document) DetachDocument();
881 return false;
882 }
883 }
884 if (PARSE_MORE == status)
885 {
886 PLOG(PL_ERROR, "ProtoJson::Parser::LoadDocument() error: incomplete JSON document!\n");
887 if (NULL != document) DetachDocument();
888 return false;
889 }
890 else
891 {
892 if (NULL != document) DetachDocument();
893 return true;
894 }
895 } // end ProtoJson::Parser::LoadDocument()
896
897
898 ProtoJson::Document* ProtoJson::Parser::DetachDocument()
899 {
900 Document* doc = current_document;
901 current_document = NULL;
902 return doc;
903 } // end ProtoJson::Parser::DetachDocument()
904
905
906 // This infers the Item type from the first character
907 // of the Item's textual representation
908 ProtoJson::Item::Type ProtoJson::Parser::GetType(char c)
909 {
910 c = tolower(c);
911 switch (c)
912 {
913 case OBJECT_START:
914 return Item::OBJECT;
915 case ARRAY_START:
916 return Item::ARRAY;
917 case QUOTE:
918 return Item::STRING;
919 case TRUE_START:
920 return Item::TRUE;
921 case FALSE_START:
922 return Item::FALSE;
923 case NULL_START:
924 return Item::NONE;
925 default:
926 return Item::NUMBER;
927 }
928 } // end ProtoJson::Parser::GetType()
929
930
931
932 bool ProtoJson::Parser::AddValueToParent(Item* parent, Item& value)
933 {
934 // Values may be added to one of 3 parent types
935 // 1) if NULL == parent, "value" is a root level item and MUST be an ARRAY or OBJECT, or
936 // 2) Value items may be appended to ARRAYs, or
937 // 3) Value items may be assigned to an Object Entry
938
939 ASSERT(value.IsValue());
940
941 if (NULL == parent)
942 {
943 //ASSERT((Item::ARRAY == value.GetType()) || (Item::OBJECT == value.GetType()));
944 ASSERT(Item::INVALID != value.GetType());
945 current_document->AddItem(value);
946 }
947 else
948 {
949 switch (parent->GetType())
950 {
951 case Item::ARRAY:
952 if (!static_cast<Array*>(parent)->AppendValue(value))
953 {
954 PLOG(PL_ERROR, "ProtoJson::Parser::AddValueToParent() error: unable to append array\n");
955 return false;
956 }
957 break;
958 case Item::ENTRY:
959 static_cast<Entry*>(parent)->SetValue(&value);
960 break;
961 default:
962 PLOG(PL_ERROR, "ProtoJson::Parser::AddValueToParent() error: invalid parent type\n");
963 ASSERT(0);
964 return false;
965 }
966 }
967 return true;
968 } // end AddValueToParent()
969
970 bool ProtoJson::Parser::IsValidEscapeCode(char c)
971 {
972 switch (c)
973 {
974 case 'b': // backspace
975 case 'f': // form feed
976 case 'n': // new line
977 case 'r': // carriage return
978 case 't': // tab
979 case '"': // double quote
980 case '\\': // backslash
981 return true;
982 default:
983 return false;
984 }
985 } // end ProtoJson::Parser::IsValidEscapeCode()
986
987 char ProtoJson::Parser::GetEscapeCode(char c)
988 {
989 // returns escape code for input char
990 // (or zero if non-escaped character)
991 switch (c)
992 {
993 case '\b': // backspace
994 return 'b';
995 case '\f': // form feed
996 return 'f';
997 case '\n': // new line
998 return 'n';
999 case '\r': // carriage return
1000 return 'r';
1001 case '\t': // tab
1002 return 't';
1003 case '"': // double quote
1004 return '"';
1005 case '\\': // backslash
1006 return '\\';
1007 default:
1008 return 0;
1009 }
1010 } // end ProtoJson::Parser::GetEscapeCode()
1011
1012 char ProtoJson::Parser::Unescape(char c)
1013 {
1014 // returns char corresponding to escape code
1015 // (or input char if non-escaped character)
1016 switch (c)
1017 {
1018 case 'b': // backspace
1019 return '\b';
1020 case 'f': // form feed
1021 return '\f';
1022 case 'n': // new line
1023 return '\n';
1024 case 'r': // carriage return
1025 return '\r';
1026 case 't': // tab
1027 return '\t';
1028 case '"': // double quote
1029 return '"';
1030 case '\\': // backslash
1031 return '\\';
1032 default:
1033 return c;
1034 }
1035 } // end ProtoJson::Parser::Unescape()
1036
1037 bool ProtoJson::Parser::AddToString(String& string, const char* text, unsigned int length)
1038 {
1039 // Unescape text being added
1040 // First, determine length of "unescaped" version of 'text'
1041 unsigned int count = 0;
1042 bool pending = input_escape_pending;
1043 for (unsigned int i = 0; i < length; i++)
1044 {
1045 char c = text[i];
1046 if (pending)
1047 {
1048 pending = false;
1049 if (IsValidEscapeCode(c))
1050 {
1051 count++;
1052 }
1053 else
1054 {
1055 PLOG(PL_ERROR, "ProtoJson::Parser::AddToString() error: invalid escape sequence code '\\%c'!\n", c);
1056 return false;
1057 }
1058 }
1059 else if ('\\' == c)
1060 {
1061 pending = true;
1062 continue;
1063 }
1064 else
1065 {
1066 count++;
1067 }
1068 }
1069 size_t total = string.GetLength() + count;
1070 char* buffer = new char[total + 1]; // include null terminator
1071 if (NULL == buffer)
1072 {
1073 PLOG(PL_ERROR, "ProtoJson::Parser::AddToString() new buffer error: %s\n", GetErrorString());
1074 return false;
1075 }
1076 if (NULL != string.GetText())
1077 strcpy(buffer, string.GetText());
1078 if (0 != length)
1079 {
1080 // Convert/copy 'unescaped text' into new buffer
1081 char* ptr = buffer + string.GetLength();
1082 count = 0;
1083 for (unsigned int i = 0; i < length; i++)
1084 {
1085 char c = text[i];
1086 if (input_escape_pending)
1087 {
1088 input_escape_pending = false;
1089 // already validated escape codes above
1090 ptr[count++] = Unescape(c);
1091 }
1092 else if ('\\' == c)
1093 {
1094 input_escape_pending = true;
1095 continue;
1096 }
1097 else
1098 {
1099 ptr[count++] = c;
1100 }
1101 }
1102 }
1103 buffer[total] = '\0';
1104 string.SetTextPtr(buffer);
1105 return true;
1106 } // end ProtoJson::Parser::AddToString()
1107
1108 ProtoJson::Parser::Status ProtoJson::Parser::ProcessStringInput(const char* input, unsigned int length)
1109 {
1110 bool start = (NULL == current_item) ? true : false;
1111 String* string;
1112 if (start)
1113 {
1114 // We're starting a new string, so create using top of stack as parent
1115 Item* parent = PeekStack();
1116 if ((NULL != parent) && ((Item::ENTRY != parent->GetType()) && (Item::ARRAY != parent->GetType())))
1117 {
1118 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessStringInput() error: invalid JSON syntax\n");
1119 return PARSE_ERROR;
1120 }
1121 string = new String(parent);
1122 if (NULL == string)
1123 {
1124 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessStringInput() new String error: %s\n", GetErrorString());
1125 return PARSE_ERROR;
1126 }
1127 current_item = string;
1128 }
1129 else
1130 {
1131 ASSERT(Item::STRING == current_item->GetType());
1132 string = static_cast<String*>(current_item);
1133 }
1134 if (0 == length) return PARSE_MORE; // need more input
1135 unsigned int i = 0;//start ? 1 : 0; // to skip leading quote if applicable
1136 const char* startPtr = input + i;
1137 for (; i < length; i++)
1138 {
1139 char c = input[i];
1140 if (is_escaped)
1141 {
1142 // TBD - should we convert escaped characters here,
1143 // or do it within the AddToString() method?
1144 // (and PrintString() should have option to
1145 // output escaped or raw version of string)
1146 is_escaped = false;
1147 continue;
1148 }
1149 else if (ESCAPE == c)
1150 {
1151 is_escaped = true;
1152 continue;
1153 }
1154 else if (QUOTE == c)
1155 {
1156 // We've found the end of the string
1157 if (AddToString(*string, startPtr, i))
1158 {
1159 // consume string text and end QUOTE
1160 input_offset += i + 1;
1161 if (!AddValueToParent(string->AccessParent(), *string))
1162 {
1163 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessStringInput() error: unable to add to parent\n");
1164 return PARSE_ERROR;
1165 }
1166 current_item = NULL;
1167 return PARSE_DONE;
1168 }
1169 else
1170 {
1171 return PARSE_ERROR;
1172 }
1173 }
1174 }
1175 // Incomplete string, need more input
1176 if (AddToString(*string, startPtr, length))
1177 {
1178 input_offset += length;
1179 return PARSE_MORE;
1180 }
1181 else
1182 {
1183 return PARSE_ERROR;
1184 }
1185 } // end ProtoJson::Parser::ProcessStringInput()
1186
1187 bool ProtoJson::Parser::AddToTemp(const char* text, unsigned int length)
1188 {
1189 // TBD - strip.convert escape sequences?
1190 if (0 == length) return true;
1191 unsigned int total = temp_buffer_len + length;
1192 if (total > temp_buffer_max)
1193 {
1194 char* buffer = new char[total+1]; // include null terminator
1195 if (NULL == buffer)
1196 {
1197 PLOG(PL_ERROR, "ProtoJson::Parser::AddToTemp() new buffer error: %s\n", GetErrorString());
1198 return false;
1199 }
1200 //if (NULL != temp_buffer)
1201 if (0 != temp_buffer_len)
1202 {
1203 memcpy(buffer, temp_buffer, temp_buffer_len);
1204 delete[] temp_buffer;
1205 }
1206 memcpy(buffer + temp_buffer_len, text, length);
1207 buffer[total] = '\0';
1208 temp_buffer = buffer;
1209 temp_buffer_len = temp_buffer_max = total;
1210 }
1211 else
1212 {
1213 memcpy(temp_buffer + temp_buffer_len, text, length);
1214 temp_buffer[total] = '\0';
1215 temp_buffer_len = total;
1216 }
1217 return true;
1218 } // end ProtoJson::Parser::AddToTemp()
1219
1220 ProtoJson::Parser::Status ProtoJson::Parser::ProcessNumberInput(const char* input, unsigned int length)
1221 {
1222 bool start = (NULL == current_item) ? true : false;
1223 Number* number;
1224 if (start)
1225 {
1226 // We're starting a new number, so create using top of stack as parent
1227 Item* parent = PeekStack();
1228 if ((NULL != parent) && ((Item::ENTRY != parent->GetType()) && (Item::ARRAY != parent->GetType())))
1229 {
1230 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: invalid JSON syntax\n");
1231 return PARSE_ERROR;
1232 }
1233 number = new Number(parent);
1234 if (NULL == number)
1235 {
1236 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() new Number error: %s\n", GetErrorString());
1237 return PARSE_ERROR;
1238 }
1239 current_item = number;
1240 temp_buffer_len = 0;
1241 }
1242 else
1243 {
1244 ASSERT(Item::NUMBER == current_item->GetType());
1245 number = static_cast<Number*>(current_item);
1246 }
1247 if (0 == length) return PARSE_MORE; // need more input
1248 for (unsigned int i = 0; i < length; i++)
1249 {
1250 char c = input[i];
1251 if (isspace(c) || (COMMA == c) || (OBJECT_END == c) || (ARRAY_END == c))
1252 {
1253 // end of number string found
1254 if (AddToTemp(input, i))
1255 {
1256 input_offset += i; // consume number text
1257 if (!number->SetValue(temp_buffer))
1258 {
1259 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: invalid number text\n");
1260 return PARSE_ERROR;
1261 }
1262 temp_buffer_len = 0; // reset temp_buffer
1263 if (!AddValueToParent(number->AccessParent(), *number))
1264 {
1265 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: unable to add number to parent\n");
1266 return PARSE_ERROR;
1267 }
1268 current_item = NULL;
1269 return PARSE_DONE;
1270 }
1271 else
1272 {
1273 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: unable to update temp_buffer\n");
1274 return PARSE_ERROR;
1275 }
1276 }
1277 }
1278 // incomplete number text, need more input
1279 if (AddToTemp(input, length))
1280 {
1281 input_offset += length;
1282 return PARSE_MORE;
1283 }
1284 else
1285 {
1286 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: unable to update temp_buffer\n");
1287 return PARSE_ERROR;
1288 }
1289 } // end ProtoJson::Parser::ProcessNumberInput()
1290
1291 bool ProtoJson::Parser::FixedItemIsValid(Item::Type type)
1292 {
1293 char* ptr = temp_buffer;
1294 // Convert temp_buffer to lower case for validation
1295 while ('\0' != *ptr)
1296 {
1297 *ptr = tolower(*ptr);
1298 ptr++;
1299 }
1300 switch (type)
1301 {
1302 case Item::TRUE:
1303 return (0 == strcmp(temp_buffer, "true"));
1304 break;
1305 case Item::FALSE:
1306 return (0 == strcmp(temp_buffer, "false"));
1307 break;
1308 case Item::NONE:
1309 return (0 == strcmp(temp_buffer, "null"));
1310 break;
1311 default:
1312 return false;
1313 }
1314 } // end ProtoJson::Parser::FixedItemIsValid()
1315
1316 ProtoJson::Parser::Status ProtoJson::Parser::ProcessFixedInput(const char* input, unsigned int length)
1317 {
1318 // This is used for "true", "false", and "null" value fields (i.e. fixed text)
1319 // Basically, the first character gives it away, but we validate
1320 bool start = (NULL == current_item) ? true : false;
1321 if (start)
1322 {
1323 // We're starting a new number, so create using top of stack as parent
1324 Item* parent = PeekStack();
1325 if ((NULL != parent) && ((Item::ENTRY != parent->GetType()) && (Item::ARRAY != parent->GetType())))
1326 {
1327 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessNumberInput() error: invalid JSON syntax\n");
1328 return PARSE_ERROR;
1329 }
1330 // TBD if parent is an object, then this MUST be the object's value field
1331 char c = tolower(*input);
1332 switch (c)
1333 {
1334 case TRUE_START:
1335 current_item = new ProtoJson::Boolean(true, parent);
1336 break;
1337 case FALSE_START:
1338 current_item = new ProtoJson::Boolean(false, parent);
1339 break;
1340 case NULL_START:
1341 current_item = new ProtoJson::NullValue(parent);
1342 break;
1343 default:
1344 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessFixedInput(%5s) error: invalid text\n", input);
1345 return PARSE_ERROR;
1346 }
1347 }
1348 ASSERT((Item::TRUE == current_item->GetType()) ||
1349 (Item::FALSE == current_item->GetType()) ||
1350 (Item::NONE == current_item->GetType()));
1351 if (0 == length) return PARSE_MORE; // need more input
1352 for (unsigned int i = 0; i < length; i++)
1353 {
1354 char c = input[i];
1355 if (isspace(c) || (COMMA == c) || (OBJECT_END == c) || (ARRAY_END == c))
1356 {
1357 // end of fixed value found
1358 if (AddToTemp(input, i))
1359 {
1360 // consume fixed item chars
1361 input_offset += i;
1362 if (!FixedItemIsValid(current_item->GetType()))
1363 {
1364 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessFixedInput(%s) error: invalid fixed text\n", temp_buffer);
1365 return PARSE_ERROR;
1366 }
1367 temp_buffer_len = 0; // reset temp_buffer
1368 if (!AddValueToParent(current_item->AccessParent(), *current_item))
1369 {
1370 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessFixedInput() error: unable to add \"%s\" value to parent\n", temp_buffer);
1371 return PARSE_ERROR;
1372 }
1373 current_item = NULL;
1374 return PARSE_DONE;
1375 }
1376 else
1377 {
1378 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessFixedInput() error: unable to update temp_buffer\n");
1379 return PARSE_ERROR;
1380 }
1381 }
1382 }
1383 // Did not yet find end of fixed text
1384 if (AddToTemp(input, length))
1385 {
1386 return PARSE_MORE;
1387 }
1388 else
1389 {
1390 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessFixedInput() error: unable to update temp_buffer\n");
1391 return PARSE_ERROR;
1392 }
1393 } // end ProtoJson::Parser::ProcessFixedInput()
1394
1395 ProtoJson::Parser::Status ProtoJson::Parser::ProcessArrayInput(const char* input, unsigned int length)
1396 {
1397 // Seeking array value items or ARRAY_END
1398 bool start = (NULL == current_item) ? true : false;
1399 Array* array;
1400 if (start)
1401 {
1402 if (NULL == (array = new Array(PeekStack())))
1403 {
1404 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessArrayInput() new Array error: %s\n", GetErrorString());
1405 return PARSE_ERROR;
1406 }
1407 current_item = array;
1408 }
1409 else
1410 {
1411 ASSERT(Item::ARRAY == current_item->GetType());
1412 array = static_cast<Array*>(current_item);
1413 }
1414 if (0 == length) return PARSE_MORE; // need more input
1415 for (unsigned int i = 0; i < length; i++)
1416 {
1417 char c = input[i];
1418 if (isspace(c))
1419 continue;
1420 else if (COMMA == c)
1421 // TBD - validate that a comma is indeed followed by a value???
1422 // skipping blank array fields is permissive, but maybe OK?
1423 continue;
1424 else if (ARRAY_END == c)
1425 {
1426 // consume white space + ARRAY_END
1427 input_offset += i + 1;
1428 // Attach completed array to parent
1429 if (!AddValueToParent(array->AccessParent(), *array))
1430 {
1431 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessArrayInput() error: unable to add array to parent\n");
1432 return PARSE_ERROR;
1433 }
1434 current_item = NULL;
1435 return PARSE_DONE;
1436 }
1437 else
1438 {
1439 // Should be first character of an array value item
1440 PushStack(*current_item);
1441 current_item = NULL;
1442 input_offset += i;
1443 return ProcessValueInput(input + i, length - i);
1444 }
1445 }
1446 input_offset += length;
1447 return PARSE_MORE; // more input needed
1448 } // end ProtoJson::Parser::ProcessArrayInput()
1449
1450 ProtoJson::Parser::Status ProtoJson::Parser::ProcessEntryInput(const char* input, unsigned int length)
1451 {
1452 // Seeking entry key, Value, or end-of-entry delimiter
1453 bool start = (NULL == current_item) ? true : false;
1454 Entry* entry;
1455 Object* object; // parent of entry
1456 if (start)
1457 {
1458 // An ENTRY's parent MUST always be an OBJECT
1459 ASSERT((NULL != PeekStack()) && (Item::OBJECT == PeekStack()->GetType()));
1460 object = static_cast<Object*>(PeekStack());
1461 if (NULL == (entry = new Entry(object)))
1462 {
1463 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() new Entry error: %s\n", GetErrorString());
1464 return PARSE_ERROR;
1465 }
1466 current_item = entry;
1467 }
1468 else
1469 {
1470 ASSERT(Item::ENTRY == current_item->GetType());
1471 entry = static_cast<Entry*>(current_item);
1472 object = static_cast<Object*>(entry->AccessParent());
1473 }
1474 // Notes:
1475 // 1) First, the Entry "key" is sought, cached in temp_buffer and set upon completion
1476 // 2) Second, the key must be followed by a colon delimiter so we find that
1477 // 3) Then, we push the Entry to stack and parse for it's Value field, possibly going down multiple levels
1478 // 4) When the Value is complete, it adds itself to the Entry and returns PARSE_DONE to upper layer (which pops stack)
1479 // 5) At this point, we look for the end-of-entry (either COMMA or END_OBJECT)
1480 //
1481 // The key detail here is the Value item knows to add itself to Entry (or Array) parents upon completion.
1482 // That happens in the code for the different Value input processors
1483
1484
1485 enum Mode
1486 {
1487 SEEK_KEY, // accumulating key string (starts here)
1488 SEEK_COLON,
1489 SEEK_VALUE, // got key, look for value
1490 SEEK_TERM // got value, look for end-of-entry (termination) delimiter
1491 };
1492 Mode mode;
1493 if (NULL == entry->GetKey())
1494 mode = SEEK_KEY;
1495 else if (seek_colon)
1496 mode = SEEK_COLON;
1497 else if (NULL == entry->GetValue())
1498 mode = SEEK_VALUE;
1499 else
1500 mode = SEEK_TERM;
1501 if (0 == length) return PARSE_MORE; // need more input
1502 for (unsigned int i = 0; i < length; i++)
1503 {
1504 char c = input[i];
1505 switch (mode)
1506 {
1507 case SEEK_KEY:
1508 if (is_escaped)
1509 {
1510 is_escaped = false;
1511 continue;
1512 }
1513 else if (ESCAPE == c)
1514 {
1515 is_escaped = true;
1516 continue;
1517 }
1518 else if (c == QUOTE)
1519 {
1520 // non-escaped QUOTE is end of key string
1521 if (!AddToTemp(input, i))
1522 {
1523 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() error: unable to add to temp_buffer\n");
1524 return PARSE_ERROR;
1525 }
1526 if (!entry->SetKey(temp_buffer))
1527 {
1528 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() error: unable to set entry key\n");
1529 return PARSE_ERROR;
1530 }
1531 temp_buffer_len = 0; // reset temp_buffer
1532 seek_colon = true;
1533 mode = SEEK_COLON;
1534 }
1535 break;
1536 case SEEK_COLON:
1537 if (COLON == c)
1538 {
1539 // we don't need to consume anything here since
1540 // it's just a mode change with no return
1541 seek_colon = false;
1542 mode = SEEK_VALUE;
1543 }
1544 break;
1545 case SEEK_VALUE:
1546 if (isspace(c))
1547 {
1548 continue; // skip white space
1549 }
1550 else
1551 {
1552 // upper level will re-enter and mode with be SEEK_TERM if value completed
1553 input_offset += i; // consume skipped white space
1554 PushStack(*entry);
1555 current_item = NULL;
1556 return ProcessValueInput(input + i, length - i);
1557 }
1558 break;
1559 case SEEK_TERM:
1560 if (isspace(c))
1561 {
1562 continue; // skip white space
1563 }
1564 switch (c)
1565 {
1566 // Either of these indicates end-of-entry, but note we
1567 // preserve the OBJECT_END for the upper layer object parsing
1568 case COMMA:
1569 input_offset++; // consume comma
1570 case OBJECT_END:
1571 input_offset += i; // consume white space
1572 if (!object->InsertEntry(*entry))
1573 {
1574 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() error: entry insertion failure\n");
1575 return PARSE_ERROR;
1576 }
1577 current_item = NULL; // entry is finished, upper layer will pop object off stack
1578 return PARSE_DONE;
1579 default:
1580 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() error: invalid JSON input\n");
1581 return PARSE_ERROR;
1582 }
1583 break;
1584 } // end switch (mode)
1585 } // end for (...)
1586 // if we make it here, we need more input
1587 // incomplete entry text, need more input
1588 if (AddToTemp(input, length))
1589 {
1590 input_offset += length;
1591 return PARSE_MORE;
1592 }
1593 else
1594 {
1595 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessEntryInput() error: unable to update temp_buffer\n");
1596 return PARSE_ERROR;
1597 }
1598
1599 //input_offset += length;
1600 //return PARSE_MORE;
1601 } // end ProtoJson::Parser::ProcessEntryInput()
1602
1603 ProtoJson::Parser::Status ProtoJson::Parser::ProcessObjectInput(const char* input, unsigned int length)
1604 {
1605 // Seeking object key,value items or OBJECT_END
1606 bool start = (NULL == current_item) ? true : false;
1607 Object* object;
1608 if (start)
1609 {
1610 if (NULL == (object = new Object(PeekStack())))
1611 {
1612 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessObjectInput() new Object error: %s\n", GetErrorString());
1613 return PARSE_ERROR;
1614 }
1615 current_item = object;
1616 }
1617 else
1618 {
1619 ASSERT(Item::OBJECT == current_item->GetType());
1620 object = static_cast<Object*>(current_item);
1621 }
1622 if (0 == length) return PARSE_MORE; // need more input
1623 for (unsigned int i = 0; i < length; i++)
1624 {
1625 char c = input[i];
1626 if (isspace(c))
1627 continue;
1628 else if (COMMA == c)
1629 // TBD - validate that a comma is indeed followed by a value???
1630 // skipping blank array fields is permissive, but maybe OK?
1631 continue;
1632 else if (OBJECT_END == c)
1633 {
1634 input_offset += i + 1; // consume white space + OBJECT_END
1635 // Attach completed object to parent
1636 if (!AddValueToParent(object->AccessParent(), *object))
1637 {
1638 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessObjectInput() error: unable to add object to parent\n");
1639 return PARSE_ERROR;
1640 }
1641 current_item = NULL; // current_item completed
1642 return PARSE_DONE;
1643 }
1644 else if (QUOTE == c)
1645 {
1646 // Should be first character of an object key string
1647 PushStack(*current_item);
1648 current_item = NULL;
1649 input_offset += i + 1; // consume whitespace + QUOTE
1650 return ProcessEntryInput(input + i + 1, length - (i + 1));
1651 }
1652 else
1653 {
1654 // Invalid JSON syntax
1655 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessObjectInput() error: invalid Object content\n");
1656 return PARSE_ERROR;
1657 }
1658 }
1659 input_offset += length;
1660 return PARSE_MORE; // more input needed
1661 } // end ProtoJson::Parser::ProcessObjectInput()
1662
1663 ProtoJson::Parser::Status ProtoJson::Parser::ProcessValueInput(const char* input, unsigned int length)
1664 {
1665 ASSERT(NULL == current_item);
1666 if (0 == length) return PARSE_MORE;
1667 // This is invoked to process ARRAY or OBJECT Item items
1668 // The first char of the "input" should be beginning of some Item item
1669 // (string, number, object, array, true, false, null)
1670 Item::Type type = GetType(input[0]);
1671 switch (type)
1672 {
1673 case Item::STRING:
1674 // consume QUOTE (string start delimiter)
1675 input_offset++;
1676 return ProcessStringInput(input+1, length-1);
1677 case Item::NUMBER:
1678 return ProcessNumberInput(input, length);
1679 break;
1680 case Item::OBJECT:
1681 // consume OBJECT_START delimiter
1682 input_offset++;
1683 return ProcessObjectInput(input+1, length-1);
1684 break;
1685 case Item::ARRAY:
1686 // consume ARRAY_START delimiter
1687 input_offset++;
1688 return ProcessArrayInput(input+1, length-1);
1689 break;
1690 case Item::TRUE:
1691 case Item::FALSE:
1692 case Item::NONE:
1693 return ProcessFixedInput(input, length);
1694 default:
1695 // Will not occur
1696 ASSERT(0);
1697 return PARSE_ERROR;
1698 }
1699 } // end Status ProtoJson::Parser::ProcessValueInput(()
1700
1701 // This routine will become the heart of
1702 // our ProtoJson parser that processes input
1703 // to form a ProtoJson document/tree
1704
1705 // This consumes all of the input provided with the following return values:
1706 // 1) PARSE_ERROR indicating a JSON syntax error (or memory allocation error)
1707 // 2) PARSE_MORE indicating more input is needed to have a complete, valid JSON document
1708 // 3) PARSE_DONE indicating a completed JSON document/stanza
1709 ProtoJson::Parser::Status ProtoJson::Parser::ProcessInput(const char* inputBuffer, unsigned int inputLength)
1710 {
1711 if (NULL == current_document)
1712 {
1713 if (NULL == (current_document = new Document()))
1714 {
1715 PLOG(PL_ERROR, "ProtoJson::Parser::ProcessInput() new document error: %s\n", GetErrorString());
1716 return PARSE_ERROR;
1717 }
1718 }
1719 // Top level call to process some JSON input
1720 Status result = PARSE_MORE;
1721 input_offset = 0;
1722 while (input_offset < inputLength)
1723 {
1724 //ProtoCheckLogAllocations(stdout);
1725 const char* input = inputBuffer + input_offset;
1726 unsigned int length = inputLength - input_offset;
1727 // TBD - should we pop the stack down in the lower parser layers instead?
1728 if (NULL == current_item) current_item = PopStack();
1729 if (NULL == current_item)
1730 {
1731 bool NONE = true;
1732 result = PARSE_DONE; // default result for NONE document
1733 // Seeking top level item
1734 for (unsigned int i = 0; i < length; i++)
1735 {
1736 char c = input[i];
1737 // Skip white space
1738 if (isspace(c)) continue;
1739 switch (c)
1740 {
1741 case ARRAY_START:
1742 {
1743 // consume skipped white space + ARRAY_START
1744 NONE = false;
1745 input_offset += (i + 1);
1746 unsigned int remainder = (length > i) ? length - (i+1) : 0;
1747 result = ProcessArrayInput(input + (i + 1), remainder);
1748 break;
1749 }
1750 case OBJECT_START:
1751 {
1752 // consume skipped white space + OBJECT_START
1753 NONE = false;
1754 input_offset += (i + 1);
1755 unsigned int remainder = (length > i) ? length - (i+1) : 0;
1756 result = ProcessObjectInput(input + (i + 1), remainder);
1757 break;
1758 }
1759 case QUOTE:
1760 {
1761 // consume skipped white space + QUOTE
1762 NONE = false;
1763 input_offset += (i + 1);
1764 unsigned int remainder = (length > i) ? length - (i+1) : 0;
1765 result = ProcessStringInput(input + (i + 1), remainder);
1766 break;
1767 }
1768 case TRUE_START:
1769 case FALSE_START:
1770 case NULL_START:
1771 {
1772 NONE = false;
1773 input_offset += i;
1774 unsigned int remainder = (length > i) ? length - i : 0;
1775 result = ProcessFixedInput(input + i, remainder);
1776 break;
1777 }
1778 default:
1779 {
1780 if (0 == isdigit(c))
1781 return PARSE_ERROR; // invalid input at top level
1782 NONE = false;
1783 input_offset += i;
1784 unsigned int remainder = (length > i) ? length - i : 0;
1785 result = ProcessNumberInput(input + i, remainder);
1786 break;
1787 }
1788
1789 }
1790 break; // an increment of non-whitespace parsing occurred
1791 }
1792 if (NONE) input_offset += length; // consumes skipped white space
1793 if (PARSE_ERROR == result) break;
1794 }
1795 else
1796 {
1797 switch (current_item->GetType())
1798 {
1799 case Item::ENTRY:
1800 result = ProcessEntryInput(input, length);
1801 break;
1802 case Item::STRING:
1803 result = ProcessStringInput(input, length);
1804 break;
1805 case Item::NUMBER:
1806 result = ProcessNumberInput(input, length);
1807 break;
1808 case Item::OBJECT:
1809 result = ProcessObjectInput(input, length);
1810 break;
1811 case Item::ARRAY:
1812 result = ProcessArrayInput(input, length);
1813 break;
1814 default:
1815 result = ProcessFixedInput(input, length);
1816 break;
1817 }
1818 if (PARSE_ERROR == result) break;
1819 //ASSERT ((result != PARSE_MORE) || (input_offset < inputLength));
1820 }
1821 } // end while (length > 0)
1822 if (PARSE_DONE == result)
1823 {
1824 // Only really "DONE" if no pending current_item or stack, else need more input
1825 if ((NULL != current_item) || (NULL != PeekStack()))
1826 return PARSE_MORE; // more input needed
1827 else
1828 return PARSE_DONE;
1829 }
1830 else
1831 {
1832 return result;
1833 }
1834 } // end ProtoJson::Parser::ProcessInput()
1835
1836
1837