From 54c456702c7fe6b9b0ef026f864dc1bc9590c88e Mon Sep 17 00:00:00 2001 From: jhofstee Date: Mon, 22 Sep 2025 22:53:01 +0200 Subject: [PATCH] zlib: reduce code duplication The offset in the allocated memory was calculated in alloc and free, this makes it a single constant so it only needs to be defined once. PR-URL: https://github.com/nodejs/node/pull/57810 Reviewed-By: James M Snell Reviewed-By: Anna Henningsen --- src/node_zlib.cc | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/node_zlib.cc b/src/node_zlib.cc index c704e23db4..1adbb7dda3 100644 --- a/src/node_zlib.cc +++ b/src/node_zlib.cc @@ -612,9 +612,11 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork { return AllocForBrotli(data, real_size); } + static constexpr size_t reserveSizeAndAlign = + std::max(sizeof(size_t), alignof(max_align_t)); + static void* AllocForBrotli(void* data, size_t size) { - constexpr size_t offset = std::max(sizeof(size_t), alignof(max_align_t)); - size += offset; + size += reserveSizeAndAlign; CompressionStream* ctx = static_cast(data); char* memory = UncheckedMalloc(size); if (memory == nullptr) [[unlikely]] { @@ -623,7 +625,7 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork { *reinterpret_cast(memory) = size; ctx->unreported_allocations_.fetch_add(size, std::memory_order_relaxed); - return memory + offset; + return memory + reserveSizeAndAlign; } static void FreeForZlib(void* data, void* pointer) { @@ -631,8 +633,7 @@ class CompressionStream : public AsyncWrap, public ThreadPoolWork { return; } CompressionStream* ctx = static_cast(data); - constexpr size_t offset = std::max(sizeof(size_t), alignof(max_align_t)); - char* real_pointer = static_cast(pointer) - offset; + char* real_pointer = static_cast(pointer) - reserveSizeAndAlign; size_t real_size = *reinterpret_cast(real_pointer); ctx->unreported_allocations_.fetch_sub(real_size, std::memory_order_relaxed);