49 lines
1.6 KiB
C++
49 lines
1.6 KiB
C++
#pragma once
|
|
|
|
#include <cstddef>
|
|
|
|
namespace borla {
|
|
namespace utf8_text {
|
|
|
|
// Continuation bytes are 0b10xxxxxx — every byte of a multi-byte sequence
|
|
// except the first.
|
|
inline bool IsContinuationByte(char value)
|
|
{
|
|
return (static_cast<unsigned char>(value) & 0xC0) == 0x80;
|
|
}
|
|
|
|
// Longest prefix of `text` that is at most `max_bytes` long AND ends on a UTF-8
|
|
// character boundary. Returns the length in bytes; the caller copies that many.
|
|
//
|
|
// Truncating on a raw byte boundary is not a cosmetic problem. The previous
|
|
// firmware capped the same field with substr(0, 100), which splits a 3-byte
|
|
// Chinese character straddling byte 100 into an incomplete sequence. The
|
|
// server's websockets library validates text frames as UTF-8 and force-closes
|
|
// with code 1007 (invalid frame payload data) — seen in production as "invalid
|
|
// continuation byte at position 214", killing the session mid-story. JSON
|
|
// escaping does not help: half a character is still invalid UTF-8, and cJSON
|
|
// escapes control characters without validating encoding.
|
|
inline size_t SafeTruncatedLength(
|
|
const char* text,
|
|
size_t length,
|
|
size_t max_bytes)
|
|
{
|
|
if (text == nullptr) {
|
|
return 0;
|
|
}
|
|
if (length <= max_bytes) {
|
|
return length;
|
|
}
|
|
// Walk left from the cap until the byte at the cut is a lead byte, i.e.
|
|
// the start of the character that is being dropped. Everything before it
|
|
// is then a run of complete characters.
|
|
size_t end = max_bytes;
|
|
while (end > 0 && IsContinuationByte(text[end])) {
|
|
--end;
|
|
}
|
|
return end;
|
|
}
|
|
|
|
} // namespace utf8_text
|
|
} // namespace borla
|