blob: ba35f614047cf145bfe6e64b231d3e8f83330c7c [file] [log] [blame]
Armando Montanez516022c2020-05-14 09:12:19 -07001// Copyright 2020 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
15#include "pw_containers/intrusive_list.h"
16
17#include "pw_assert/assert.h"
18
19namespace pw::intrusive_list_impl {
20
Keir Mierle69cd61d2020-08-18 13:47:46 -070021List::Item::~Item() { unlist(); }
22
23void List::Item::unlist(Item* prev) {
24 if (prev == nullptr) {
25 prev = previous();
26 }
27 // Skip over this.
28 prev->next_ = next_;
29
30 // Retain the invariant that unlisted items are self-cycles.
31 next_ = this;
32}
33
34List::Item* List::Item::previous() {
35 // Follow the cycle around to find the previous element; O(N).
36 Item* prev = next_;
37 while (prev->next_ != this) {
38 prev = prev->next_;
39 }
40 return prev;
41}
42
Wyatt Hepler70f033e2020-06-10 22:22:27 -070043void List::insert_after(Item* pos, Item& item) {
Keir Mierle69cd61d2020-08-18 13:47:46 -070044 PW_CHECK(
45 item.unlisted(),
Wyatt Hepler70f033e2020-06-10 22:22:27 -070046 "Cannot add an item to a pw::IntrusiveList that is already in a list");
Armando Montanez516022c2020-05-14 09:12:19 -070047 item.next_ = pos->next_;
48 pos->next_ = &item;
Armando Montanez516022c2020-05-14 09:12:19 -070049}
50
Keir Mierle69cd61d2020-08-18 13:47:46 -070051void List::erase_after(Item* pos) { pos->next_->unlist(pos); }
Armando Montanez516022c2020-05-14 09:12:19 -070052
Keir Mierle69cd61d2020-08-18 13:47:46 -070053List::Item* List::before_end() noexcept { return before_begin()->previous(); }
Armando Montanez516022c2020-05-14 09:12:19 -070054
55void List::clear() {
Wyatt Hepler70f033e2020-06-10 22:22:27 -070056 while (!empty()) {
57 erase_after(before_begin());
58 }
59}
60
61bool 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) {
64 erase_after(pos);
65 return true;
66 }
Armando Montanez516022c2020-05-14 09:12:19 -070067 }
Wyatt Hepler70f033e2020-06-10 22:22:27 -070068 return false;
Armando Montanez516022c2020-05-14 09:12:19 -070069}
70
Keir Mierlefbd4a112020-09-20 21:20:49 -070071size_t List::size() const {
72 size_t total = 0;
73 Item* item = head_.next_;
74 while (item != &head_) {
75 item = item->next_;
76 total++;
77 }
78 return total;
79}
80
Armando Montanez516022c2020-05-14 09:12:19 -070081} // namespace pw::intrusive_list_impl