From 30dc6aaf878b2c55efcf7598fdb8886e06d14e01 Mon Sep 17 00:00:00 2001 From: Tom Sepez Date: Tue, 25 Sep 2018 20:06:50 +0000 Subject: Add FxAlignToBoundary<>() template helper function. Because I nearly botched this trivial calculation in the previous CL. Change-Id: I7438f9d3476d93b7899c2d7d761234769f53f9e3 Reviewed-on: https://pdfium-review.googlesource.com/43010 Commit-Queue: Lei Zhang Reviewed-by: Lei Zhang --- core/fxcrt/cfx_bitstream.cpp | 3 ++- core/fxcrt/fx_memory.h | 7 +++++++ core/fxcrt/fx_memory_unittest.cpp | 23 +++++++++++++++++++++++ 3 files changed, 32 insertions(+), 1 deletion(-) (limited to 'core/fxcrt') diff --git a/core/fxcrt/cfx_bitstream.cpp b/core/fxcrt/cfx_bitstream.cpp index 3d3040d96a..d16fc2f1a4 100644 --- a/core/fxcrt/cfx_bitstream.cpp +++ b/core/fxcrt/cfx_bitstream.cpp @@ -8,6 +8,7 @@ #include +#include "core/fxcrt/fx_memory.h" #include "core/fxcrt/fx_system.h" CFX_BitStream::CFX_BitStream(pdfium::span pData) @@ -18,7 +19,7 @@ CFX_BitStream::CFX_BitStream(pdfium::span pData) CFX_BitStream::~CFX_BitStream() {} void CFX_BitStream::ByteAlign() { - m_BitPos = (m_BitPos + 7) & ~7; + m_BitPos = FxAlignToBoundary<8>(m_BitPos); } uint32_t CFX_BitStream::GetBits(uint32_t nBits) { diff --git a/core/fxcrt/fx_memory.h b/core/fxcrt/fx_memory.h index 707e084211..b39911269b 100644 --- a/core/fxcrt/fx_memory.h +++ b/core/fxcrt/fx_memory.h @@ -130,6 +130,13 @@ inline void FX_Free(void* ptr) { template char (&ArraySizeHelper(T (&array)[N]))[N]; +// Round up to the power-of-two boundary N. +template +inline T FxAlignToBoundary(T size) { + static_assert(N > 0 && (N & (N - 1)) == 0, "Not non-zero power of two"); + return (size + N - 1) & ~(N - 1); +} + // Used with std::unique_ptr to FX_Free raw memory. struct FxFreeDeleter { inline void operator()(void* ptr) const { FX_Free(ptr); } diff --git a/core/fxcrt/fx_memory_unittest.cpp b/core/fxcrt/fx_memory_unittest.cpp index 8c577835d6..eab11113cd 100644 --- a/core/fxcrt/fx_memory_unittest.cpp +++ b/core/fxcrt/fx_memory_unittest.cpp @@ -83,3 +83,26 @@ TEST(fxcrt, DISABLED_FXMEM_DefaultOOM) { EXPECT_FALSE(FXMEM_DefaultRealloc(ptr, kMaxByteAlloc)); FXMEM_DefaultFree(ptr); } + +TEST(fxcrt, FXAlign) { + static_assert(std::numeric_limits::max() % 2 == 1, + "numeric limit must be odd for this test"); + + size_t s0 = 0; + size_t s1 = 1; + size_t s2 = 2; + size_t sbig = std::numeric_limits::max() - 2; + EXPECT_EQ(0u, FxAlignToBoundary<2>(s0)); + EXPECT_EQ(2u, FxAlignToBoundary<2>(s1)); + EXPECT_EQ(2u, FxAlignToBoundary<2>(s2)); + EXPECT_EQ(std::numeric_limits::max() - 1, FxAlignToBoundary<2>(sbig)); + + int i0 = 0; + int i511 = 511; + int i512 = 512; + int ineg = -513; + EXPECT_EQ(0, FxAlignToBoundary<512>(i0)); + EXPECT_EQ(512, FxAlignToBoundary<512>(i511)); + EXPECT_EQ(512, FxAlignToBoundary<512>(i512)); + EXPECT_EQ(-512, FxAlignToBoundary<512>(ineg)); +} -- cgit v1.2.3