| 143 | } |
| 144 | |
| 145 | int utf8SafeTruncateBuffer(const char* buf, int len) { |
| 146 | if (len <= 0) return 0; |
| 147 | |
| 148 | // Walk back past continuation bytes (10xxxxxx) to find the lead byte |
| 149 | int leadPos = len - 1; |
| 150 | while (leadPos > 0 && (static_cast<uint8_t>(buf[leadPos]) & 0xC0) == 0x80) { |
| 151 | leadPos--; |
| 152 | } |
| 153 | |
| 154 | // Determine expected length of the sequence starting at leadPos |
| 155 | int expectedLen = utf8CodepointLen(static_cast<unsigned char>(buf[leadPos])); |
| 156 | int actualLen = len - leadPos; |
| 157 | |
| 158 | if (actualLen < expectedLen && leadPos > 0) { |
| 159 | // Incomplete UTF-8 sequence at the end — exclude it |
| 160 | return leadPos; |
| 161 | } |
| 162 | return len; |
| 163 | } |
| 164 | |
| 165 | size_t utf8RemoveLastChar(std::string& str) { |
| 166 | if (str.empty()) return 0; |
no test coverage detected