| 12528 | {} |
| 12529 | |
| 12530 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 12531 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 12532 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 12533 | |
| 12534 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 12535 | uchar c = m_str[idx]; |
| 12536 | switch (c) { |
| 12537 | case '<': os << "<"; break; |
| 12538 | case '&': os << "&"; break; |
| 12539 | |
| 12540 | case '>': |
| 12541 | // See: http://www.w3.org/TR/xml/#syntax |
| 12542 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 12543 | os << ">"; |
| 12544 | else |
| 12545 | os << c; |
| 12546 | break; |
| 12547 | |
| 12548 | case '\"': |
| 12549 | if (m_forWhat == ForAttributes) |
| 12550 | os << """; |
| 12551 | else |
| 12552 | os << c; |
| 12553 | break; |
| 12554 | |
| 12555 | default: |
| 12556 | // Check for control characters and invalid utf-8 |
| 12557 | |
| 12558 | // Escape control characters in standard ascii |
| 12559 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 12560 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 12561 | hexEscapeChar(os, c); |
| 12562 | break; |
| 12563 | } |
| 12564 | |
| 12565 | // Plain ASCII: Write it to stream |
| 12566 | if (c < 0x7F) { |
| 12567 | os << c; |
| 12568 | break; |
| 12569 | } |
| 12570 | |
| 12571 | // UTF-8 territory |
| 12572 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 12573 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 12574 | // First check that this bytes is a valid lead byte: |
| 12575 | // This means that it is not encoded as 1111 1XXX |
| 12576 | // Or as 10XX XXXX |
| 12577 | if (c < 0xC0 || |
| 12578 | c >= 0xF8) { |
| 12579 | hexEscapeChar(os, c); |
| 12580 | break; |
| 12581 | } |
| 12582 | |
| 12583 | auto encBytes = trailingBytes(c); |
| 12584 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 12585 | if (idx + encBytes - 1 >= m_str.size()) { |
| 12586 | hexEscapeChar(os, c); |
| 12587 | break; |
no test coverage detected