From f94fabfd9a44f541338960d65b44c168daffdab8 Mon Sep 17 00:00:00 2001 From: pybind11_abseil authors Date: Wed, 14 Aug 2024 09:05:55 -0700 Subject: [PATCH] Avoid extra string-copies in `typecaster`. PiperOrigin-RevId: 662940213 --- pybind11_abseil/absl_casters.h | 11 ++++++++++- 1 file changed, 10 insertions(+), 1 deletion(-) diff --git a/pybind11_abseil/absl_casters.h b/pybind11_abseil/absl_casters.h index 0e57884..a465f4a 100644 --- a/pybind11_abseil/absl_casters.h +++ b/pybind11_abseil/absl_casters.h @@ -42,6 +42,7 @@ #include #include #include +#include #include #include #include @@ -634,7 +635,15 @@ struct type_caster { return str(std::string(src)).release(); } #endif - return bytes(std::string(src)).release(); + bytes data(nullptr, src.size()); + // Cord::CopyToArray is not always available so we need to copy + // the cord manually. + char* ptr = PyBytes_AS_STRING(data.ptr()); + for (absl::string_view chunk : src.Chunks()) { + std::memcpy(ptr, chunk.data(), chunk.size()); + ptr += chunk.size(); + } + return data.release(); } };