| 367 | } |
| 368 | |
| 369 | void shrink_buffer() override { |
| 370 | if (buffer_ == nullptr) { |
| 371 | return; |
| 372 | } |
| 373 | |
| 374 | const uint32_t read_pos = buffer_->reader_index_; |
| 375 | // Keep Python-backed InputStream shrink behavior aligned with C++: |
| 376 | // best-effort compaction only after both the global floor (4096) and the |
| 377 | // configured stream buffer size threshold are crossed. |
| 378 | if (FORY_PREDICT_TRUE(read_pos <= 4096 || |
| 379 | read_pos < initial_buffer_size_)) { |
| 380 | return; |
| 381 | } |
| 382 | |
| 383 | const uint32_t remaining = remaining_size(); |
| 384 | if (read_pos > 0) { |
| 385 | if (remaining > 0) { |
| 386 | std::memmove(data_.data(), data_.data() + read_pos, |
| 387 | static_cast<size_t>(remaining)); |
| 388 | } |
| 389 | buffer_->reader_index_ = 0; |
| 390 | buffer_->size_ = remaining; |
| 391 | buffer_->writer_index_ = remaining; |
| 392 | } |
| 393 | |
| 394 | const uint32_t current_capacity = static_cast<uint32_t>(data_.size()); |
| 395 | uint32_t target_capacity = current_capacity; |
| 396 | if (current_capacity > initial_buffer_size_) { |
| 397 | if (remaining == 0) { |
| 398 | target_capacity = initial_buffer_size_; |
| 399 | } else if (remaining <= current_capacity / 4) { |
| 400 | const uint32_t doubled = |
| 401 | remaining > std::numeric_limits<uint32_t>::max() / 2 |
| 402 | ? std::numeric_limits<uint32_t>::max() |
| 403 | : remaining * 2; |
| 404 | target_capacity = std::max<uint32_t>( |
| 405 | initial_buffer_size_, |
| 406 | std::max<uint32_t>(doubled, static_cast<uint32_t>(1))); |
| 407 | } |
| 408 | } |
| 409 | if (target_capacity < current_capacity) { |
| 410 | data_.resize(target_capacity); |
| 411 | data_.shrink_to_fit(); |
| 412 | buffer_->data_ = data_.data(); |
| 413 | } |
| 414 | } |
| 415 | |
| 416 | Result<void, Error> unread(uint32_t size) override { |
| 417 | if (FORY_PREDICT_FALSE(size > buffer_->reader_index_)) { |