1 // Copyright 2013 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef CONTENT_RENDERER_MEDIA_TAGGED_LIST_H_ 6 #define CONTENT_RENDERER_MEDIA_TAGGED_LIST_H_ 7 8 #include <algorithm> 9 #include <list> 10 11 #include "base/logging.h" 12 #include "base/memory/ref_counted.h" 13 14 namespace content { 15 16 // Implements the pattern of a list of items, where added items are 17 // tagged, you can tag all items, and you can retrieve the list of 18 // items that are tagged, which removes the tag. 19 // 20 // For thread safety, operations on this object should be under an 21 // external lock. An internally-locked version could be created, but 22 // is not needed at the moment as users already lock. 23 template <class ItemType> 24 class TaggedList { 25 public: 26 typedef std::list<scoped_refptr<ItemType> > ItemList; 27 28 TaggedList() {} 29 30 void AddAndTag(ItemType* item) { 31 items_.push_back(item); 32 tagged_items_.push_back(item); 33 } 34 35 void TagAll() { 36 tagged_items_ = items_; 37 } 38 39 const ItemList& Items() const { 40 return items_; 41 } 42 43 // Retrieves the list of items with tags, and removes their tags. 44 // 45 // |dest| should be empty. 46 void RetrieveAndClearTags(ItemList* dest) { 47 DCHECK(dest->empty()); 48 dest->swap(tagged_items_); 49 } 50 51 // Remove an item that matches a predicate. Will return a reference 52 // to it if it is found. 53 template <class UnaryPredicate> 54 scoped_refptr<ItemType> Remove(UnaryPredicate predicate) { 55 tagged_items_.remove_if(predicate); 56 57 typename ItemList::iterator it = std::find_if( 58 items_.begin(), items_.end(), predicate); 59 if (it != items_.end()) { 60 scoped_refptr<ItemType> removed_item = *it; 61 items_.erase(it); 62 return removed_item; 63 } 64 65 return NULL; 66 } 67 68 template <class UnaryPredicate> 69 bool Contains(UnaryPredicate predicate) const { 70 return std::find_if(items_.begin(), items_.end(), predicate) != 71 items_.end(); 72 } 73 74 void Clear() { 75 items_.clear(); 76 tagged_items_.clear(); 77 } 78 79 bool IsEmpty() const { 80 bool is_empty = items_.empty(); 81 DCHECK(!is_empty || tagged_items_.empty()); 82 return is_empty; 83 } 84 85 private: 86 ItemList items_; 87 ItemList tagged_items_; 88 89 DISALLOW_COPY_AND_ASSIGN(TaggedList); 90 }; 91 92 } // namespace content 93 94 #endif // CONTENT_RENDERER_MEDIA_TAGGED_LIST_H_ 95