1 /* 2 * Copyright 2022 Google LLC 3 * 4 * Use of this source code is governed by a BSD-style license that can be 5 * found in the LICENSE file. 6 */ 7 8 #ifndef SkAlign_DEFINED 9 #define SkAlign_DEFINED 10 11 #include "include/private/base/SkAssert.h" 12 13 #include <cstddef> 14 SkAlign2(T x)15template <typename T> static constexpr T SkAlign2(T x) { return (x + 1) >> 1 << 1; } SkAlign4(T x)16template <typename T> static constexpr T SkAlign4(T x) { return (x + 3) >> 2 << 2; } SkAlign8(T x)17template <typename T> static constexpr T SkAlign8(T x) { return (x + 7) >> 3 << 3; } SkAlign16(T x)18template <typename T> static constexpr T SkAlign16(T x) { return (x + 15) >> 4 << 4; } 19 SkIsAlign2(T x)20template <typename T> static constexpr bool SkIsAlign2(T x) { return 0 == (x & 1); } SkIsAlign4(T x)21template <typename T> static constexpr bool SkIsAlign4(T x) { return 0 == (x & 3); } SkIsAlign8(T x)22template <typename T> static constexpr bool SkIsAlign8(T x) { return 0 == (x & 7); } SkIsAlign16(T x)23template <typename T> static constexpr bool SkIsAlign16(T x) { return 0 == (x & 15); } 24 25 SkAlignPtr(T x)26template <typename T> static constexpr T SkAlignPtr(T x) { 27 static_assert(sizeof(void*) == 4 || sizeof(void*) == 8); 28 return sizeof(void*) == 8 ? SkAlign8(x) : SkAlign4(x); 29 } SkIsAlignPtr(T x)30template <typename T> static constexpr bool SkIsAlignPtr(T x) { 31 static_assert(sizeof(void*) == 4 || sizeof(void*) == 8); 32 return sizeof(void*) == 8 ? SkIsAlign8(x) : SkIsAlign4(x); 33 } 34 35 /** 36 * align up to a power of 2 37 */ SkAlignTo(size_t x,size_t alignment)38static inline constexpr size_t SkAlignTo(size_t x, size_t alignment) { 39 // The same as alignment && SkIsPow2(value), w/o a dependency cycle. 40 SkASSERT(alignment && (alignment & (alignment - 1)) == 0); 41 return (x + alignment - 1) & ~(alignment - 1); 42 } 43 44 #endif 45