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