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