C/C++ API Reference
Loading...
Searching...
No Matches
iterable.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 "pw_allocator/block/contiguous.h"
17
18namespace pw::allocator {
19namespace internal {
20
21// Trivial base class for trait support.
22struct IterableBase {};
23
24} // namespace internal
25
27
34template <typename Derived>
36 protected:
37 constexpr explicit IterableBlock() {
38 // Assert within a function, since `Derived` is not complete when this type
39 // is defined.
40 static_assert(is_contiguous_v<Derived>,
41 "Types derived from IterableBlock must also derive "
42 "from ContiguousBlock");
43 }
44
45 public:
52 class Iterator final {
53 public:
54 constexpr explicit Iterator(Derived* block) : block_(block) {}
55 constexpr Iterator& operator++() {
56 block_ = block_ != nullptr ? block_->Next() : nullptr;
57 return *this;
58 }
59 constexpr bool operator!=(const Iterator& other) {
60 return block_ != other.block_;
61 }
62 constexpr Derived* operator*() { return block_; }
63
64 private:
65 Derived* block_;
66 };
67
76 class Range final {
77 public:
79 constexpr explicit Range(Derived* begin) : begin_(begin), end_(nullptr) {}
80
82 constexpr Range(Derived* begin_inclusive, Derived* end_inclusive)
83 : begin_(begin_inclusive), end_(end_inclusive->Next()) {}
84
85 constexpr Iterator& begin() { return begin_; }
86 constexpr Iterator& end() { return end_; }
87
88 private:
89 Iterator begin_;
90 Iterator end_;
91 };
92};
93
96template <typename BlockType>
97struct is_iterable : std::is_base_of<internal::IterableBase, BlockType> {};
98
100template <typename BlockType>
102
104
105} // namespace pw::allocator
Definition: iterable.h:76
constexpr Range(Derived *begin)
Constructs a range including begin and all valid following blocks.
Definition: iterable.h:79
constexpr Range(Derived *begin_inclusive, Derived *end_inclusive)
Constructs a range of blocks from begin to end, inclusively.
Definition: iterable.h:82
Definition: iterable.h:35
constexpr bool is_iterable_v
Helper variable template for is_iterable<BlockType>::value.
Definition: iterable.h:101
Definition: iterable.h:22
Definition: iterable.h:97