blob: c9d6c052a453bc7b8b57ca620ea7c8c20062f9a6 [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
dcheng7c2ca352016-04-22 21:15:3611#include "base/memory/ptr_util.h"
[email protected]c6c301ad2014-04-15 18:20:2612#include "base/values.h"
13
[email protected]d9e559d2012-07-05 01:04:5714namespace extensions {
15
kalmanbd9f6182015-07-11 00:01:3616struct ValueCounter::Entry {
dcheng7c2ca352016-04-22 21:15:3617 explicit Entry(std::unique_ptr<base::Value> value)
dchenge59eca1602015-12-18 17:48:0018 : value(std::move(value)), count(1) {}
[email protected]d9e559d2012-07-05 01:04:5719
dcheng7c2ca352016-04-22 21:15:3620 std::unique_ptr<base::Value> value;
kalmanbd9f6182015-07-11 00:01:3621 int count;
22};
[email protected]d9e559d2012-07-05 01:04:5723
kalmanbd9f6182015-07-11 00:01:3624ValueCounter::ValueCounter() {
25}
[email protected]d9e559d2012-07-05 01:04:5726
kalmanbd9f6182015-07-11 00:01:3627ValueCounter::~ValueCounter() {
28}
[email protected]d9e559d2012-07-05 01:04:5729
kalmanbd9f6182015-07-11 00:01:3630bool ValueCounter::Add(const base::Value& value) {
limasdf6ca2e3c2015-11-13 22:16:0431 for (const auto& entry : entries_) {
kalmanbd9f6182015-07-11 00:01:3632 if (entry->value->Equals(&value)) {
33 ++entry->count;
34 return false;
[email protected]d9e559d2012-07-05 01:04:5735 }
36 }
Jeremy Roman16529d0e2017-08-24 18:13:4737 entries_.push_back(std::make_unique<Entry>(value.CreateDeepCopy()));
kalmanbd9f6182015-07-11 00:01:3638 return true;
[email protected]d9e559d2012-07-05 01:04:5739}
40
kalmanbd9f6182015-07-11 00:01:3641bool ValueCounter::Remove(const base::Value& value) {
limasdf6ca2e3c2015-11-13 22:16:0442 for (auto it = entries_.begin(); it != entries_.end(); ++it) {
kalmanbd9f6182015-07-11 00:01:3643 if ((*it)->value->Equals(&value)) {
44 if (--(*it)->count == 0) {
45 std::swap(*it, entries_.back());
46 entries_.pop_back();
47 return true; // Removed the last entry.
48 }
49 return false; // Removed, but no the last entry.
50 }
[email protected]d9e559d2012-07-05 01:04:5751 }
kalmanbd9f6182015-07-11 00:01:3652 return false; // Nothing to remove.
[email protected]d9e559d2012-07-05 01:04:5753}
54
55} // namespace extensions