From a9563bb1a5f9de78f025acfa28fb09700e87a573 Mon Sep 17 00:00:00 2001 From: Zehua Zou Date: Mon, 30 Nov 2026 18:05:04 +0800 Subject: [PATCH] avoid a temporary buffer in spaced PLAIN encoding --- cpp/src/parquet/encoder.cc | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/cpp/src/parquet/encoder.cc b/cpp/src/parquet/encoder.cc index 30341bbe25e1..58ea85ea4745 100644 --- a/cpp/src/parquet/encoder.cc +++ b/cpp/src/parquet/encoder.cc @@ -151,15 +151,28 @@ class PlainEncoder : public EncoderImpl, virtual public TypedEncoder { void PutSpaced(const T* src, int num_values, const uint8_t* valid_bits, int64_t valid_bits_offset) override { - if (valid_bits != NULLPTR) { - PARQUET_ASSIGN_OR_THROW(auto buffer, ::arrow::AllocateBuffer(num_values * sizeof(T), - this->memory_pool())); - T* data = buffer->template mutable_data_as(); - int num_valid_values = ::arrow::util::internal::SpacedCompress( - src, num_values, valid_bits, valid_bits_offset, data); - Put(data, num_valid_values); + if (valid_bits == nullptr || num_values == 0) { + return Put(src, num_values); + } + if constexpr (::arrow::internal::IsOneOf::value) { + // Binary input contains descriptors; Put encodes the bytes they reference. + ::arrow::internal::VisitSetBitRunsVoid(valid_bits, valid_bits_offset, num_values, + [&](int64_t start, int64_t length) { + Put(src + start, static_cast(length)); + }); } else { - Put(src, num_values); + // Compact directly into the page, reserving only space for present values. + const int64_t count = + ::arrow::internal::CountSetBits(valid_bits, valid_bits_offset, num_values); + if (count == 0) { + return; + } + const int64_t bytes = count * static_cast(sizeof(T)); + PARQUET_THROW_NOT_OK(sink_.Reserve(bytes)); + T* out = reinterpret_cast(sink_.mutable_data() + sink_.length()); + ::arrow::util::internal::SpacedCompress(src, num_values, valid_bits, + valid_bits_offset, out); + sink_.UnsafeAdvance(bytes); } } @@ -327,13 +340,14 @@ inline void PlainEncoder::Put(const ::arrow::Array& values) { template <> inline void PlainEncoder::Put(const FixedLenByteArray* src, int num_values) { - if (descr_->type_length() == 0) { + const int64_t byte_width = descr_->type_length(); + if (byte_width == 0) { return; } + PARQUET_THROW_NOT_OK(sink_.Reserve(num_values * byte_width)); for (int i = 0; i < num_values; ++i) { - // Write the result to the output stream DCHECK(src[i].ptr != nullptr) << "Value ptr cannot be NULL"; - PARQUET_THROW_NOT_OK(sink_.Append(src[i].ptr, descr_->type_length())); + sink_.UnsafeAppend(src[i].ptr, byte_width); } }