MCPcopy Create free account
hub / github.com/FreeCAD/FreeCAD / sanitizeUtf8Bytes

Function sanitizeUtf8Bytes

src/Base/InputSource.cpp:45–162  ·  view source on GitHub ↗

Replaces embedded NUL bytes and invalid UTF-8 byte sequences with '?' to avoid Xerces treating NUL as a string terminator and to keep input reasonably UTF-8-like.

Source from the content-addressed store, hash-verified

43// Replaces embedded NUL bytes and invalid UTF-8 byte sequences with '?' to avoid Xerces treating
44// NUL as a string terminator and to keep input reasonably UTF-8-like.
45void sanitizeUtf8Bytes(XMLByte* const toFill, const std::size_t len)
46{
47 auto* data = reinterpret_cast<std::uint8_t*>(
48 toFill
49 ); // NOLINT(cppcoreguidelines-pro-type-reinterpret-cast)
50
51 auto markInvalidByte = [&](std::size_t pos) {
52 data[pos] = static_cast<std::uint8_t>('?');
53 };
54
55 auto isCont = [&](std::uint8_t b) {
56 return (b & 0xC0) == 0x80;
57 };
58
59 std::size_t i = 0;
60 while (i < len) {
61 const std::uint8_t b0 = data[i];
62
63 if (b0 == 0) {
64 markInvalidByte(i);
65 ++i;
66 continue;
67 }
68
69 if (b0 < 0x80) {
70 ++i;
71 continue;
72 }
73
74 // Reject stray continuation bytes
75 if (isCont(b0)) {
76 markInvalidByte(i);
77 ++i;
78 continue;
79 }
80
81 // 2-byte sequence: C2..DF 80..BF
82 if (b0 >= 0xC2 && b0 <= 0xDF) {
83 if (i + 1 >= len || !isCont(data[i + 1])) {
84 markInvalidByte(i);
85 ++i;
86 continue;
87 }
88 i += 2;
89 continue;
90 }
91
92 // 3-byte sequences
93 if (b0 >= 0xE0 && b0 <= 0xEF) {
94 if (i + 2 >= len) {
95 markInvalidByte(i);
96 ++i;
97 continue;
98 }
99
100 const std::uint8_t b1 = data[i + 1];
101 const std::uint8_t b2 = data[i + 2];
102 if (!isCont(b1) || !isCont(b2)) {

Callers 1

validateBytesMethod · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected