blob: b90ca327dd679455f3a6a169dad68e3f944c5325 [file] [log] [blame]
[email protected]c6c301ad2014-04-15 18:20:261// Copyright 2014 The Chromium Authors. All rights reserved.
[email protected]d9e559d2012-07-05 01:04:572// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
[email protected]c6c301ad2014-04-15 18:20:265#include "extensions/common/value_counter.h"
[email protected]d9e559d2012-07-05 01:04:576
7#include <algorithm>
dcheng7c2ca352016-04-22 21:15:368#include <memory>
dchenge59eca1602015-12-18 17:48:009#include <utility>
[email protected]d9e559d2012-07-05 01:04:5710
[email protected]c6c301ad2014-04-15 18:20:2611#include "base/values.h"
12
[email protected]d9e559d2012-07-05 01:04:5713namespace extensions {
14
kalmanbd9f6182015-07-11 00:01:3615struct ValueCounter::Entry {
dcheng7c2ca352016-04-22 21:15:3616 explicit Entry(std::unique_ptr<base::Value> value)
dchenge59eca1602015-12-18 17:48:0017 : value(std::move(value)), count(1) {}
[email protected]d9e559d2012-07-05 01:04:5718
dcheng7c2ca352016-04-22 21:15:3619 std::unique_ptr<base::Value> value;
kalmanbd9f6182015-07-11 00:01:3620 int count;
21};
[email protected]d9e559d2012-07-05 01:04:5722
kalmanbd9f6182015-07-11 00:01:3623ValueCounter::ValueCounter() {
24}
[email protected]d9e559d2012-07-05 01:04:5725
kalmanbd9f6182015-07-11 00:01:3626ValueCounter::~ValueCounter() {
27}
[email protected]d9e559d2012-07-05 01:04:5728
kalmanbd9f6182015-07-11 00:01:3629bool ValueCounter::Add(const base::Value& value) {
limasdf6ca2e3c2015-11-13 22:16:0430 for (const auto& entry : entries_) {
kalmanbd9f6182015-07-11 00:01:3631 if (entry->value->Equals(&value)) {
32 ++entry->count;
33 return false;
[email protected]d9e559d2012-07-05 01:04:5734 }
35 }
Jeremy Roman16529d0e2017-08-24 18:13:4736 entries_.push_back(std::make_unique<Entry>(value.CreateDeepCopy()));
kalmanbd9f6182015-07-11 00:01:3637 return true;
[email protected]d9e559d2012-07-05 01:04:5738}
39
kalmanbd9f6182015-07-11 00:01:3640bool ValueCounter::Remove(const base::Value& value) {
limasdf6ca2e3c2015-11-13 22:16:0441 for (auto it = entries_.begin(); it != entries_.end(); ++it) {
kalmanbd9f6182015-07-11 00:01:3642 if ((*it)->value->Equals(&value)) {
43 if (--(*it)->count == 0) {
44 std::swap(*it, entries_.back());
45 entries_.pop_back();
46 return true; // Removed the last entry.
47 }
48 return false; // Removed, but no the last entry.
49 }
[email protected]d9e559d2012-07-05 01:04:5750 }
kalmanbd9f6182015-07-11 00:01:3651 return false; // Nothing to remove.
[email protected]d9e559d2012-07-05 01:04:5752}
53
54} // namespace extensions