From 4fcf2c0a0968c88c60570da8fa6d7a18371c4b4b Mon Sep 17 00:00:00 2001 From: Carlos O'Ryan Date: Sun, 7 May 2023 13:12:01 -0700 Subject: [PATCH] fix: avoid warnings on MSVC (#12697) Warnings in header files can be a problem for consumers that enable `/WX` (or `-Werror`). In this case, using `... & -align` produces a warning (C4146) with MSVC. The fix is to use equivalent expression `... & ~(align - 1)`, which was already used in the same file. Fixes #12675 Closes #12697 COPYBARA_INTEGRATE_REVIEW=https://github.com/protocolbuffers/protobuf/pull/12697 from coryan:fix-msvc-warnings-in-arena-align 835f3b489a85e1b50281ac2943bd74d159eb3ead PiperOrigin-RevId: 530137165 --- src/google/protobuf/arena_align.h | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/src/google/protobuf/arena_align.h b/src/google/protobuf/arena_align.h index 958bb9d072..d63393c843 100644 --- a/src/google/protobuf/arena_align.h +++ b/src/google/protobuf/arena_align.h @@ -99,7 +99,7 @@ struct ArenaAlignDefault { } static inline PROTOBUF_ALWAYS_INLINE constexpr size_t Ceil(size_t n) { - return (n + align - 1) & -align; + return (n + align - 1) & ~(align - 1); } static inline PROTOBUF_ALWAYS_INLINE constexpr size_t Floor(size_t n) { return (n & ~(align - 1)); @@ -113,7 +113,7 @@ struct ArenaAlignDefault { template static inline PROTOBUF_ALWAYS_INLINE T* Ceil(T* ptr) { uintptr_t intptr = reinterpret_cast(ptr); - return reinterpret_cast((intptr + align - 1) & -align); + return reinterpret_cast((intptr + align - 1) & ~(align - 1)); } template @@ -142,7 +142,9 @@ struct ArenaAlign { return (reinterpret_cast(ptr) & (align - 1)) == 0U; } - constexpr size_t Ceil(size_t n) const { return (n + align - 1) & -align; } + constexpr size_t Ceil(size_t n) const { + return (n + align - 1) & ~(align - 1); + } constexpr size_t Floor(size_t n) const { return (n & ~(align - 1)); } constexpr size_t Padded(size_t n) const { @@ -156,7 +158,7 @@ struct ArenaAlign { template T* Ceil(T* ptr) const { uintptr_t intptr = reinterpret_cast(ptr); - return reinterpret_cast((intptr + align - 1) & -align); + return reinterpret_cast((intptr + align - 1) & ~(align - 1)); } template