1 // Copyright (c) 2013 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 "ui/gfx/sequential_id_generator.h"
6
7 #include "base/logging.h"
8
9 namespace {
10
11 // Removes |key| from |first|, and |first[key]| from |second|.
12 template<typename T>
Remove(uint32 key,T * first,T * second)13 void Remove(uint32 key, T* first, T* second) {
14 typename T::iterator iter = first->find(key);
15 if (iter == first->end())
16 return;
17
18 uint32 second_key = iter->second;
19 first->erase(iter);
20
21 iter = second->find(second_key);
22 DCHECK(iter != second->end());
23 second->erase(iter);
24 }
25
26 } // namespace
27
28 namespace ui {
29
SequentialIDGenerator(uint32 min_id)30 SequentialIDGenerator::SequentialIDGenerator(uint32 min_id)
31 : min_id_(min_id),
32 min_available_id_(min_id) {
33 }
34
~SequentialIDGenerator()35 SequentialIDGenerator::~SequentialIDGenerator() {
36 }
37
GetGeneratedID(uint32 number)38 uint32 SequentialIDGenerator::GetGeneratedID(uint32 number) {
39 IDMap::iterator find = number_to_id_.find(number);
40 if (find != number_to_id_.end())
41 return find->second;
42
43 int id = GetNextAvailableID();
44 number_to_id_.insert(std::make_pair(number, id));
45 id_to_number_.insert(std::make_pair(id, number));
46 return id;
47 }
48
HasGeneratedIDFor(uint32 number) const49 bool SequentialIDGenerator::HasGeneratedIDFor(uint32 number) const {
50 return number_to_id_.find(number) != number_to_id_.end();
51 }
52
ReleaseGeneratedID(uint32 id)53 void SequentialIDGenerator::ReleaseGeneratedID(uint32 id) {
54 UpdateNextAvailableIDAfterRelease(id);
55 Remove(id, &id_to_number_, &number_to_id_);
56 }
57
ReleaseNumber(uint32 number)58 void SequentialIDGenerator::ReleaseNumber(uint32 number) {
59 DCHECK_GT(number_to_id_.count(number), 0U);
60 UpdateNextAvailableIDAfterRelease(number_to_id_[number]);
61 Remove(number, &number_to_id_, &id_to_number_);
62 }
63
ResetForTest()64 void SequentialIDGenerator::ResetForTest() {
65 number_to_id_.clear();
66 id_to_number_.clear();
67 min_available_id_ = min_id_;
68 }
69
GetNextAvailableID()70 uint32 SequentialIDGenerator::GetNextAvailableID() {
71 const uint32 kMaxID = 128;
72 while (id_to_number_.count(min_available_id_) > 0 &&
73 min_available_id_ < kMaxID) {
74 ++min_available_id_;
75 }
76 if (min_available_id_ >= kMaxID)
77 min_available_id_ = min_id_;
78 return min_available_id_;
79 }
80
UpdateNextAvailableIDAfterRelease(uint32 id)81 void SequentialIDGenerator::UpdateNextAvailableIDAfterRelease(uint32 id) {
82 if (id < min_available_id_) {
83 min_available_id_ = id;
84 DCHECK_GE(min_available_id_, min_id_);
85 }
86 }
87
88 } // namespace ui
89