Pigweed
Loading...
Searching...
No Matches
layout.h
1// Copyright 2024 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_preprocessor/compiler.h"
20#include "pw_result/result.h"
21
22namespace pw::allocator {
23
39class Layout {
40 public:
41 constexpr Layout() : Layout(0) {}
42 constexpr explicit Layout(size_t size)
43 : Layout(size, alignof(std::max_align_t)) {}
44 constexpr Layout(size_t size, size_t alignment)
45 : size_(size), alignment_(alignment) {}
46
48 template <typename T>
49 static constexpr Layout Of() {
50 return Layout(sizeof(T), alignof(T));
51 }
52
55 static constexpr Layout Unwrap(const Result<Layout>& result) {
56 return result.ok() ? (*result) : Layout();
57 }
58
59 constexpr Layout Extend(size_t size) const {
60 PW_ASSERT(!PW_ADD_OVERFLOW(size, size_, &size));
61 return Layout(size, alignment_);
62 }
63
64 constexpr size_t size() const { return size_; }
65 constexpr size_t alignment() const { return alignment_; }
66
67 private:
68 size_t size_;
69 size_t alignment_;
70};
71
72inline bool operator==(const Layout& lhs, const Layout& rhs) {
73 return lhs.size() == rhs.size() && lhs.alignment() == rhs.alignment();
74}
75
76inline bool operator!=(const Layout& lhs, const Layout& rhs) {
77 return !(lhs == rhs);
78}
79
80} // namespace pw::allocator
Definition: layout.h:39
static constexpr Layout Unwrap(const Result< Layout > &result)
Definition: layout.h:55
static constexpr Layout Of()
Creates a Layout for the given type.
Definition: layout.h:49
#define PW_ADD_OVERFLOW(a, b, out)
Definition: compiler.h:244