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
18 #include "pw_assert/assert.h"
19 #include "pw_bytes/span.h"
20 #include "pw_preprocessor/compiler.h"
21
22 namespace pw {
23
24 /// Returns the value rounded down to the nearest multiple of alignment.
AlignDown(size_t value,size_t alignment)25 constexpr size_t AlignDown(size_t value, size_t alignment) {
26 PW_ASSERT(!PW_MUL_OVERFLOW((value / alignment), alignment, &value));
27 return value;
28 }
29
30 /// Returns the value rounded down to the nearest multiple of alignment.
31 template <typename T>
AlignDown(T * value,size_t alignment)32 constexpr T* AlignDown(T* value, size_t alignment) {
33 return reinterpret_cast<T*>(
34 AlignDown(reinterpret_cast<size_t>(value), alignment));
35 }
36
37 /// Returns the value rounded up to the nearest multiple of alignment.
AlignUp(size_t value,size_t alignment)38 constexpr size_t AlignUp(size_t value, size_t alignment) {
39 PW_ASSERT(!PW_ADD_OVERFLOW(value, alignment - 1, &value));
40 return AlignDown(value, alignment);
41 }
42
43 /// Returns the value rounded up to the nearest multiple of alignment.
44 template <typename T>
AlignUp(T * value,size_t alignment)45 constexpr T* AlignUp(T* value, size_t alignment) {
46 return reinterpret_cast<T*>(
47 AlignUp(reinterpret_cast<size_t>(value), alignment));
48 }
49
50 /// Returns the number of padding bytes required to align the provided length.
Padding(size_t length,size_t alignment)51 constexpr size_t Padding(size_t length, size_t alignment) {
52 return AlignUp(length, alignment) - length;
53 }
54
55 /// Returns the largest aligned subspan of a given byte span.
56 ///
57 /// The subspan will start and end on alignment boundaries.
58 ///
59 /// @returns A `ByteSpan` within `bytes` aligned to `alignment`, or an empty
60 /// `ByteSpan` if alignment was not possible.
61 ByteSpan GetAlignedSubspan(ByteSpan bytes, size_t alignment);
62
63 } // namespace pw
64