| 109 | } |
| 110 | |
| 111 | std::string valueToQuotedString( const char *value ) |
| 112 | { |
| 113 | // Not sure how to handle unicode... |
| 114 | if (strpbrk(value, "\"\\\b\f\n\r\t") == NULL && !containsControlCharacter( value )) |
| 115 | return std::string("\"") + value + "\""; |
| 116 | // We have to walk value and escape any special characters. |
| 117 | // Appending to std::string is not efficient, but this should be rare. |
| 118 | // (Note: forward slashes are *not* rare, but I am not escaping them.) |
| 119 | unsigned maxsize = strlen(value)*2 + 3; // allescaped+quotes+NULL |
| 120 | std::string result; |
| 121 | result.reserve(maxsize); // to avoid lots of mallocs |
| 122 | result += "\""; |
| 123 | for (const char* c=value; *c != 0; ++c) |
| 124 | { |
| 125 | switch(*c) |
| 126 | { |
| 127 | case '\"': |
| 128 | result += "\\\""; |
| 129 | break; |
| 130 | case '\\': |
| 131 | result += "\\\\"; |
| 132 | break; |
| 133 | case '\b': |
| 134 | result += "\\b"; |
| 135 | break; |
| 136 | case '\f': |
| 137 | result += "\\f"; |
| 138 | break; |
| 139 | case '\n': |
| 140 | result += "\\n"; |
| 141 | break; |
| 142 | case '\r': |
| 143 | result += "\\r"; |
| 144 | break; |
| 145 | case '\t': |
| 146 | result += "\\t"; |
| 147 | break; |
| 148 | //case '/': |
| 149 | // Even though \/ is considered a legal escape in JSON, a bare |
| 150 | // slash is also legal, so I see no reason to escape it. |
| 151 | // (I hope I am not misunderstanding something. |
| 152 | // blep notes: actually escaping \/ may be useful in javascript to avoid </ |
| 153 | // sequence. |
| 154 | // Should add a flag to allow this compatibility mode and prevent this |
| 155 | // sequence from occurring. |
| 156 | default: |
| 157 | if ( isControlCharacter( *c ) ) |
| 158 | { |
| 159 | std::ostringstream oss; |
| 160 | oss << "\\u" << std::hex << std::uppercase << std::setfill('0') << std::setw(4) << static_cast<int>(*c); |
| 161 | result += oss.str(); |
| 162 | } |
| 163 | else |
| 164 | { |
| 165 | result += *c; |
| 166 | } |
| 167 | break; |
| 168 | } |
no test coverage detected