linked_list.h revision 1b1966d9448e979d1503a3d8843708bfa8880dc6
1/* 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 for (LinkedListEntry<T>* e = head_; e != nullptr; e = e->next) { 63 if (e->element != nullptr && predicate(e->element)) { 64 e->element = nullptr; 65 } 66 } 67 } 68 69 private: 70 LinkedListEntry<T>* head_; 71 DISALLOW_COPY_AND_ASSIGN(LinkedList); 72}; 73 74#endif // __LINKED_LIST_H 75