Blink roll 25b6bd3a7a131ffe68d809546ad1a20707915cdc:3a503f41ae42e5b79cfcd2ff10e65afde...
[chromium-blink-merge.git] / extensions / common / value_counter.cc
blob4138f251895981b39568d5eed7cb3fc90b27491f
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.
5 #include "extensions/common/value_counter.h"
7 #include <algorithm>
9 #include "base/values.h"
11 namespace extensions {
13 ValueCounter::ValueCounter() {}
15 ValueCounter::~ValueCounter() {}
17 ValueCounter::Entry::Entry(const base::Value& value)
18 : value_(value.DeepCopy()), count_(1) {}
20 ValueCounter::Entry::~Entry() {}
22 int ValueCounter::Entry::Increment() { return ++count_; }
24 int ValueCounter::Entry::Decrement() { return --count_; }
26 int ValueCounter::Add(const base::Value& value) { return AddImpl(value, true); }
28 int 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();
37 return remaining;
40 return 0;
43 int ValueCounter::AddIfMissing(const base::Value& value) {
44 return AddImpl(value, false);
47 int 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();
52 entries_.push_back(linked_ptr<Entry>(new Entry(value)));
53 return 1;
56 } // namespace extensions