1 // Copyright 2020 The Pigweed Authors
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
7 // https://www.apache.org/licenses/LICENSE-2.0
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
15 #include "pw_containers/intrusive_list.h"
17 #include "pw_assert/assert.h"
19 namespace pw::intrusive_list_impl {
21 List::Item::~Item() { unlist(); }
23 void List::Item::unlist(Item* prev) {
24 if (prev == nullptr) {
30 // Retain the invariant that unlisted items are self-cycles.
34 List::Item* List::Item::previous() {
35 // Follow the cycle around to find the previous element; O(N).
37 while (prev->next_ != this) {
43 void List::insert_after(Item* pos, Item& item) {
46 "Cannot add an item to a pw::IntrusiveList that is already in a list");
47 item.next_ = pos->next_;
51 void List::erase_after(Item* pos) { pos->next_->unlist(pos); }
53 List::Item* List::before_end() noexcept { return before_begin()->previous(); }
57 erase_after(before_begin());
61 bool List::remove(const Item& item_to_remove) {
62 for (Item* pos = before_begin(); pos->next_ != end(); pos = pos->next_) {
63 if (pos->next_ == &item_to_remove) {
71 size_t List::size() const {
73 Item* item = head_.next_;
74 while (item != &head_) {
81 } // namespace pw::intrusive_list_impl