summaryrefslogtreecommitdiffstats
path: root/base/containers/scoped_ptr_hash_map_unittest.cc
blob: 88fe41f9a0dfe4aa2cc020d80ac26720f6482c43 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
// Copyright 2015 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "base/containers/scoped_ptr_hash_map.h"

#include "base/memory/scoped_ptr.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace base {
namespace {

struct DeleteCounter {
 public:
  DeleteCounter() {}
  ~DeleteCounter() { g_delete_count++; }

  static void ResetCounter() { g_delete_count = 0; }
  static int delete_count() { return g_delete_count; }

 private:
  static int g_delete_count;
};

int DeleteCounter::g_delete_count = 0;

struct CountingDeleter {
 public:
  inline void operator()(DeleteCounter* ptr) const {
    g_deleter_call_count++;
    delete ptr;
  }

  static int count() { return g_deleter_call_count; }
  static void ResetCounter() { g_deleter_call_count = 0; }

 private:
  static int g_deleter_call_count;
};

int CountingDeleter::g_deleter_call_count = 0;

TEST(ScopedPtrHashMapTest, CustomDeleter) {
  int key = 123;

  // Test dtor.
  DeleteCounter::ResetCounter();
  CountingDeleter::ResetCounter();
  {
    ScopedPtrHashMap<int, scoped_ptr<DeleteCounter, CountingDeleter>> map;
    map.set(key, scoped_ptr<DeleteCounter, CountingDeleter>(new DeleteCounter));
  }
  EXPECT_EQ(1, DeleteCounter::delete_count());
  EXPECT_EQ(1, CountingDeleter::count());

  // Test set and erase.
  DeleteCounter::ResetCounter();
  CountingDeleter::ResetCounter();
  {
    ScopedPtrHashMap<int, scoped_ptr<DeleteCounter, CountingDeleter>> map;
    map.erase(map.set(
        key, scoped_ptr<DeleteCounter, CountingDeleter>(new DeleteCounter)));
    EXPECT_EQ(1, DeleteCounter::delete_count());
    EXPECT_EQ(1, CountingDeleter::count());
  }
  EXPECT_EQ(1, DeleteCounter::delete_count());
  EXPECT_EQ(1, CountingDeleter::count());

  // Test set more than once.
  DeleteCounter::ResetCounter();
  CountingDeleter::ResetCounter();
  {
    ScopedPtrHashMap<int, scoped_ptr<DeleteCounter, CountingDeleter>> map;
    map.set(key, scoped_ptr<DeleteCounter, CountingDeleter>(new DeleteCounter));
    map.set(key, scoped_ptr<DeleteCounter, CountingDeleter>(new DeleteCounter));
    map.set(key, scoped_ptr<DeleteCounter, CountingDeleter>(new DeleteCounter));
    EXPECT_EQ(2, DeleteCounter::delete_count());
    EXPECT_EQ(2, CountingDeleter::count());
  }
  EXPECT_EQ(3, DeleteCounter::delete_count());
  EXPECT_EQ(3, CountingDeleter::count());
}

}  // namespace
}  // namespace base