refactor: add overflow-safe CeilDiv helper

Introduce `CeilDiv()` for integral ceiling division without the typical `(dividend + divisor - 1) / divisor` overflow, asserting a non-zero divisor.

Replace existing ceiling-division expressions with `CeilDiv()` to centralize the preconditions.

Add unit tests covering return type deduction, max-value behavior, and divisor checks.
This commit is contained in:
Lőrinc
2026-01-28 14:45:30 +01:00
parent 4a05825a3f
commit 02d047fd5b
15 changed files with 85 additions and 19 deletions

View File

@@ -8,6 +8,7 @@
#include <tinyformat.h>
#include <util/fs_helpers.h>
#include <util/log.h>
#include <util/overflow.h>
#include <stdexcept>
@@ -59,8 +60,8 @@ size_t FlatFileSeq::Allocate(const FlatFilePos& pos, size_t add_size, bool& out_
{
out_of_space = false;
unsigned int n_old_chunks = (pos.nPos + m_chunk_size - 1) / m_chunk_size;
unsigned int n_new_chunks = (pos.nPos + add_size + m_chunk_size - 1) / m_chunk_size;
unsigned int n_old_chunks = CeilDiv(pos.nPos, m_chunk_size);
unsigned int n_new_chunks = CeilDiv(pos.nPos + add_size, m_chunk_size);
if (n_new_chunks > n_old_chunks) {
size_t old_size = pos.nPos;
size_t new_size = n_new_chunks * m_chunk_size;