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