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#include "pw_numeric/rounding.h"
24
25namespace pw {
26
28
30inline bool IsAlignedAs(const void* ptr, size_t alignment) {
31 return (cpp20::bit_cast<uintptr_t>(ptr) % alignment) == 0;
32}
33
36template <typename T>
37bool IsAlignedAs(const void* ptr) {
38 return IsAlignedAs(ptr, alignof(T));
39}
40
42constexpr size_t AlignDown(uintptr_t value, size_t alignment) {
43 return RoundDown(value, alignment);
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 return RoundUp(value, alignment);
56}
57
59template <typename T>
60constexpr T* AlignUp(T* value, size_t alignment) {
61 return reinterpret_cast<T*>(
62 AlignUp(reinterpret_cast<uintptr_t>(value), alignment));
63}
64
66constexpr size_t Padding(size_t length, size_t alignment) {
67 return AlignUp(length, alignment) - length;
68}
69
76ByteSpan GetAlignedSubspan(ByteSpan bytes, size_t alignment);
77
79
80} // 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:66
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:42
bool IsAlignedAs(const void *ptr, size_t alignment)
Returns whether the given pointer meets the given alignment requirement.
Definition: alignment.h:30
The Pigweed namespace.
Definition: alignment.h:27
constexpr T RoundUp(T value, U multiple)
Returns the value rounded up to the nearest multiple.
Definition: rounding.h:42
constexpr T RoundDown(T value, U multiple)
Returns the value rounded down to the nearest multiple.
Definition: rounding.h:26