@@ -620,6 +620,8 @@ struct type_caster<std::basic_string<CharT, Traits, Allocator>, enable_if_t<is_s
620
620
std::is_same<CharT, char32_t >::value ? 32 :
621
621
(sizeof (CharT) == 2 ? 16 : 32 ); /* std::wstring is UTF-16 on Windows, UTF-32 everywhere else */
622
622
623
+ static constexpr const char *encoding = UTF_N == 8 ? " utf8" : UTF_N == 16 ? " utf16" : " utf32" ;
624
+
623
625
// C++ only requires char/char16_t/char32_t to be at least 8/16/32 bits, but Python's encoding
624
626
// assumes exactly 1/2/4 bytes:
625
627
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
639
641
}
640
642
641
643
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 ));
645
645
if (!utfNbytes) { PyErr_Clear (); return false ; }
646
646
647
647
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
655
655
static handle cast (const StringType &src, return_value_policy /* policy */ , handle /* parent */ ) {
656
656
const char *buffer = reinterpret_cast <const char *>(src.c_str ());
657
657
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 );
659
659
if (!s) throw error_already_set ();
660
660
return s;
661
661
}
0 commit comments