]> git.netwichtig.de Git - user/henk/code/inspircd.git/blob - src/modules/m_rpc_json.cpp
6d9b024f9cf57bbc6915ebdab265dc5a92b98e34
[user/henk/code/inspircd.git] / src / modules / m_rpc_json.cpp
1 /*       +------------------------------------+
2  *       | Inspire Internet Relay Chat Daemon |
3  *       +------------------------------------+
4  *
5  *  InspIRCd: (C) 2002-2007 InspIRCd Development Team
6  * See: http://www.inspircd.org/wiki/index.php/Credits
7  *
8  * This program is free but copyrighted software; see
9  *          the file COPYING for details.
10  *
11  * ---------------------------------------------------
12  */
13
14 #include <cstddef>
15 #include <cstdio>
16 #include <iostream>
17 #include <stdexcept>
18 #include <utility>
19
20 #include "inspircd.h"
21 #include "users.h"
22 #include "channels.h"
23 #include "configreader.h"
24 #include "modules.h"
25 #include "inspsocket.h"
26 #include "httpd.h"
27 #include "json.h"
28
29 /* $ModDesc: Provides a JSON-RPC interface for modules using m_httpd.so */
30
31 class ModuleRpcJson : public Module
32 {
33  public:
34         ModuleRpcJson(InspIRCd* Me) : Module(Me)
35         {
36                 json::rpc::init ();
37         }
38
39         void OnEvent(Event* event)
40         {
41                 std::stringstream data("");
42
43                 if (event->GetEventID() == "httpd_url")
44                 {
45                         HTTPRequest* http = (HTTPRequest*)event->GetData();
46
47                         if (http->GetURI() == "/jsonrpc" && http->GetType() == "POST")
48                         {
49                                 std::string response_text;
50                                 json::rpc::process (http, response_text, http->GetPostData().c_str());
51                                 data << response_text;
52
53                                 /* Send the document back to m_httpd */
54                                 HTTPDocument response(http->sock, &data, 200, "X-Powered-By: m_rpc_json.so\r\n"
55                                                                               "Content-Type: application/json; charset=iso-8859-1\r\n");
56                                 Request req((char*)&response, (Module*)this, event->GetSource());
57                                 req.Send();
58                         }
59                 }
60         }
61
62         void Implements(char* List)
63         {
64                 List[I_OnEvent] = 1;
65         }
66
67         virtual ~ModuleRpcJson()
68         {
69         }
70
71         virtual Version GetVersion()
72         {
73                 return Version(0, 1, 0, 0, VF_VENDOR, API_VERSION);
74         }
75 };
76
77 static void
78 unreachable_internal (char const *file, int line, char const *function)
79 {
80   char buf[1024];
81   snprintf (buf, 1024, "%s (%d) [%s] critical: Unreachable line reached.",
82             file, line, function);
83
84   throw std::runtime_error (buf);
85 }
86
87 static void
88 throw_unless_internal (char const *file, int line, char const *function, char const *condition)
89 {
90   char buf[1024];
91   snprintf (buf, 1024, "%s (%d) [%s] critical: Assertion `%s' failed.",
92             file, line, function, condition);
93
94   throw std::runtime_error (buf);
95 }
96
97 static void
98 throw_msg_unless_internal (char const *file, int line, char const *function, char const *message)
99 {
100   char buf[1024];
101   snprintf (buf, 1024, "%s (%d) [%s] critical: %s.",
102             file, line, function, message);
103
104   throw std::runtime_error (buf);
105 }
106
107
108 namespace json
109 {
110   ValueIteratorBase::ValueIteratorBase ()
111   {
112   }
113
114
115   ValueIteratorBase::ValueIteratorBase (const Value::ObjectValues::iterator &current)
116     : current_ (current)
117   {
118   }
119
120   Value &
121   ValueIteratorBase::deref () const
122   {
123     return current_->second;
124   }
125
126
127   void 
128   ValueIteratorBase::increment ()
129   {
130     ++current_;
131   }
132
133
134   void 
135   ValueIteratorBase::decrement ()
136   {
137     --current_;
138   }
139
140
141   ValueIteratorBase::difference_type 
142   ValueIteratorBase::computeDistance (const SelfType &other) const
143   {
144     return difference_type (std::distance (current_, other.current_));
145   }
146
147
148   bool 
149   ValueIteratorBase::isEqual (const SelfType &other) const
150   {
151     return current_ == other.current_;
152   }
153
154
155   void 
156   ValueIteratorBase::copy (const SelfType &other)
157   {
158     current_ = other.current_;
159   }
160
161
162   Value 
163   ValueIteratorBase::key () const
164   {
165     const Value::CZString czstring = (*current_).first;
166     if (czstring.c_str ())
167       {
168         if (czstring.isStaticString ())
169           return Value (StaticString (czstring.c_str ()));
170         return Value (czstring.c_str ());
171       }
172     return Value (czstring.index ());
173   }
174
175
176   unsigned 
177   ValueIteratorBase::index () const
178   {
179     const Value::CZString czstring = (*current_).first;
180     if (!czstring.c_str ())
181       return czstring.index ();
182     return unsigned (-1);
183   }
184
185
186   char const *
187   ValueIteratorBase::memberName () const
188   {
189     char const *name = (*current_).first.c_str ();
190     return name ? name : "";
191   }
192
193
194   ValueConstIterator::ValueConstIterator ()
195   {
196   }
197
198
199   ValueConstIterator::ValueConstIterator (const Value::ObjectValues::iterator &current)
200     : ValueIteratorBase (current)
201   {
202   }
203
204   ValueConstIterator &
205   ValueConstIterator::operator = (const ValueIteratorBase &other)
206   {
207     copy (other);
208     return *this;
209   }
210
211
212   ValueIterator::ValueIterator ()
213   {
214   }
215
216
217   ValueIterator::ValueIterator (const Value::ObjectValues::iterator &current)
218     : ValueIteratorBase (current)
219   {
220   }
221
222   ValueIterator::ValueIterator (const ValueConstIterator &other)
223     : ValueIteratorBase (other)
224   {
225   }
226
227   ValueIterator::ValueIterator (const ValueIterator &other)
228     : ValueIteratorBase (other)
229   {
230   }
231
232   ValueIterator &
233   ValueIterator::operator = (const SelfType &other)
234   {
235     copy (other);
236     return *this;
237   }
238 }
239
240 namespace json
241 {
242   inline bool 
243   in (char c, char c1, char c2, char c3, char c4)
244   {
245     return c == c1 || c == c2 || c == c3 || c == c4;
246   }
247
248   inline bool 
249   in (char c, char c1, char c2, char c3, char c4, char c5)
250   {
251     return c == c1 || c == c2 || c == c3 || c == c4 || c == c5;
252   }
253
254
255   Reader::Reader ()
256   {
257   }
258
259   bool
260   Reader::parse (const std::string &document, 
261                  Value &root)
262   {
263     document_ = document;
264     char const *begin = document_.c_str ();
265     char const *end = begin + document_.length ();
266     return parse (begin, end, root);
267   }
268
269   bool
270   Reader::parse (std::istream& sin,
271                  Value &root)
272   {
273     std::string doc;
274     std::getline (sin, doc, (char)EOF);
275     return parse (doc, root);
276   }
277
278   bool 
279   Reader::parse (char const *beginDoc, char const *endDOc, 
280                  Value &root)
281   {
282     begin_ = beginDoc;
283     end_ = endDOc;
284     current_ = begin_;
285     lastValueEnd_ = 0;
286     lastValue_ = 0;
287     errors_.clear ();
288     while (!nodes_.empty ())
289       nodes_.pop ();
290     nodes_.push (&root);
291    
292     bool successful = readValue ();
293     return successful;
294   }
295
296
297   bool
298   Reader::readValue ()
299   {
300     Token token;
301     do
302       readToken (token);
303     while (token.type_ == tokenComment);
304     bool successful = true;
305
306     switch (token.type_)
307       {
308       case tokenObjectBegin:
309         successful = readObject ();
310         break;
311       case tokenArrayBegin:
312         successful = readArray ();
313         break;
314       case tokenNumber:
315         successful = decodeNumber (token);
316         break;
317       case tokenString:
318         successful = decodeString (token);
319         break;
320       case tokenTrue:
321         currentValue () = true;
322         break;
323       case tokenFalse:
324         currentValue () = false;
325         break;
326       case tokenNull:
327         currentValue () = Value ();
328         break;
329       default:
330         return addError ("Syntax error: value, object or array expected.", token);
331       }
332
333     return successful;
334   }
335
336
337   bool 
338   Reader::expectToken (TokenType type, Token &token, char const *message)
339   {
340     readToken (token);
341     if (token.type_ != type)
342       return addError (message, token);
343     return true;
344   }
345
346
347   bool 
348   Reader::readToken (Token &token)
349   {
350     skipSpaces ();
351     token.start_ = current_;
352     char c = getNextChar ();
353     bool ok = true;
354     switch (c)
355       {
356       case '{':
357         token.type_ = tokenObjectBegin;
358         break;
359       case '}':
360         token.type_ = tokenObjectEnd;
361         break;
362       case '[':
363         token.type_ = tokenArrayBegin;
364         break;
365       case ']':
366         token.type_ = tokenArrayEnd;
367         break;
368       case '"':
369         token.type_ = tokenString;
370         ok = readString ();
371         break;
372 #if 0
373 #ifdef __GNUC__
374       case '0'...'9':
375 #endif
376 #else
377       case '0': case '1': case '2': case '3':
378       case '4': case '5': case '6': case '7':
379       case '8': case '9':
380 #endif
381       case '-':
382         token.type_ = tokenNumber;
383         readNumber ();
384         break;
385       case 't':
386         token.type_ = tokenTrue;
387         ok = match ("rue", 3);
388         break;
389       case 'f':
390         token.type_ = tokenFalse;
391         ok = match ("alse", 4);
392         break;
393       case 'n':
394         token.type_ = tokenNull;
395         ok = match ("ull", 3);
396         break;
397       case ',':
398         token.type_ = tokenArraySeparator;
399         break;
400       case ':':
401         token.type_ = tokenMemberSeparator;
402         break;
403       case 0:
404         token.type_ = tokenEndOfStream;
405         break;
406       default:
407         ok = false;
408         break;
409       }
410     if (!ok)
411       token.type_ = tokenError;
412     token.end_ = current_;
413     return true;
414   }
415
416
417   void 
418   Reader::skipSpaces ()
419   {
420     while (current_ != end_)
421       {
422         char c = *current_;
423         if (c == ' ' || c == '\t' || c == '\r' || c == '\n')
424           ++current_;
425         else
426           break;
427       }
428   }
429
430
431   bool 
432   Reader::match (Location pattern, int patternLength)
433   {
434     if (end_ - current_ < patternLength)
435       return false;
436     int index = patternLength;
437     while (index--)
438       if (current_[index] != pattern[index])
439         return false;
440     current_ += patternLength;
441     return true;
442   }
443
444
445   void 
446   Reader::readNumber ()
447   {
448     while (current_ != end_)
449       {
450         if (!(*current_ >= '0' && *current_ <= '9')  &&
451              !in (*current_, '.', 'e', 'E', '+', '-'))
452           break;
453         ++current_;
454       }
455   }
456
457   bool
458   Reader::readString ()
459   {
460     char c = 0;
461     while (current_ != end_)
462       {
463         c = getNextChar ();
464         if (c == '\\')
465           getNextChar ();
466         else if (c == '"')
467           break;
468       }
469     return c == '"';
470   }
471
472
473   bool 
474   Reader::readObject ()
475   {
476     Token tokenName;
477     std::string name;
478     currentValue () = Value (objectValue);
479     while (readToken (tokenName))
480       {
481         if (tokenName.type_ == tokenObjectEnd && name.empty ())  // empty object
482           return true;
483         if (tokenName.type_ != tokenString)
484           break;
485       
486         name = "";
487         if (!decodeString (tokenName, name))
488           return recoverFromError (tokenObjectEnd);
489
490         Token colon;
491         if (!readToken (colon) ||  colon.type_ != tokenMemberSeparator)
492           {
493             return addErrorAndRecover ("Missing ':' after object member name", 
494                                        colon, 
495                                        tokenObjectEnd);
496           }
497         Value &value = currentValue ()[ name ];
498         nodes_.push (&value);
499         bool ok = readValue ();
500         nodes_.pop ();
501         if (!ok) // error already set
502           return recoverFromError (tokenObjectEnd);
503
504         Token comma;
505         if (!readToken (comma)
506              ||   (comma.type_ != tokenObjectEnd && 
507                    comma.type_ != tokenArraySeparator))
508           {
509             return addErrorAndRecover ("Missing ',' or '}' in object declaration", 
510                                        comma, 
511                                        tokenObjectEnd);
512           }
513         if (comma.type_ == tokenObjectEnd)
514           return true;
515       }
516     return addErrorAndRecover ("Missing '}' or object member name", 
517                                tokenName, 
518                                tokenObjectEnd);
519   }
520
521
522   bool 
523   Reader::readArray ()
524   {
525     currentValue () = Value (arrayValue);
526     skipSpaces ();
527     if (*current_ == ']') // empty array
528       {
529         Token endArray;
530         readToken (endArray);
531         return true;
532       }
533     int index = 0;
534     while (true)
535       {
536         Value &value = currentValue ()[ index++ ];
537         nodes_.push (&value);
538         bool ok = readValue ();
539         nodes_.pop ();
540         if (!ok) // error already set
541           return recoverFromError (tokenArrayEnd);
542
543         Token token;
544         if (!readToken (token) 
545              ||   (token.type_ != tokenArraySeparator && 
546                    token.type_ != tokenArrayEnd))
547           {
548             return addErrorAndRecover ("Missing ',' or ']' in array declaration", 
549                                        token, 
550                                        tokenArrayEnd);
551           }
552         if (token.type_ == tokenArrayEnd)
553           break;
554       }
555     return true;
556   }
557
558
559   bool 
560   Reader::decodeNumber (Token &token)
561   {
562     bool isDouble = false;
563     for (Location inspect = token.start_; inspect != token.end_; ++inspect)
564       {
565         isDouble = isDouble  
566           ||  in (*inspect, '.', 'e', 'E', '+')  
567           ||   (*inspect == '-' && inspect != token.start_);
568       }
569     if (isDouble)
570       return decodeDouble (token);
571     Location current = token.start_;
572     bool isNegative = *current == '-';
573     if (isNegative)
574       ++current;
575     unsigned threshold = (isNegative ? unsigned (-Value::minInt) 
576                              : Value::maxUInt) / 10;
577     unsigned value = 0;
578     while (current < token.end_)
579       {
580         char c = *current++;
581         if (c < '0'  ||  c > '9')
582           return addError ("'" + std::string (token.start_, token.end_) + "' is not a number.", token);
583         if (value >= threshold)
584           return decodeDouble (token);
585         value = value * 10 + unsigned (c - '0');
586       }
587     if (isNegative)
588       currentValue () = -int (value);
589     else if (value <= unsigned (Value::maxInt))
590       currentValue () = int (value);
591     else
592       currentValue () = value;
593     return true;
594   }
595
596
597   bool 
598   Reader::decodeDouble (Token &token)
599   {
600     double value = 0;
601     const int bufferSize = 32;
602     int count;
603     int length = int (token.end_ - token.start_);
604     if (length <= bufferSize)
605       {
606         char buffer[bufferSize];
607         memcpy (buffer, token.start_, length);
608         buffer[length] = 0;
609         count = sscanf (buffer, "%lf", &value);
610       }
611     else
612       {
613         std::string buffer (token.start_, token.end_);
614         count = sscanf (buffer.c_str (), "%lf", &value);
615       }
616
617     if (count != 1)
618       return addError ("'" + std::string (token.start_, token.end_) + "' is not a number.", token);
619     currentValue () = value;
620     return true;
621   }
622
623
624   bool 
625   Reader::decodeString (Token &token)
626   {
627     std::string decoded;
628     if (!decodeString (token, decoded))
629       return false;
630     currentValue () = decoded;
631     return true;
632   }
633
634
635   bool 
636   Reader::decodeString (Token &token, std::string &decoded)
637   {
638     Location current = token.start_ + 1; // skip '"'
639     Location end = token.end_ - 1;       // do not include '"'
640     decoded.reserve (long (end - current));
641
642     while (current != end)
643       {
644         char c = *current++;
645         if (expect_false (c == '"'))
646           break;
647         else if (expect_false (c == '\\'))
648           {
649             if (expect_false (current == end))
650               return addError ("Empty escape sequence in string", token, current);
651             char escape = *current++;
652             switch (escape)
653               {
654               case '"':
655               case '/':
656               case '\\': decoded += escape; break;
657
658               case 'b': decoded += '\010'; break;
659               case 't': decoded += '\011'; break;
660               case 'n': decoded += '\012'; break;
661               case 'f': decoded += '\014'; break;
662               case 'r': decoded += '\015'; break;
663               case 'u':
664                 {
665                   unsigned unicode;
666                   if (!decodeUnicodeEscapeSequence (token, current, end, unicode))
667                     return false;
668                   // @todo encode unicode as utf8.
669                   // @todo remember to alter the writer too.
670                 }
671                 break;
672               default:
673                 return addError ("Bad escape sequence in string", token, current);
674               }
675           }
676         else
677           {
678             decoded += c;
679           }
680       }
681
682     return true;
683   }
684
685
686   bool 
687   Reader::decodeUnicodeEscapeSequence (Token &token, 
688                                        Location &current, 
689                                        Location end, 
690                                        unsigned &unicode)
691   {
692     if (end - current < 4)
693       return addError ("Bad unicode escape sequence in string: four digits expected.", token, current);
694     unicode = 0;
695     for (int index = 0; index < 4; ++index)
696       {
697         char c = *current++;
698         unicode *= 16;
699         if (c >= '0' && c <= '9')
700           unicode += c - '0';
701         else if (c >= 'a' && c <= 'f')
702           unicode += c - 'a' + 10;
703         else if (c >= 'A' && c <= 'F')
704           unicode += c - 'A' + 10;
705         else
706           return addError ("Bad unicode escape sequence in string: hexadecimal digit expected.", token, current);
707       }
708     return true;
709   }
710
711
712   bool 
713   Reader::addError (const std::string &message, 
714                     Token &token,
715                     Location extra)
716   {
717     ErrorInfo info;
718     info.token_ = token;
719     info.message_ = message;
720     info.extra_ = extra;
721     errors_.push_back (info);
722     return false;
723   }
724
725
726   bool 
727   Reader::recoverFromError (TokenType skipUntilToken)
728   {
729     int errorCount = int (errors_.size ());
730     Token skip;
731     while (true)
732       {
733         if (!readToken (skip))
734           errors_.resize (errorCount); // discard errors caused by recovery
735         if (skip.type_ == skipUntilToken  ||  skip.type_ == tokenEndOfStream)
736           break;
737       }
738     errors_.resize (errorCount);
739     return false;
740   }
741
742
743   bool 
744   Reader::addErrorAndRecover (const std::string &message, 
745                               Token &token,
746                               TokenType skipUntilToken)
747   {
748     addError (message, token);
749     return recoverFromError (skipUntilToken);
750   }
751
752
753   Value &
754   Reader::currentValue ()
755   {
756     return *(nodes_.top ());
757   }
758
759
760   char 
761   Reader::getNextChar ()
762   {
763     if (current_ == end_)
764       return 0;
765     return *current_++;
766   }
767
768
769   void 
770   Reader::getLocationLineAndColumn (Location location,
771                                     int &line,
772                                     int &column) const
773   {
774     Location current = begin_;
775     Location lastLineStart = current;
776     line = 0;
777     while (current < location && current != end_)
778       {
779         char c = *current++;
780         if (c == '\r')
781           {
782             if (*current == '\n')
783               ++current;
784             lastLineStart = current;
785             ++line;
786           }
787         else if (c == '\n')
788           {
789             lastLineStart = current;
790             ++line;
791           }
792       }
793     // column & line start at 1
794     column = int (location - lastLineStart) + 1;
795     ++line;
796   }
797
798
799   std::string
800   Reader::getLocationLineAndColumn (Location location) const
801   {
802     int line, column;
803     getLocationLineAndColumn (location, line, column);
804     char buffer[18+16+16+1];
805     sprintf (buffer, "Line %d, Column %d", line, column);
806     return buffer;
807   }
808
809
810   std::string 
811   Reader::error_msgs () const
812   {
813     std::string formattedMessage;
814     for (Errors::const_iterator itError = errors_.begin ();
815           itError != errors_.end ();
816           ++itError)
817       {
818         const ErrorInfo &error = *itError;
819         formattedMessage += "* " + getLocationLineAndColumn (error.token_.start_) + "\n";
820         formattedMessage += "  " + error.message_ + "\n";
821         if (error.extra_)
822           formattedMessage += "See " + getLocationLineAndColumn (error.extra_) + " for detail.\n";
823       }
824     return formattedMessage;
825   }
826 } // namespace json
827
828 namespace json
829 {
830   void
831   unreachable_internal (char const *file, int line, char const *function)
832   {
833     char buf[1024];
834     snprintf (buf, 1024, "%s (%d) [%s] critical: Unreachable line reached.",
835               file, line, function);
836   
837     throw std::runtime_error (buf);
838   }
839   
840   void
841   throw_unless_internal (char const *file, int line, char const *function, char const *condition)
842   {
843     char buf[1024];
844     snprintf (buf, 1024, "%s (%d) [%s] critical: Assertion `%s' failed.",
845               file, line, function, condition);
846   
847     throw std::runtime_error (buf);
848   }
849   
850   void
851   throw_msg_unless_internal (char const *file, int line, char const *function, char const *message)
852   {
853     char buf[1024];
854     snprintf (buf, 1024, "%s (%d) [%s] critical: %s.",
855               file, line, function, message);
856   
857     throw std::runtime_error (buf);
858   }
859   
860   const Value Value::null;
861   const int Value::minInt = int (~ (unsigned (-1)/2));
862   const int Value::maxInt = int (unsigned (-1)/2);
863   const unsigned Value::maxUInt = unsigned (-1);
864
865   ValueAllocator::~ValueAllocator ()
866   {
867   }
868
869   class DefaultValueAllocator : public ValueAllocator
870   {
871   public:
872     virtual ~DefaultValueAllocator ()
873     {
874     }
875
876     virtual char *makeMemberName (char const *memberName)
877     {
878       return duplicateStringValue (memberName);
879     }
880
881     virtual void releaseMemberName (char *memberName)
882     {
883       releaseStringValue (memberName);
884     }
885
886     virtual char *duplicateStringValue (char const *value, unsigned length = unknown)
887     {
888       //@todo invesgate this old optimization
889 #if 0
890       if (!value || value[0] == 0)
891         return 0;
892 #endif
893
894       if (length == unknown)
895         length = (unsigned)strlen (value);
896       char *newString = static_cast<char *> (malloc (length + 1));
897       memcpy (newString, value, length);
898       newString[length] = 0;
899       return newString;
900     }
901
902     virtual void releaseStringValue (char *value)
903     {
904       if (value)
905         free (value);
906     }
907   };
908
909   static ValueAllocator *&valueAllocator ()
910   {
911     static DefaultValueAllocator defaultAllocator;
912     static ValueAllocator *valueAllocator = &defaultAllocator;
913     return valueAllocator;
914   }
915
916   static struct DummyValueAllocatorInitializer {
917     DummyValueAllocatorInitializer () 
918     {
919       valueAllocator ();      // ensure valueAllocator () statics are initialized before main ().
920     }
921   } dummyValueAllocatorInitializer;
922
923
924
925   Value::CZString::CZString (int index)
926     : cstr_ (0)
927     , index_ (index)
928   {
929   }
930
931   Value::CZString::CZString (char const *cstr, DuplicationPolicy allocate)
932     : cstr_ (allocate == duplicate ? valueAllocator()->makeMemberName (cstr) 
933              : cstr)
934     , index_ (allocate)
935   {
936   }
937
938   Value::CZString::CZString (const CZString &other)
939     : cstr_ (other.index_ != noDuplication &&  other.cstr_ != 0
940              ?  valueAllocator()->makeMemberName (other.cstr_)
941              : other.cstr_)
942     , index_ (other.cstr_ ? (other.index_ == noDuplication ? noDuplication : duplicate)
943               : other.index_)
944   {
945   }
946
947   Value::CZString::~CZString ()
948   {
949     if (cstr_ && index_ == duplicate)
950       valueAllocator()->releaseMemberName (const_cast<char *> (cstr_));
951   }
952
953   void 
954   Value::CZString::swap (CZString &other)
955   {
956     std::swap (cstr_, other.cstr_);
957     std::swap (index_, other.index_);
958   }
959
960   Value::CZString &
961   Value::CZString::operator = (const CZString &other)
962   {
963     CZString temp (other);
964     swap (temp);
965     return *this;
966   }
967
968   bool 
969   Value::CZString::operator < (const CZString &other) const 
970   {
971     if (cstr_)
972       return strcmp (cstr_, other.cstr_) < 0;
973     return index_ < other.index_;
974   }
975
976   bool 
977   Value::CZString::operator == (const CZString &other) const 
978   {
979     if (cstr_)
980       return strcmp (cstr_, other.cstr_) == 0;
981     return index_ == other.index_;
982   }
983
984
985   int 
986   Value::CZString::index () const
987   {
988     return index_;
989   }
990
991
992   char const *
993   Value::CZString::c_str () const
994   {
995     return cstr_;
996   }
997
998   bool 
999   Value::CZString::isStaticString () const
1000   {
1001     return index_ == noDuplication;
1002   }
1003
1004
1005   // class Value::Value
1006
1007   Value::Value (ValueType type)
1008     : type_ (type)
1009     , allocated_ (0)
1010   {
1011     switch (type)
1012       {
1013       case nullValue:
1014         break;
1015       case intValue:
1016       case uintValue:
1017         value_.int_ = 0;
1018         break;
1019       case realValue:
1020         value_.real_ = 0.0;
1021         break;
1022       case stringValue:
1023         value_.string_ = 0;
1024         break;
1025       case arrayValue:
1026       case objectValue:
1027         value_.map_ = new ObjectValues ();
1028         break;
1029       case booleanValue:
1030         value_.bool_ = false;
1031         break;
1032       default:
1033         throw_unreachable;
1034       }
1035   }
1036
1037
1038   Value::Value (int value)
1039     : type_ (intValue)
1040   {
1041     value_.int_ = value;
1042   }
1043
1044
1045   Value::Value (unsigned value)
1046     : type_ (uintValue)
1047   {
1048     value_.uint_ = value;
1049   }
1050
1051   Value::Value (double value)
1052     : type_ (realValue)
1053   {
1054     value_.real_ = value;
1055   }
1056
1057   Value::Value (char const *value)
1058     : type_ (stringValue)
1059     , allocated_ (true)
1060   {
1061     value_.string_ = valueAllocator()->duplicateStringValue (value);
1062   }
1063
1064   Value::Value (const std::string &value)
1065     : type_ (stringValue)
1066     , allocated_ (true)
1067   {
1068     value_.string_ = valueAllocator()->duplicateStringValue (value.c_str (), (unsigned)value.length ());
1069   }
1070
1071   Value::Value (const StaticString &value)
1072     : type_ (stringValue)
1073     , allocated_ (false)
1074   {
1075     value_.string_ = const_cast<char *> (value.c_str ());
1076   }
1077
1078
1079   Value::Value (bool value)
1080     : type_ (booleanValue)
1081   {
1082     value_.bool_ = value;
1083   }
1084
1085
1086   Value::Value (const Value &other)
1087     : type_ (other.type_)
1088   {
1089     switch (type_)
1090       {
1091       case nullValue:
1092       case intValue:
1093       case uintValue:
1094       case realValue:
1095       case booleanValue:
1096         value_ = other.value_;
1097         break;
1098       case stringValue:
1099         if (other.value_.string_)
1100           {
1101             value_.string_ = valueAllocator()->duplicateStringValue (other.value_.string_);
1102             allocated_ = true;
1103           }
1104         else
1105           value_.string_ = 0;
1106         break;
1107       case arrayValue:
1108       case objectValue:
1109         value_.map_ = new ObjectValues (*other.value_.map_);
1110         break;
1111       default:
1112         throw_unreachable;
1113       }
1114   }
1115
1116
1117   Value::~Value ()
1118   {
1119     switch (type_)
1120       {
1121       case nullValue:
1122       case intValue:
1123       case uintValue:
1124       case realValue:
1125       case booleanValue:
1126         break;
1127       case stringValue:
1128         if (allocated_)
1129           valueAllocator()->releaseStringValue (value_.string_);
1130         break;
1131       case arrayValue:
1132       case objectValue:
1133         delete value_.map_;
1134         break;
1135       default:
1136         throw_unreachable;
1137       }
1138   }
1139
1140   Value &
1141   Value::operator = (const Value &other)
1142   {
1143     Value temp (other);
1144     swap (temp);
1145     return *this;
1146   }
1147
1148   void 
1149   Value::swap (Value &other)
1150   {
1151     ValueType temp = type_;
1152     type_ = other.type_;
1153     other.type_ = temp;
1154     std::swap (value_, other.value_);
1155     int temp2 = allocated_;
1156     allocated_ = other.allocated_;
1157     other.allocated_ = temp2;
1158   }
1159
1160   ValueType 
1161   Value::type () const
1162   {
1163     return type_;
1164   }
1165
1166   bool 
1167   Value::operator < (const Value &other) const
1168   {
1169     int typeDelta = type_ - other.type_;
1170     if (typeDelta)
1171       return typeDelta < 0 ? true : false;
1172     switch (type_)
1173       {
1174       case nullValue:
1175         return false;
1176       case intValue:
1177         return value_.int_ < other.value_.int_;
1178       case uintValue:
1179         return value_.uint_ < other.value_.uint_;
1180       case realValue:
1181         return value_.real_ < other.value_.real_;
1182       case booleanValue:
1183         return value_.bool_ < other.value_.bool_;
1184       case stringValue:
1185         return (value_.string_ == 0 && other.value_.string_)
1186           || (other.value_.string_  
1187               && value_.string_  
1188               && strcmp (value_.string_, other.value_.string_) < 0);
1189       case arrayValue:
1190       case objectValue:
1191         {
1192           int delta = int (value_.map_->size () - other.value_.map_->size ());
1193           if (delta)
1194             return delta < 0;
1195           return (*value_.map_) < (*other.value_.map_);
1196         }
1197       default:
1198         throw_unreachable;
1199       }
1200     return 0;  // unreachable
1201   }
1202
1203   bool 
1204   Value::operator <= (const Value &other) const
1205   {
1206     return !(other > *this);
1207   }
1208
1209   bool 
1210   Value::operator >= (const Value &other) const
1211   {
1212     return !(*this < other);
1213   }
1214
1215   bool 
1216   Value::operator > (const Value &other) const
1217   {
1218     return other < *this;
1219   }
1220
1221   bool 
1222   Value::operator == (const Value &other) const
1223   {
1224     if (type_ != other.type_)
1225       return false;
1226
1227     switch (type_)
1228       {
1229       case nullValue:
1230         return true;
1231       case intValue:
1232         return value_.int_ == other.value_.int_;
1233       case uintValue:
1234         return value_.uint_ == other.value_.uint_;
1235       case realValue:
1236         return value_.real_ == other.value_.real_;
1237       case booleanValue:
1238         return value_.bool_ == other.value_.bool_;
1239       case stringValue:
1240         return (value_.string_ == other.value_.string_)
1241           || (other.value_.string_  
1242               && value_.string_  
1243               && strcmp (value_.string_, other.value_.string_) == 0);
1244       case arrayValue:
1245       case objectValue:
1246         return value_.map_->size () == other.value_.map_->size ()
1247           && (*value_.map_) == (*other.value_.map_);
1248       default:
1249         throw_unreachable;
1250       }
1251     return 0;  // unreachable
1252   }
1253
1254   bool 
1255   Value::operator != (const Value &other) const
1256   {
1257     return !(*this == other);
1258   }
1259
1260   Value::operator char const * () const
1261   {
1262     throw_unless (type_ == stringValue);
1263     return value_.string_;
1264   }
1265
1266
1267   Value::operator std::string () const
1268   {
1269     switch (type_)
1270       {
1271       case nullValue:
1272         return "";
1273       case stringValue:
1274         return value_.string_ ? value_.string_ : "";
1275       case booleanValue:
1276         return value_.bool_ ? "true" : "false";
1277       case intValue:
1278       case uintValue:
1279       case realValue:
1280       case arrayValue:
1281       case objectValue:
1282         throw_msg_unless (false, "Type is not convertible to string");
1283       default:
1284         throw_unreachable;
1285       }
1286     return ""; // unreachable
1287   }
1288
1289   Value::operator int () const
1290   {
1291     switch (type_)
1292       {
1293       case nullValue:
1294         return 0;
1295       case intValue:
1296         return value_.int_;
1297       case uintValue:
1298         throw_msg_unless (value_.uint_ < (unsigned)maxInt, "integer out of signed integer range");
1299         return value_.uint_;
1300       case realValue:
1301         throw_msg_unless (value_.real_ >= minInt && value_.real_ <= maxInt, "Real out of signed integer range");
1302         return int (value_.real_);
1303       case booleanValue:
1304         return value_.bool_ ? 1 : 0;
1305       case stringValue:
1306       case arrayValue:
1307       case objectValue:
1308         throw_msg_unless (false, "Type is not convertible to int");
1309       default:
1310         throw_unreachable;
1311       }
1312     return 0; // unreachable;
1313   }
1314
1315   Value::operator unsigned () const
1316   {
1317     switch (type_)
1318       {
1319       case nullValue:
1320         return 0;
1321       case intValue:
1322         throw_msg_unless (value_.int_ >= 0, "Negative integer can not be converted to unsigned integer");
1323         return value_.int_;
1324       case uintValue:
1325         return value_.uint_;
1326       case realValue:
1327         throw_msg_unless (value_.real_ >= 0 && value_.real_ <= maxUInt,  "Real out of unsigned integer range");
1328         return unsigned (value_.real_);
1329       case booleanValue:
1330         return value_.bool_ ? 1 : 0;
1331       case stringValue:
1332       case arrayValue:
1333       case objectValue:
1334         throw_msg_unless (false, "Type is not convertible to uint");
1335       default:
1336         throw_unreachable;
1337       }
1338     return 0; // unreachable;
1339   }
1340
1341   Value::operator double () const
1342   {
1343     switch (type_)
1344       {
1345       case nullValue:
1346         return 0.0;
1347       case intValue:
1348         return value_.int_;
1349       case uintValue:
1350         return value_.uint_;
1351       case realValue:
1352         return value_.real_;
1353       case booleanValue:
1354         return value_.bool_ ? 1.0 : 0.0;
1355       case stringValue:
1356       case arrayValue:
1357       case objectValue:
1358         throw_msg_unless (false, "Type is not convertible to double");
1359       default:
1360         throw_unreachable;
1361       }
1362     return 0; // unreachable;
1363   }
1364
1365   Value::operator bool () const
1366   {
1367     switch (type_)
1368       {
1369       case nullValue:
1370         return false;
1371       case intValue:
1372       case uintValue:
1373         return value_.int_ != 0;
1374       case realValue:
1375         return value_.real_ != 0.0;
1376       case booleanValue:
1377         return value_.bool_;
1378       case stringValue:
1379         return value_.string_ && value_.string_[0] != 0;
1380       case arrayValue:
1381       case objectValue:
1382         return value_.map_->size () != 0;
1383       default:
1384         throw_unreachable;
1385       }
1386     return false; // unreachable;
1387   }
1388
1389
1390   bool 
1391   Value::isConvertibleTo (ValueType other) const
1392   {
1393     switch (type_)
1394       {
1395       case nullValue:
1396         return true;
1397       case intValue:
1398         return (other == nullValue && value_.int_ == 0)
1399           || other == intValue
1400           || (other == uintValue  && value_.int_ >= 0)
1401           || other == realValue
1402           || other == stringValue
1403           || other == booleanValue;
1404       case uintValue:
1405         return (other == nullValue && value_.uint_ == 0)
1406           || (other == intValue  && value_.uint_ <= (unsigned)maxInt)
1407           || other == uintValue
1408           || other == realValue
1409           || other == stringValue
1410           || other == booleanValue;
1411       case realValue:
1412         return (other == nullValue && value_.real_ == 0.0)
1413           || (other == intValue && value_.real_ >= minInt && value_.real_ <= maxInt)
1414           || (other == uintValue && value_.real_ >= 0 && value_.real_ <= maxUInt)
1415           || other == realValue
1416           || other == stringValue
1417           || other == booleanValue;
1418       case booleanValue:
1419         return (other == nullValue && value_.bool_ == false)
1420           || other == intValue
1421           || other == uintValue
1422           || other == realValue
1423           || other == stringValue
1424           || other == booleanValue;
1425       case stringValue:
1426         return other == stringValue
1427           || (other == nullValue && (!value_.string_ || value_.string_[0] == 0));
1428       case arrayValue:
1429         return other == arrayValue
1430           || (other == nullValue && value_.map_->size () == 0);
1431       case objectValue:
1432         return other == objectValue
1433           || (other == nullValue && value_.map_->size () == 0);
1434       default:
1435         throw_unreachable;
1436       }
1437     return false; // unreachable;
1438   }
1439
1440
1441   /// Number of values in array or object
1442   unsigned 
1443   Value::size () const
1444   {
1445     switch (type_)
1446       {
1447       case nullValue:
1448       case intValue:
1449       case uintValue:
1450       case realValue:
1451       case booleanValue:
1452       case stringValue:
1453         return 0;
1454       case arrayValue:  // size of the array is highest index + 1
1455         if (!value_.map_->empty ())
1456           {
1457             ObjectValues::const_iterator itLast = value_.map_->end ();
1458             --itLast;
1459             return itLast->first.index ()+1;
1460           }
1461         return 0;
1462       case objectValue:
1463         return int (value_.map_->size ());
1464       default:
1465         throw_unreachable;
1466       }
1467     return 0; // unreachable;
1468   }
1469
1470
1471   bool 
1472   Value::empty () const
1473   {
1474     if (isNull () || isArray () || isObject ())
1475       return size () == 0u;
1476     else
1477       return false;
1478   }
1479
1480
1481   bool
1482   Value::operator ! () const
1483   {
1484     return isNull ();
1485   }
1486
1487
1488   void 
1489   Value::clear ()
1490   {
1491     throw_unless (type_ == nullValue || type_ == arrayValue  || type_ == objectValue);
1492
1493     switch (type_)
1494       {
1495       case arrayValue:
1496       case objectValue:
1497         value_.map_->clear ();
1498         break;
1499       default:
1500         break;
1501       }
1502   }
1503
1504   void 
1505   Value::resize (unsigned newSize)
1506   {
1507     throw_unless (type_ == nullValue || type_ == arrayValue);
1508     if (type_ == nullValue)
1509       *this = Value (arrayValue);
1510     unsigned oldSize = size ();
1511     if (newSize == 0)
1512       clear ();
1513     else if (newSize > oldSize)
1514       (*this)[ newSize - 1 ];
1515     else
1516       {
1517         for (unsigned index = newSize; index < oldSize; ++index)
1518           value_.map_->erase (index);
1519         throw_unless (size () == newSize);
1520       }
1521   }
1522
1523
1524   Value &
1525   Value::operator [] (int index)
1526   {
1527     return operator [] (static_cast<unsigned> (index));
1528   }
1529
1530
1531   Value &
1532   Value::operator [] (unsigned index)
1533   {
1534     throw_unless (type_ == nullValue || type_ == arrayValue);
1535     if (type_ == nullValue)
1536       *this = Value (arrayValue);
1537     CZString key (index);
1538     ObjectValues::iterator it = value_.map_->lower_bound (key);
1539     if (it != value_.map_->end () && it->first == key)
1540       return it->second;
1541
1542     ObjectValues::value_type defaultValue (key, null);
1543     it = value_.map_->insert (it, defaultValue);
1544     return it->second;
1545   }
1546
1547
1548   const Value &
1549   Value::operator [] (int index) const
1550   {
1551     return operator [] (static_cast<unsigned> (index));
1552   }
1553
1554
1555   const Value &
1556   Value::operator [] (unsigned index) const
1557   {
1558     throw_unless (type_ == nullValue || type_ == arrayValue);
1559     if (type_ == nullValue)
1560       return null;
1561     CZString key (index);
1562     ObjectValues::const_iterator it = value_.map_->find (key);
1563     if (it == value_.map_->end ())
1564       return null;
1565     return it->second;
1566   }
1567
1568
1569   Value &
1570   Value::operator [] (char const *key)
1571   {
1572     return resolveReference (key, false);
1573   }
1574
1575
1576   Value &
1577   Value::resolveReference (char const *key, bool isStatic)
1578   {
1579     throw_unless (type_ == nullValue || type_ == objectValue);
1580     if (type_ == nullValue)
1581       *this = Value (objectValue);
1582     CZString actualKey (key, isStatic ? CZString::noDuplication 
1583                         : CZString::duplicateOnCopy);
1584     ObjectValues::iterator it = value_.map_->lower_bound (actualKey);
1585     if (it != value_.map_->end () && it->first == actualKey)
1586       return it->second;
1587
1588     ObjectValues::value_type defaultValue (actualKey, null);
1589     it = value_.map_->insert (it, defaultValue);
1590     Value &value = it->second;
1591     return value;
1592   }
1593
1594
1595   Value 
1596   Value::get (int index, const Value &defaultValue) const
1597   {
1598     return get (static_cast<unsigned> (index), defaultValue);
1599   }
1600
1601
1602   Value 
1603   Value::get (unsigned index, const Value &defaultValue) const
1604   {
1605     const Value *value = &((*this)[index]);
1606     return value == &null ? defaultValue : *value;
1607   }
1608
1609
1610   bool 
1611   Value::isValidIndex (int index) const
1612   {
1613     return isValidIndex (static_cast<unsigned> (index));
1614   }
1615
1616
1617   bool 
1618   Value::isValidIndex (unsigned index) const
1619   {
1620     return index < size ();
1621   }
1622
1623
1624
1625   const Value &
1626   Value::operator [] (char const *key) const
1627   {
1628     throw_unless (type_ == nullValue || type_ == objectValue);
1629     if (type_ == nullValue)
1630       return null;
1631     CZString actualKey (key, CZString::noDuplication);
1632     ObjectValues::const_iterator it = value_.map_->find (actualKey);
1633     if (it == value_.map_->end ())
1634       return null;
1635     return it->second;
1636   }
1637
1638
1639   Value &
1640   Value::operator [] (const std::string &key)
1641   {
1642     return (*this)[ key.c_str () ];
1643   }
1644
1645
1646   const Value &
1647   Value::operator [] (const std::string &key) const
1648   {
1649     return (*this)[ key.c_str () ];
1650   }
1651
1652   Value &
1653   Value::operator [] (const StaticString &key)
1654   {
1655     return resolveReference (key, true);
1656   }
1657
1658
1659   Value &
1660   Value::append (const Value &value)
1661   {
1662     return (*this)[size ()] = value;
1663   }
1664
1665
1666   Value 
1667   Value::get (char const *key, const Value &defaultValue) const
1668   {
1669     const Value *value = &((*this)[key]);
1670     return value == &null ? defaultValue : *value;
1671   }
1672
1673
1674   Value 
1675   Value::get (const std::string &key, const Value &defaultValue) const
1676   {
1677     return get (key.c_str (), defaultValue);
1678   }
1679
1680   Value
1681   Value::removeMember (char const *key)
1682   {
1683     throw_unless (type_ == nullValue || type_ == objectValue);
1684     if (type_ == nullValue)
1685       return null;
1686     CZString actualKey (key, CZString::noDuplication);
1687     ObjectValues::iterator it = value_.map_->find (actualKey);
1688     if (it == value_.map_->end ())
1689       return null;
1690     Value old (it->second);
1691     value_.map_->erase (it);
1692     return old;
1693   }
1694
1695   Value
1696   Value::removeMember (const std::string &key)
1697   {
1698     return removeMember (key.c_str ());
1699   }
1700
1701   bool 
1702   Value::isMember (char const *key) const
1703   {
1704     const Value *value = &((*this)[key]);
1705     return value != &null;
1706   }
1707
1708
1709   bool 
1710   Value::isMember (const std::string &key) const
1711   {
1712     return isMember (key.c_str ());
1713   }
1714
1715
1716   Value::Members 
1717   Value::getMemberNames () const
1718   {
1719     throw_unless (type_ == nullValue || type_ == objectValue);
1720     if (type_ == nullValue)
1721       return Value::Members ();
1722     Members members;
1723     members.reserve (value_.map_->size ());
1724     ObjectValues::const_iterator it;
1725     ObjectValues::const_iterator itEnd = value_.map_->end ();
1726     for (it = value_.map_->begin (); it != itEnd; ++it)
1727       members.push_back (std::string (it->first.c_str()));
1728     return members;
1729   }
1730
1731   bool
1732   Value::isNull () const
1733   {
1734     return type_ == nullValue;
1735   }
1736
1737
1738   bool 
1739   Value::isBool () const
1740   {
1741     return type_ == booleanValue;
1742   }
1743
1744
1745   bool 
1746   Value::isInt () const
1747   {
1748     return type_ == intValue;
1749   }
1750
1751
1752   bool 
1753   Value::isUInt () const
1754   {
1755     return type_ == uintValue;
1756   }
1757
1758
1759   bool 
1760   Value::isIntegral () const
1761   {
1762     return type_ == intValue  
1763       || type_ == uintValue  
1764       || type_ == booleanValue;
1765   }
1766
1767
1768   bool 
1769   Value::isDouble () const
1770   {
1771     return type_ == realValue;
1772   }
1773
1774
1775   bool 
1776   Value::isNumeric () const
1777   {
1778     return isIntegral () || isDouble ();
1779   }
1780
1781
1782   bool 
1783   Value::isString () const
1784   {
1785     return type_ == stringValue;
1786   }
1787
1788
1789   bool 
1790   Value::isArray () const
1791   {
1792     return type_ == nullValue || type_ == arrayValue;
1793   }
1794
1795
1796   bool 
1797   Value::isObject () const
1798   {
1799     return type_ == nullValue || type_ == objectValue;
1800   }
1801
1802
1803   Value::const_iterator 
1804   Value::begin () const
1805   {
1806     switch (type_)
1807       {
1808       case arrayValue:
1809       case objectValue:
1810         if (value_.map_)
1811           return const_iterator (value_.map_->begin ());
1812         break;
1813       default:
1814         break;
1815       }
1816     return const_iterator ();
1817   }
1818
1819   Value::const_iterator 
1820   Value::end () const
1821   {
1822     switch (type_)
1823       {
1824       case arrayValue:
1825       case objectValue:
1826         if (value_.map_)
1827           return const_iterator (value_.map_->end ());
1828         break;
1829       default:
1830         break;
1831       }
1832     return const_iterator ();
1833   }
1834
1835
1836   Value::iterator 
1837   Value::begin ()
1838   {
1839     switch (type_)
1840       {
1841       case arrayValue:
1842       case objectValue:
1843         if (value_.map_)
1844           return iterator (value_.map_->begin ());
1845         break;
1846       default:
1847         break;
1848       }
1849     return iterator ();
1850   }
1851
1852   Value::iterator 
1853   Value::end ()
1854   {
1855     switch (type_)
1856       {
1857       case arrayValue:
1858       case objectValue:
1859         if (value_.map_)
1860           return iterator (value_.map_->end ());
1861         break;
1862       default:
1863         break;
1864       }
1865     return iterator ();
1866   }
1867 } // namespace json
1868
1869 namespace json
1870 {
1871   static void uintToString (unsigned value, 
1872                             char *&current)
1873   {
1874     *--current = 0;
1875     do
1876       {
1877         *--current = (value % 10) + '0';
1878         value /= 10;
1879       }
1880     while (value != 0);
1881   }
1882
1883   std::string valueToString (int value)
1884   {
1885     char buffer[32];
1886     char *current = buffer + sizeof (buffer);
1887     bool isNegative = value < 0;
1888     if (isNegative)
1889       value = -value;
1890     uintToString (unsigned (value), current);
1891     if (isNegative)
1892       *--current = '-';
1893     throw_unless (current >= buffer);
1894     return current;
1895   }
1896
1897
1898   std::string valueToString (unsigned value)
1899   {
1900     char buffer[32];
1901     char *current = buffer + sizeof (buffer);
1902     uintToString (value, current);
1903     throw_unless (current >= buffer);
1904     return current;
1905   }
1906
1907   std::string valueToString (double value)
1908   {
1909     char buffer[32];
1910     sprintf (buffer, "%.16g", value); 
1911     return buffer;
1912   }
1913
1914
1915   std::string valueToString (bool value)
1916   {
1917     return value ? "true" : "false";
1918   }
1919
1920   std::string valueToQuotedString (char const *value)
1921   {
1922     // Not sure how to handle unicode...
1923     if (std::strpbrk (value, "\"\\\b\f\n\r\t") == NULL)
1924       return std::string ("\"") + value + "\"";
1925     // We have to walk value and escape any special characters.
1926     // Appending to std::string is not efficient, but this should be rare.
1927     // (Note: forward slashes are *not* rare, but I am not escaping them.)
1928     unsigned maxsize = strlen (value) * 2 + 3; // allescaped+quotes+NULL
1929     std::string result;
1930     result.reserve (maxsize); // to avoid lots of mallocs
1931     result += "\"";
1932     for (char const* c=value; *c != 0; ++c){
1933       switch (*c){
1934       case '\"':
1935         result += "\\\"";
1936         break;
1937       case '\\':
1938         result += "\\\\";
1939         break;
1940       case '\b':
1941         result += "\\b";
1942         break;
1943       case '\f':
1944         result += "\\f";
1945         break;
1946       case '\n':
1947         result += "\\n";
1948         break;
1949       case '\r':
1950         result += "\\r";
1951         break;
1952       case '\t':
1953         result += "\\t";
1954         break;
1955       case '/':
1956         // Even though \/ is considered a legal escape in JSON, a bare
1957         // slash is also legal, so I see no reason to escape it.
1958         // (I hope I am not misunderstanding something.)
1959       default:
1960         result += *c;
1961       }
1962     }
1963     result += "\"";
1964     return result;
1965   }
1966
1967   // Class Writer
1968   std::string 
1969   Writer::write (const Value &root)
1970   {
1971     document_ = "";
1972     writeValue (root);
1973     document_ += "\n";
1974     return document_;
1975   }
1976
1977
1978   void 
1979   Writer::writeValue (const Value &value)
1980   {
1981     switch (value.type ())
1982       {
1983       case nullValue:
1984         document_ += "null";
1985         break;
1986       case intValue:
1987         document_ += valueToString (static_cast<int> (value));
1988         break;
1989       case uintValue:
1990         document_ += valueToString (static_cast<unsigned> (value));
1991         break;
1992       case realValue:
1993         document_ += valueToString (static_cast<double> (value));
1994         break;
1995       case stringValue:
1996         document_ += valueToQuotedString (static_cast<char const *> (value));
1997         break;
1998       case booleanValue:
1999         document_ += valueToString (static_cast<bool> (value));
2000         break;
2001       case arrayValue:
2002         {
2003           document_ += "[";
2004           int size = value.size ();
2005           for (int index = 0; index < size; ++index)
2006             {
2007               if (index > 0)
2008                 document_ += ",";
2009               writeValue (value[index]);
2010             }
2011           document_ += "]";
2012         }
2013         break;
2014       case objectValue:
2015         {
2016           Value::Members members (value.getMemberNames ());
2017           document_ += "{";
2018           for (Value::Members::iterator it = members.begin (); 
2019                 it != members.end (); 
2020                 ++it)
2021             {
2022               const std::string &name = *it;
2023               if (it != members.begin ())
2024                 document_ += ",";
2025               document_ += valueToQuotedString (name.c_str ());
2026               document_ += ":";
2027               writeValue (value[name]);
2028             }
2029           document_ += "}";
2030         }
2031         break;
2032       }
2033   }
2034 } // namespace json
2035
2036 /**
2037  * RPC
2038  */
2039
2040 namespace json
2041 {
2042   namespace rpc
2043   {
2044     typedef std::map<std::string, void (*) (HTTPRequest *, Value &, Value &)> method_map;
2045   
2046     method_map methods;
2047   
2048     void
2049     add_method (char *name, method mth)
2050     {
2051       methods[name] = mth;
2052     }
2053   
2054     void
2055     system_list_methods (HTTPRequest *http, Value &request, Value &response)
2056     {
2057       unsigned i = 0;
2058       Value method_list (arrayValue);
2059     
2060       method_map::iterator it;
2061       for (it = methods.begin(); it != methods.end(); ++it)
2062         {
2063           method_list[i] = Value (it->first);
2064           i++;
2065         }
2066     
2067       response["result"] = method_list;
2068     }
2069
2070     void
2071     init ()
2072     {
2073       add_method ("system.listMethods", &system_list_methods);
2074     }
2075   
2076     void
2077     service (HTTPRequest *http, Value &request, Value &response)
2078     {
2079       char const *methodName = static_cast<char const *> (request["method"]);
2080       
2081       method_map::iterator mth = methods.find (methodName);
2082       if (mth != methods.end ())
2083         (*mth->second) (http, request, response);
2084     }
2085     
2086     void
2087     process (HTTPRequest *http, std::string &response_text, char const *request_text)
2088     {
2089       std::string text;
2090       bool parse_success;
2091       Value request (objectValue);
2092       Value response (objectValue);
2093       Reader r;
2094       Writer w;
2095   
2096       parse_success = r.parse (request_text, request_text + strlen (request_text), request);
2097   
2098       service (http, request, response);
2099   
2100       text = w.write (response);
2101   
2102       response_text = text.c_str ();
2103   
2104       return;
2105     }
2106   } // namespace rpc
2107 } // namespace json
2108
2109 MODULE_INIT(ModuleRpcJson)