C/C++ API Reference
Loading...
Searching...
No Matches
alignment.h
1// Copyright 2023 The Pigweed Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may not
4// use this file except in compliance with the License. You may obtain a copy of
5// the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
11// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
12// License for the specific language governing permissions and limitations under
13// the License.
14#pragma once
15
16#include <cstddef>
17#include <cstdint>
18
19#include "lib/stdcompat/bit.h"
20#include "pw_assert/assert.h"
21#include "pw_bytes/span.h"
22#include "pw_numeric/checked_arithmetic.h"
23
24namespace pw {
25
27
29inline bool IsAlignedAs(const void* ptr, size_t alignment) {
30 return (cpp20::bit_cast<uintptr_t>(ptr) % alignment) == 0;
31}
32
35template <typename T>
36bool IsAlignedAs(const void* ptr) {
37 return IsAlignedAs(ptr, alignof(T));
38}
39
41constexpr size_t AlignDown(uintptr_t value, size_t alignment) {
42 PW_ASSERT(CheckedMul((value / alignment), alignment, value));
43 return value;
44}
45
47template <typename T>
48constexpr T* AlignDown(T* value, size_t alignment) {
49 return reinterpret_cast<T*>(
50 AlignDown(reinterpret_cast<uintptr_t>(value), alignment));
51}
52
54constexpr size_t AlignUp(uintptr_t value, size_t alignment) {
55 PW_ASSERT(CheckedIncrement(value, alignment - 1));
56 return AlignDown(value, alignment);
57}
58
60template <typename T>
61constexpr T* AlignUp(T* value, size_t alignment) {
62 return reinterpret_cast<T*>(
63 AlignUp(reinterpret_cast<uintptr_t>(value), alignment));
64}
65
67constexpr size_t Padding(size_t length, size_t alignment) {
68 return AlignUp(length, alignment) - length;
69}
70
77ByteSpan GetAlignedSubspan(ByteSpan bytes, size_t alignment);
78
80
81} // namespace pw
ByteSpan GetAlignedSubspan(ByteSpan bytes, size_t alignment)
constexpr size_t Padding(size_t length, size_t alignment)
Returns the number of padding bytes required to align the provided length.
Definition: alignment.h:67
constexpr size_t AlignUp(uintptr_t value, size_t alignment)
Returns the value rounded up to the nearest multiple of alignment.
Definition: alignment.h:54
constexpr size_t AlignDown(uintptr_t value, size_t alignment)
Returns the value rounded down to the nearest multiple of alignment.
Definition: alignment.h:41
bool IsAlignedAs(const void *ptr, size_t alignment)
Returns whether the given pointer meets the given alignment requirement.
Definition: alignment.h:29
constexpr bool CheckedIncrement(T &base, Inc inc)
Definition: checked_arithmetic.h:118
constexpr bool CheckedMul(A a, B b, T &result)
Definition: checked_arithmetic.h:206
The Pigweed namespace.
Definition: alignment.h:27