| 506 | static constexpr size_t UTF_N = 8 * sizeof(CharT); |
| 507 | |
| 508 | bool load(handle src, bool) { |
| 509 | handle load_src = src; |
| 510 | if (!src) { |
| 511 | return false; |
| 512 | } |
| 513 | if (!PyUnicode_Check(load_src.ptr())) { |
| 514 | return load_raw(load_src); |
| 515 | } |
| 516 | |
| 517 | // For UTF-8 we avoid the need for a temporary `bytes` object by using |
| 518 | // `PyUnicode_AsUTF8AndSize`. |
| 519 | if (UTF_N == 8) { |
| 520 | Py_ssize_t size = -1; |
| 521 | const auto *buffer |
| 522 | = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size)); |
| 523 | if (!buffer) { |
| 524 | PyErr_Clear(); |
| 525 | return false; |
| 526 | } |
| 527 | value = StringType(buffer, static_cast<size_t>(size)); |
| 528 | return true; |
| 529 | } |
| 530 | |
| 531 | auto utfNbytes |
| 532 | = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(), |
| 533 | UTF_N == 8 ? "utf-8" |
| 534 | : UTF_N == 16 ? "utf-16" |
| 535 | : "utf-32", |
| 536 | nullptr)); |
| 537 | if (!utfNbytes) { |
| 538 | PyErr_Clear(); |
| 539 | return false; |
| 540 | } |
| 541 | |
| 542 | const auto *buffer |
| 543 | = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr())); |
| 544 | size_t length = static_cast<size_t>(PYBIND11_BYTES_SIZE(utfNbytes.ptr())) / sizeof(CharT); |
| 545 | // Skip BOM for UTF-16/32 |
| 546 | if (UTF_N > 8) { |
| 547 | buffer++; |
| 548 | length--; |
| 549 | } |
| 550 | value = StringType(buffer, length); |
| 551 | |
| 552 | // If we're loading a string_view we need to keep the encoded Python object alive: |
| 553 | if (IsView) { |
| 554 | loader_life_support::add_patient(utfNbytes); |
| 555 | } |
| 556 | |
| 557 | return true; |
| 558 | } |
| 559 | |
| 560 | static handle |
| 561 | cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) { |
nothing calls this directly
no test coverage detected