blob: a6bea6c8f4578b57ae6a9c31c5cc2eb67db70dc2 [file] [log] [blame]
Dmitriy Ivanovd59e5002014-05-09 09:10:14 -07001/*
2 * Copyright (C) 2014 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#ifndef __LINKED_LIST_H
18#define __LINKED_LIST_H
19
20#include "private/bionic_macros.h"
21
22template<typename T>
23struct LinkedListEntry {
24 LinkedListEntry<T>* next;
25 T* element;
26};
27
28/*
29 * Represents linked list of objects of type T
30 */
31template<typename T, typename Allocator>
32class LinkedList {
33 public:
34 LinkedList() : head_(nullptr) {}
35
36 void push_front(T* const element) {
37 LinkedListEntry<T>* new_entry = Allocator::alloc();
38 new_entry->next = head_;
39 new_entry->element = element;
40 head_ = new_entry;
41 }
42
43 void clear() {
44 while (head_ != nullptr) {
45 LinkedListEntry<T>* p = head_;
46 head_ = head_->next;
47 Allocator::free(p);
48 }
49 }
50
51 template<typename F>
52 void for_each(F&& action) {
53 for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
54 if (e->element != nullptr) {
55 action(e->element);
56 }
57 }
58 }
59
60 template<typename F>
61 void remove_if(F&& predicate) {
62 LinkedListEntry<T>* e = head_;
63 for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) {
64 if (e->element != nullptr && predicate(e->element)) {
65 e->element = nullptr;
66 }
67 }
68 }
69
70 private:
71 LinkedListEntry<T>* head_;
72 DISALLOW_COPY_AND_ASSIGN(LinkedList);
73};
74
75#endif // __LINKED_LIST_H