cmake/Source/cmXMLSafe.cxx

91 lines
2.2 KiB
C++
Raw Normal View History

2016-10-30 18:24:19 +01:00
/* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
file Copyright.txt or https://cmake.org/licensing for details. */
2009-10-04 10:30:41 +03:00
#include "cmXMLSafe.h"
2020-02-01 23:06:01 +01:00
#include <cstdio>
#include <cstring>
2015-11-17 17:22:37 +01:00
#include <sstream>
2020-02-01 23:06:01 +01:00
#include "cm_utf8.h"
2009-10-04 10:30:41 +03:00
2016-07-09 11:21:54 +02:00
cmXMLSafe::cmXMLSafe(const char* s)
: Data(s)
, Size(static_cast<unsigned long>(strlen(s)))
, DoQuotes(true)
2009-10-04 10:30:41 +03:00
{
}
2016-07-09 11:21:54 +02:00
cmXMLSafe::cmXMLSafe(std::string const& s)
: Data(s.c_str())
, Size(static_cast<unsigned long>(s.length()))
, DoQuotes(true)
2009-10-04 10:30:41 +03:00
{
}
cmXMLSafe& cmXMLSafe::Quotes(bool b)
{
this->DoQuotes = b;
return *this;
}
2021-09-14 00:13:48 +02:00
std::string cmXMLSafe::str() const
2009-10-04 10:30:41 +03:00
{
2015-11-17 17:22:37 +01:00
std::ostringstream ss;
2009-10-04 10:30:41 +03:00
ss << *this;
return ss.str();
}
2015-11-17 17:22:37 +01:00
std::ostream& operator<<(std::ostream& os, cmXMLSafe const& self)
2009-10-04 10:30:41 +03:00
{
char const* first = self.Data;
char const* last = self.Data + self.Size;
2016-07-09 11:21:54 +02:00
while (first != last) {
2010-03-17 14:00:29 +02:00
unsigned int ch;
2016-07-09 11:21:54 +02:00
if (const char* next = cm_utf8_decode_character(first, last, &ch)) {
2010-03-17 14:00:29 +02:00
// http://www.w3.org/TR/REC-xml/#NT-Char
2016-07-09 11:21:54 +02:00
if ((ch >= 0x20 && ch <= 0xD7FF) || (ch >= 0xE000 && ch <= 0xFFFD) ||
(ch >= 0x10000 && ch <= 0x10FFFF) || ch == 0x9 || ch == 0xA ||
ch == 0xD) {
switch (ch) {
2010-03-17 14:00:29 +02:00
// Escape XML control characters.
2016-07-09 11:21:54 +02:00
case '&':
os << "&amp;";
break;
case '<':
os << "&lt;";
break;
case '>':
os << "&gt;";
break;
case '"':
os << (self.DoQuotes ? "&quot;" : "\"");
break;
case '\'':
os << (self.DoQuotes ? "&apos;" : "'");
break;
case '\r':
break; // Ignore CR
2010-03-17 14:00:29 +02:00
// Print the UTF-8 character.
2016-07-09 11:21:54 +02:00
default:
os.write(first, next - first);
break;
2010-03-17 14:00:29 +02:00
}
2016-07-09 11:21:54 +02:00
} else {
2010-03-17 14:00:29 +02:00
// Use a human-readable hex value for this invalid character.
char buf[16];
2022-03-29 21:10:50 +02:00
snprintf(buf, sizeof(buf), "%X", ch);
2010-03-17 14:00:29 +02:00
os << "[NON-XML-CHAR-0x" << buf << "]";
2016-07-09 11:21:54 +02:00
}
2010-03-17 14:00:29 +02:00
first = next;
2016-07-09 11:21:54 +02:00
} else {
2010-03-17 14:00:29 +02:00
ch = static_cast<unsigned char>(*first++);
// Use a human-readable hex value for this invalid byte.
char buf[16];
2022-03-29 21:10:50 +02:00
snprintf(buf, sizeof(buf), "%X", ch);
2010-03-17 14:00:29 +02:00
os << "[NON-UTF-8-BYTE-0x" << buf << "]";
2009-10-04 10:30:41 +03:00
}
2016-07-09 11:21:54 +02:00
}
2009-10-04 10:30:41 +03:00
return os;
}