| 2085 | {} |
| 2086 | |
| 2087 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 2088 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 2089 | // (see: https://www.w3.org/TR/xml/#syntax) |
| 2090 | |
| 2091 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 2092 | uchar c = m_str[idx]; |
| 2093 | switch (c) { |
| 2094 | case '<': os << "<"; break; |
| 2095 | case '&': os << "&"; break; |
| 2096 | |
| 2097 | case '>': |
| 2098 | // See: https://www.w3.org/TR/xml/#syntax |
| 2099 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 2100 | os << ">"; |
| 2101 | else |
| 2102 | os << c; |
| 2103 | break; |
| 2104 | |
| 2105 | case '\"': |
| 2106 | if (m_forWhat == ForAttributes) |
| 2107 | os << """; |
| 2108 | else |
| 2109 | os << c; |
| 2110 | break; |
| 2111 | |
| 2112 | default: |
| 2113 | // Check for control characters and invalid utf-8 |
| 2114 | |
| 2115 | // Escape control characters in standard ascii |
| 2116 | // see https://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 2117 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 2118 | hexEscapeChar(os, c); |
| 2119 | break; |
| 2120 | } |
| 2121 | |
| 2122 | // Plain ASCII: Write it to stream |
| 2123 | if (c < 0x7F) { |
| 2124 | os << c; |
| 2125 | break; |
| 2126 | } |
| 2127 | |
| 2128 | // UTF-8 territory |
| 2129 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 2130 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 2131 | // First check that this bytes is a valid lead byte: |
| 2132 | // This means that it is not encoded as 1111 1XXX |
| 2133 | // Or as 10XX XXXX |
| 2134 | if (c < 0xC0 || |
| 2135 | c >= 0xF8) { |
| 2136 | hexEscapeChar(os, c); |
| 2137 | break; |
| 2138 | } |
| 2139 | |
| 2140 | auto encBytes = trailingBytes(c); |
| 2141 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 2142 | if (idx + encBytes - 1 >= m_str.size()) { |
| 2143 | hexEscapeChar(os, c); |
| 2144 | break; |
no test coverage detected