1 // Copyright 2014 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 #include "extensions/common/value_counter.h" 6 7 #include <algorithm> 8 9 #include "base/values.h" 10 11 namespace extensions { 12 ValueCounter()13ValueCounter::ValueCounter() {} 14 ~ValueCounter()15ValueCounter::~ValueCounter() {} 16 Entry(const base::Value & value)17ValueCounter::Entry::Entry(const base::Value& value) 18 : value_(value.DeepCopy()), count_(1) {} 19 ~Entry()20ValueCounter::Entry::~Entry() {} 21 Increment()22int ValueCounter::Entry::Increment() { return ++count_; } 23 Decrement()24int ValueCounter::Entry::Decrement() { return --count_; } 25 Add(const base::Value & value)26int ValueCounter::Add(const base::Value& value) { return AddImpl(value, true); } 27 Remove(const base::Value & value)28int ValueCounter::Remove(const base::Value& value) { 29 for (EntryList::iterator it = entries_.begin(); it != entries_.end(); it++) { 30 (*it)->value()->GetType(); 31 if ((*it)->value()->Equals(&value)) { 32 int remaining = (*it)->Decrement(); 33 if (remaining == 0) { 34 std::swap(*it, entries_.back()); 35 entries_.pop_back(); 36 } 37 return remaining; 38 } 39 } 40 return 0; 41 } 42 AddIfMissing(const base::Value & value)43int ValueCounter::AddIfMissing(const base::Value& value) { 44 return AddImpl(value, false); 45 } 46 AddImpl(const base::Value & value,bool increment)47int ValueCounter::AddImpl(const base::Value& value, bool increment) { 48 for (EntryList::iterator it = entries_.begin(); it != entries_.end(); it++) { 49 if ((*it)->value()->Equals(&value)) 50 return increment ? (*it)->Increment() : (*it)->count(); 51 } 52 entries_.push_back(linked_ptr<Entry>(new Entry(value))); 53 return 1; 54 } 55 56 } // namespace extensions 57