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