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