Pigweed
 
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_preprocessor/compiler.h"
23
24namespace pw {
25
27inline bool IsAlignedAs(const void* ptr, size_t alignment) {
28 return (cpp20::bit_cast<uintptr_t>(ptr) % alignment) == 0;
29}
30
33template <typename T>
34bool IsAlignedAs(const void* ptr) {
35 return IsAlignedAs(ptr, alignof(T));
36}
37
39constexpr size_t AlignDown(uintptr_t value, size_t alignment) {
40 PW_ASSERT(!PW_MUL_OVERFLOW((value / alignment), alignment, &value));
41 return value;
42}
43
45template <typename T>
46constexpr T* AlignDown(T* value, size_t alignment) {
47 return reinterpret_cast<T*>(
48 AlignDown(reinterpret_cast<uintptr_t>(value), alignment));
49}
50
52constexpr size_t AlignUp(uintptr_t value, size_t alignment) {
53 PW_ASSERT(!PW_ADD_OVERFLOW(value, alignment - 1, &value));
54 return AlignDown(value, alignment);
55}
56
58template <typename T>
59constexpr T* AlignUp(T* value, size_t alignment) {
60 return reinterpret_cast<T*>(
61 AlignUp(reinterpret_cast<uintptr_t>(value), alignment));
62}
63
65constexpr size_t Padding(size_t length, size_t alignment) {
66 return AlignUp(length, alignment) - length;
67}
68
75ByteSpan GetAlignedSubspan(ByteSpan bytes, size_t alignment);
76
77} // namespace pw
#define PW_ADD_OVERFLOW(a, b, out)
Definition: compiler.h:282
#define PW_MUL_OVERFLOW(a, b, out)
Definition: compiler.h:304
Provides basic helpers for reading and writing UTF-8 encoded strings.
Definition: alignment.h:27
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:65
constexpr size_t AlignUp(uintptr_t value, size_t alignment)
Returns the value rounded up to the nearest multiple of alignment.
Definition: alignment.h:52
constexpr size_t AlignDown(uintptr_t value, size_t alignment)
Returns the value rounded down to the nearest multiple of alignment.
Definition: alignment.h:39
bool IsAlignedAs(const void *ptr, size_t alignment)
Returns whether the given pointer meets the given alignment requirement.
Definition: alignment.h:27