| 1405 | } |
| 1406 | |
| 1407 | bool is_valid_utf8(const std::string & str) { |
| 1408 | const unsigned char* bytes = reinterpret_cast<const unsigned char*>(str.data()); |
| 1409 | const unsigned char* end = bytes + str.length(); |
| 1410 | |
| 1411 | while (bytes < end) { |
| 1412 | if (*bytes <= 0x7F) { |
| 1413 | // 1-byte sequence (0xxxxxxx) |
| 1414 | bytes++; |
| 1415 | } else if ((*bytes & 0xE0) == 0xC0) { |
| 1416 | // 2-byte sequence (110xxxxx 10xxxxxx) |
| 1417 | if (end - bytes < 2 || (bytes[1] & 0xC0) != 0x80) |
| 1418 | return false; |
| 1419 | bytes += 2; |
| 1420 | } else if ((*bytes & 0xF0) == 0xE0) { |
| 1421 | // 3-byte sequence (1110xxxx 10xxxxxx 10xxxxxx) |
| 1422 | if (end - bytes < 3 || (bytes[1] & 0xC0) != 0x80 || (bytes[2] & 0xC0) != 0x80) |
| 1423 | return false; |
| 1424 | bytes += 3; |
| 1425 | } else if ((*bytes & 0xF8) == 0xF0) { |
| 1426 | // 4-byte sequence (11110xxx 10xxxxxx 10xxxxxx 10xxxxxx) |
| 1427 | if (end - bytes < 4 || (bytes[1] & 0xC0) != 0x80 || |
| 1428 | (bytes[2] & 0xC0) != 0x80 || (bytes[3] & 0xC0) != 0x80) |
| 1429 | return false; |
| 1430 | bytes += 4; |
| 1431 | } else { |
| 1432 | // Invalid UTF-8 lead byte |
| 1433 | return false; |
| 1434 | } |
| 1435 | } |
| 1436 | |
| 1437 | return true; |
| 1438 | } |
| 1439 | |
| 1440 | llama_tokens format_prompt_infill( |
| 1441 | const llama_vocab * vocab, |
no test coverage detected