Skip to content

Commit df6e1e8

Browse files
committed
use constexpr const char* for encoding
1 parent 1dcbc76 commit df6e1e8

File tree

1 file changed

+4
-4
lines changed

1 file changed

+4
-4
lines changed

include/pybind11/cast.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -620,6 +620,8 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
620620
std::is_same<CharT, char32_t>::value ? 32 :
621621
(sizeof(CharT) == 2 ? 16 : 32); /* std::wstring is UTF-16 on Windows, UTF-32 everywhere else */
622622

623+
static constexpr const char *encoding = UTF_N == 8 ? "utf8" : UTF_N == 16 ? "utf16" : "utf32";
624+
623625
// C++ only requires char/char16_t/char32_t to be at least 8/16/32 bits, but Python's encoding
624626
// assumes exactly 1/2/4 bytes:
625627
static_assert(sizeof(CharT) == UTF_N / 8,
@@ -639,9 +641,7 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
639641
}
640642

641643
object utfNbytes = reinterpret_steal<object>(PyUnicode_AsEncodedString(
642-
load_src.ptr(),
643-
UTF_N == 8 ? "utf8" : UTF_N == 16 ? "utf16" : "utf32",
644-
nullptr));
644+
load_src.ptr(), encoding, nullptr));
645645
if (!utfNbytes) { PyErr_Clear(); return false; }
646646

647647
const CharT *buffer = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
@@ -655,7 +655,7 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
655655
static handle cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
656656
const char *buffer = reinterpret_cast<const char *>(src.c_str());
657657
ssize_t nbytes = ssize_t(src.size() * sizeof(CharT));
658-
handle s = PyUnicode_Decode(buffer, nbytes, UTF_N == 8 ? "utf8" : UTF_N == 16 ? "utf16" : "utf32", nullptr);
658+
handle s = PyUnicode_Decode(buffer, nbytes, encoding, nullptr);
659659
if (!s) throw error_already_set();
660660
return s;
661661
}

0 commit comments

Comments
 (0)