| 15170 | {} |
| 15171 | |
| 15172 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 15173 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 15174 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 15175 | |
| 15176 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 15177 | uchar c = m_str[idx]; |
| 15178 | switch (c) { |
| 15179 | case '<': os << "<"; break; |
| 15180 | case '&': os << "&"; break; |
| 15181 | |
| 15182 | case '>': |
| 15183 | // See: http://www.w3.org/TR/xml/#syntax |
| 15184 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 15185 | os << ">"; |
| 15186 | else |
| 15187 | os << c; |
| 15188 | break; |
| 15189 | |
| 15190 | case '\"': |
| 15191 | if (m_forWhat == ForAttributes) |
| 15192 | os << """; |
| 15193 | else |
| 15194 | os << c; |
| 15195 | break; |
| 15196 | |
| 15197 | default: |
| 15198 | // Check for control characters and invalid utf-8 |
| 15199 | |
| 15200 | // Escape control characters in standard ascii |
| 15201 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 15202 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 15203 | hexEscapeChar(os, c); |
| 15204 | break; |
| 15205 | } |
| 15206 | |
| 15207 | // Plain ASCII: Write it to stream |
| 15208 | if (c < 0x7F) { |
| 15209 | os << c; |
| 15210 | break; |
| 15211 | } |
| 15212 | |
| 15213 | // UTF-8 territory |
| 15214 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 15215 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 15216 | // First check that this bytes is a valid lead byte: |
| 15217 | // This means that it is not encoded as 1111 1XXX |
| 15218 | // Or as 10XX XXXX |
| 15219 | if (c < 0xC0 || |
| 15220 | c >= 0xF8) { |
| 15221 | hexEscapeChar(os, c); |
| 15222 | break; |
| 15223 | } |
| 15224 | |
| 15225 | auto encBytes = trailingBytes(c); |
| 15226 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 15227 | if (idx + encBytes - 1 >= m_str.size()) { |
| 15228 | hexEscapeChar(os, c); |
| 15229 | break; |
no test coverage detected