C/C++ API Reference
Loading...
Searching...
No Matches
stack.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 <array>
17#include <cstddef>
18#include <type_traits>
19
20#include "pw_span/span.h"
21#include "pw_thread_backend/stack.h"
22
23namespace pw {
24
26
27namespace internal {
28
29using ThreadStackPointer =
30 decltype(std::declval<thread::backend::Stack<0>>().data());
31
32// Returns a span of the thread stack, with std::byte used for void* stacks.
33template <typename T>
34constexpr auto ThreadStackSpan(T* pointer, size_t size) {
35 if constexpr (std::is_void_v<T>) {
36 return span(static_cast<std::byte*>(pointer), size);
37 } else {
38 return span(pointer, size);
39 }
40}
41
42// Gets the stack size and handles void* stacks.
43constexpr auto NativeStackSizeBytes(size_t size) {
44 using T = std::remove_pointer_t<ThreadStackPointer>;
45 return size * sizeof(std::conditional_t<std::is_void_v<T>, std::byte, T>);
46}
47
48} // namespace internal
49
62template <size_t kStackSizeBytes>
64 public:
65 constexpr ThreadStack() : native_stack_{} {}
66
70 using native = internal::ThreadStackPointer;
71
75 [[nodiscard]] constexpr native native_pointer() {
76 return native_stack_.data();
77 }
78
83 [[nodiscard]] constexpr size_t native_size() const {
84 return native_stack_.size();
85 }
86
87 private:
88 static_assert(
89 std::is_same_v<decltype(thread::backend::Stack<kStackSizeBytes>().data()),
90 native>,
91 "Stack pointer type must not change with size");
92 static_assert(std::is_pointer_v<native>, ".data() must return a pointer");
93
94 thread::backend::Stack<kStackSizeBytes> native_stack_;
95};
96
97} // namespace pw
Definition: stack.h:63
constexpr native native_pointer()
Definition: stack.h:75
constexpr size_t native_size() const
Definition: stack.h:83
internal::ThreadStackPointer native
Definition: stack.h:70
The Pigweed namespace.
Definition: alignment.h:27