| 14719 | {} |
| 14720 | |
| 14721 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 14722 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 14723 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 14724 | |
| 14725 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 14726 | uchar c = m_str[idx]; |
| 14727 | switch (c) { |
| 14728 | case '<': os << "<"; break; |
| 14729 | case '&': os << "&"; break; |
| 14730 | |
| 14731 | case '>': |
| 14732 | // See: http://www.w3.org/TR/xml/#syntax |
| 14733 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 14734 | os << ">"; |
| 14735 | else |
| 14736 | os << c; |
| 14737 | break; |
| 14738 | |
| 14739 | case '\"': |
| 14740 | if (m_forWhat == ForAttributes) |
| 14741 | os << """; |
| 14742 | else |
| 14743 | os << c; |
| 14744 | break; |
| 14745 | |
| 14746 | default: |
| 14747 | // Check for control characters and invalid utf-8 |
| 14748 | |
| 14749 | // Escape control characters in standard ascii |
| 14750 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 14751 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 14752 | hexEscapeChar(os, c); |
| 14753 | break; |
| 14754 | } |
| 14755 | |
| 14756 | // Plain ASCII: Write it to stream |
| 14757 | if (c < 0x7F) { |
| 14758 | os << c; |
| 14759 | break; |
| 14760 | } |
| 14761 | |
| 14762 | // UTF-8 territory |
| 14763 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 14764 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 14765 | // First check that this bytes is a valid lead byte: |
| 14766 | // This means that it is not encoded as 1111 1XXX |
| 14767 | // Or as 10XX XXXX |
| 14768 | if (c < 0xC0 || |
| 14769 | c >= 0xF8) { |
| 14770 | hexEscapeChar(os, c); |
| 14771 | break; |
| 14772 | } |
| 14773 | |
| 14774 | auto encBytes = trailingBytes(c); |
| 14775 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 14776 | if (idx + encBytes - 1 >= m_str.size()) { |
| 14777 | hexEscapeChar(os, c); |
| 14778 | break; |
no test coverage detected