| 15494 | {} |
| 15495 | |
| 15496 | void XmlEncode::encodeTo( std::ostream& os ) const { |
| 15497 | // Apostrophe escaping not necessary if we always use " to write attributes |
| 15498 | // (see: http://www.w3.org/TR/xml/#syntax) |
| 15499 | |
| 15500 | for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { |
| 15501 | unsigned char c = m_str[idx]; |
| 15502 | switch (c) { |
| 15503 | case '<': os << "<"; break; |
| 15504 | case '&': os << "&"; break; |
| 15505 | |
| 15506 | case '>': |
| 15507 | // See: http://www.w3.org/TR/xml/#syntax |
| 15508 | if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') |
| 15509 | os << ">"; |
| 15510 | else |
| 15511 | os << c; |
| 15512 | break; |
| 15513 | |
| 15514 | case '\"': |
| 15515 | if (m_forWhat == ForAttributes) |
| 15516 | os << """; |
| 15517 | else |
| 15518 | os << c; |
| 15519 | break; |
| 15520 | |
| 15521 | default: |
| 15522 | // Check for control characters and invalid utf-8 |
| 15523 | |
| 15524 | // Escape control characters in standard ascii |
| 15525 | // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 |
| 15526 | if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { |
| 15527 | hexEscapeChar(os, c); |
| 15528 | break; |
| 15529 | } |
| 15530 | |
| 15531 | // Plain ASCII: Write it to stream |
| 15532 | if (c < 0x7F) { |
| 15533 | os << c; |
| 15534 | break; |
| 15535 | } |
| 15536 | |
| 15537 | // UTF-8 territory |
| 15538 | // Check if the encoding is valid and if it is not, hex escape bytes. |
| 15539 | // Important: We do not check the exact decoded values for validity, only the encoding format |
| 15540 | // First check that this bytes is a valid lead byte: |
| 15541 | // This means that it is not encoded as 1111 1XXX |
| 15542 | // Or as 10XX XXXX |
| 15543 | if (c < 0xC0 || |
| 15544 | c >= 0xF8) { |
| 15545 | hexEscapeChar(os, c); |
| 15546 | break; |
| 15547 | } |
| 15548 | |
| 15549 | auto encBytes = trailingBytes(c); |
| 15550 | // Are there enough bytes left to avoid accessing out-of-bounds memory? |
| 15551 | if (idx + encBytes - 1 >= m_str.size()) { |
| 15552 | hexEscapeChar(os, c); |
| 15553 | break; |
no test coverage detected