| 12800 | {} |
| 12801 | |
| 12802 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 12803 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 12804 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 12805 | |
| 12806 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 12807 | uchar c = m_str[idx]; |
| 12808 | switch (c) { |
| 12809 | case '<': os << "<"; break; |
| 12810 | case '&': os << "&"; break; |
| 12811 | |
| 12812 | case '>': |
| 12813 | // See: http://www.w3.org/TR/xml/#syntax |
| 12814 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 12815 | os << ">"; |
| 12816 | else |
| 12817 | os << c; |
| 12818 | break; |
| 12819 | |
| 12820 | case '\"': |
| 12821 | if (m_forWhat == ForAttributes) |
| 12822 | os << """; |
| 12823 | else |
| 12824 | os << c; |
| 12825 | break; |
| 12826 | |
| 12827 | default: |
| 12828 | // Check for control characters and invalid utf-8 |
| 12829 | |
| 12830 | // Escape control characters in standard ascii |
| 12831 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 12832 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 12833 | hexEscapeChar(os, c); |
| 12834 | break; |
| 12835 | } |
| 12836 | |
| 12837 | // Plain ASCII: Write it to stream |
| 12838 | if (c < 0x7F) { |
| 12839 | os << c; |
| 12840 | break; |
| 12841 | } |
| 12842 | |
| 12843 | // UTF-8 territory |
| 12844 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 12845 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 12846 | // First check that this bytes is a valid lead byte: |
| 12847 | // This means that it is not encoded as 1111 1XXX |
| 12848 | // Or as 10XX XXXX |
| 12849 | if (c < 0xC0 || |
| 12850 | c >= 0xF8) { |
| 12851 | hexEscapeChar(os, c); |
| 12852 | break; |
| 12853 | } |
| 12854 | |
| 12855 | auto encBytes = trailingBytes(c); |
| 12856 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 12857 | if (idx + encBytes - 1 >= m_str.size()) { |
| 12858 | hexEscapeChar(os, c); |
| 12859 | break; |
no test coverage detected