| 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 |
|
| 15 |
template <typename T> static constexpr T SkAlign2(T x) { return (x + 1) >> 1 << 1; } |
| 16 |
template <typename T> static constexpr T SkAlign4(T x) { return (x + 3) >> 2 << 2; } |
| 17 |
template <typename T> static constexpr T SkAlign8(T x) { return (x + 7) >> 3 << 3; } |
| 18 |
template <typename T> static constexpr T SkAlign16(T x) { return (x + 15) >> 4 << 4; } |
| 19 |
|
| 20 |
template <typename T> static constexpr bool SkIsAlign2(T x) { return 0 == (x & 1); } |
| 21 |
template <typename T> static constexpr bool SkIsAlign4(T x) { return 0 == (x & 3); } |
| 22 |
template <typename T> static constexpr bool SkIsAlign8(T x) { return 0 == (x & 7); } |
| 23 |
template <typename T> static constexpr bool SkIsAlign16(T x) { return 0 == (x & 15); } |
| 24 |
|
| 25 |
|
| 26 |
template <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 |
} |
| 30 |
template <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 |
*/ |
| 38 |
template <typename T> static constexpr T SkAlignTo(T x, 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 |
/** |
| 45 |
* align up to a non power of 2 |
| 46 |
*/ |
| 47 |
template <typename T> static constexpr T SkAlignNonPow2(T x, T alignment) { |
| 48 |
return ((x + alignment - 1) / alignment) * alignment; |
| 49 |
} |
| 50 |
|
| 51 |
#endif |