Pigweed
 
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
32template <typename Derived>
34 protected:
35 constexpr explicit IterableBlock() {
36 // Assert within a function, since `Derived` is not complete when this type
37 // is defined.
38 static_assert(is_contiguous_v<Derived>,
39 "Types derived from IterableBlock must also derive "
40 "from ContiguousBlock");
41 }
42
43 public:
50 class Iterator final {
51 public:
52 constexpr explicit Iterator(Derived* block) : block_(block) {}
53 constexpr Iterator& operator++() {
54 block_ = block_ != nullptr ? block_->Next() : nullptr;
55 return *this;
56 }
57 constexpr bool operator!=(const Iterator& other) {
58 return block_ != other.block_;
59 }
60 constexpr Derived* operator*() { return block_; }
61
62 private:
63 Derived* block_;
64 };
65
74 class Range final {
75 public:
77 constexpr explicit Range(Derived* begin) : begin_(begin), end_(nullptr) {}
78
80 constexpr Range(Derived* begin_inclusive, Derived* end_inclusive)
81 : begin_(begin_inclusive), end_(end_inclusive->Next()) {}
82
83 constexpr Iterator& begin() { return begin_; }
84 constexpr Iterator& end() { return end_; }
85
86 private:
87 Iterator begin_;
88 Iterator end_;
89 };
90};
91
94template <typename BlockType>
95struct is_iterable : std::is_base_of<internal::IterableBase, BlockType> {};
96
98template <typename BlockType>
99constexpr bool is_iterable_v = is_iterable<BlockType>::value;
100
101} // namespace pw::allocator
Definition: iterable.h:74
constexpr Range(Derived *begin)
Constructs a range including begin and all valid following blocks.
Definition: iterable.h:77
constexpr Range(Derived *begin_inclusive, Derived *end_inclusive)
Constructs a range of blocks from begin to end, inclusively.
Definition: iterable.h:80
Definition: iterable.h:33
Definition: iterable.h:22
Definition: iterable.h:95