JsonCpp project page JsonCpp home page

src/lib_json/json_tool.h

Go to the documentation of this file.
00001 // Copyright 2007-2010 Baptiste Lepilleur
00002 // Distributed under MIT license, or public domain if desired and
00003 // recognized in your jurisdiction.
00004 // See file LICENSE for detail or copy at http://jsoncpp.sourceforge.net/LICENSE
00005 
00006 #ifndef LIB_JSONCPP_JSON_TOOL_H_INCLUDED
00007 #define LIB_JSONCPP_JSON_TOOL_H_INCLUDED
00008 
00009 /* This header provides common string manipulation support, such as UTF-8,
00010  * portable conversion from/to string...
00011  *
00012  * It is an internal header that must not be exposed.
00013  */
00014 
00015 namespace Json {
00016 
00018 static inline std::string codePointToUTF8(unsigned int cp) {
00019   std::string result;
00020 
00021   // based on description from http://en.wikipedia.org/wiki/UTF-8
00022 
00023   if (cp <= 0x7f) {
00024     result.resize(1);
00025     result[0] = static_cast<char>(cp);
00026   } else if (cp <= 0x7FF) {
00027     result.resize(2);
00028     result[1] = static_cast<char>(0x80 | (0x3f & cp));
00029     result[0] = static_cast<char>(0xC0 | (0x1f & (cp >> 6)));
00030   } else if (cp <= 0xFFFF) {
00031     result.resize(3);
00032     result[2] = static_cast<char>(0x80 | (0x3f & cp));
00033     result[1] = 0x80 | static_cast<char>((0x3f & (cp >> 6)));
00034     result[0] = 0xE0 | static_cast<char>((0xf & (cp >> 12)));
00035   } else if (cp <= 0x10FFFF) {
00036     result.resize(4);
00037     result[3] = static_cast<char>(0x80 | (0x3f & cp));
00038     result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
00039     result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
00040     result[0] = static_cast<char>(0xF0 | (0x7 & (cp >> 18)));
00041   }
00042 
00043   return result;
00044 }
00045 
00047 static inline bool isControlCharacter(char ch) { return ch > 0 && ch <= 0x1F; }
00048 
00049 enum {
00052   uintToStringBufferSize = 3 * sizeof(LargestUInt) + 1
00053 };
00054 
00055 // Defines a char buffer for use with uintToString().
00056 typedef char UIntToStringBuffer[uintToStringBufferSize];
00057 
00063 static inline void uintToString(LargestUInt value, char*& current) {
00064   *--current = 0;
00065   do {
00066     *--current = char(value % 10) + '0';
00067     value /= 10;
00068   } while (value != 0);
00069 }
00070 
00076 static inline void fixNumericLocale(char* begin, char* end) {
00077   while (begin < end) {
00078     if (*begin == ',') {
00079       *begin = '.';
00080     }
00081     ++begin;
00082   }
00083 }
00084 
00085 } // namespace Json {
00086 
00087 #endif // LIB_JSONCPP_JSON_TOOL_H_INCLUDED