401227 {
401228 auto &buffer_manager = BufferManager::GetBufferManager(current_segment->db);
401229 auto handle = buffer_manager.Pin(current_segment->block);
401230 if (current_dictionary.end != info.GetBlockSize()) {
401231 throw InternalException("dictionary end does not match the block size in FSSTCompressionState::Finalize");
401232 }
401233
401234
401235 auto compressed_index_buffer_size =
401236 BitpackingPrimitives::GetRequiredSize(current_segment->count, current_width);
401237 auto total_size = sizeof(fsst_compression_header_t) + compressed_index_buffer_size + current_dictionary.size +
401238 fsst_serialized_symbol_table_size;
401239 if (total_size != last_fitting_size) {
401240 throw InternalException("FSST string compression failed due to incorrect size calculation");
401241 }
401242
401243
401244 auto base_ptr = handle.Ptr();
401245 auto header_ptr = reinterpret_cast<fsst_compression_header_t *>(base_ptr);
401246 auto compressed_index_buffer_offset = sizeof(fsst_compression_header_t);
401247 auto symbol_table_offset = compressed_index_buffer_offset + compressed_index_buffer_size;
401248
401249 D_ASSERT(current_segment->count == index_buffer.size());
401250 BitpackingPrimitives::PackBuffer<sel_t, false>(base_ptr + compressed_index_buffer_offset,
401251 reinterpret_cast<uint32_t *
>(index_buffer.data()),
401252 current_segment->count, current_width);
401253
401254
401255 if (fsst_encoder != nullptr) {
401256 memcpy(base_ptr + symbol_table_offset, &fsst_serialized_symbol_table[0], fsst_serialized_symbol_table_size);
401257 } else {
401258 memset(base_ptr + symbol_table_offset, 0, fsst_serialized_symbol_table_size);
401259 }
401260
401261 auto cast_symbol_table_offset = NumericCast<uint32_t>(symbol_table_offset);
401262 if (cast_symbol_table_offset > info.GetBlockSize()) {
401263 throw InternalException("invalid fsst_symbol_table_offset in FSSTCompressionState::Finalize");
401264 }
401265
401266 Store<uint32_t>(cast_symbol_table_offset, data_ptr_cast(&header_ptr->fsst_symbol_table_offset));
401267 Store<uint32_t>((uint32_t)current_width, data_ptr_cast(&header_ptr->bitpacking_width));
401268
401269 if (total_size >= info.GetCompactionFlushLimit()) {
401270
401271 return info.GetBlockSize();
401272 }
401273
401274
401275 auto move_amount = info.GetBlockSize() - total_size;
401276
401277 auto new_dictionary_offset = symbol_table_offset + fsst_serialized_symbol_table_size;
401278 memmove(base_ptr + new_dictionary_offset, base_ptr + current_dictionary.end - current_dictionary.size,
401279 current_dictionary.size);
401280 current_dictionary.end -= move_amount;
401281 D_ASSERT(current_dictionary.end == total_size);
401282
401283 FSSTStorage::SetDictionary(*current_segment, handle, current_dictionary);
401284
401285 return total_size;
401286 }