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