Fix crash on app list start page keyboard navigation with <4 apps.
[chromium-blink-merge.git] / gpu / command_buffer / common / id_allocator.cc
blob507b14e9af19bfdd298f5b93362dc099f428c5f2
1 // Copyright (c) 2011 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.
5 // This file contains the implementation of IdAllocator.
7 #include "gpu/command_buffer/common/id_allocator.h"
9 #include "base/logging.h"
11 namespace gpu {
13 IdAllocator::IdAllocator() {}
15 IdAllocator::~IdAllocator() {}
17 ResourceId IdAllocator::AllocateID() {
18 ResourceId id;
19 ResourceIdSet::iterator iter = free_ids_.begin();
20 if (iter != free_ids_.end()) {
21 id = *iter;
22 } else {
23 id = LastUsedId() + 1;
24 if (!id) {
25 // We wrapped around to 0.
26 id = FindFirstUnusedId();
29 MarkAsUsed(id);
30 return id;
33 ResourceId IdAllocator::AllocateIDAtOrAbove(ResourceId desired_id) {
34 ResourceId id;
35 ResourceIdSet::iterator iter = free_ids_.lower_bound(desired_id);
36 if (iter != free_ids_.end()) {
37 id = *iter;
38 } else if (LastUsedId() < desired_id) {
39 id = desired_id;
40 } else {
41 id = LastUsedId() + 1;
42 if (!id) {
43 // We wrapped around to 0.
44 id = FindFirstUnusedId();
47 MarkAsUsed(id);
48 return id;
51 bool IdAllocator::MarkAsUsed(ResourceId id) {
52 DCHECK(id);
53 free_ids_.erase(id);
54 std::pair<ResourceIdSet::iterator, bool> result = used_ids_.insert(id);
55 return result.second;
58 void IdAllocator::FreeID(ResourceId id) {
59 if (id) {
60 used_ids_.erase(id);
61 free_ids_.insert(id);
65 bool IdAllocator::InUse(ResourceId id) const {
66 return id == kInvalidResource || used_ids_.find(id) != used_ids_.end();
69 ResourceId IdAllocator::LastUsedId() const {
70 if (used_ids_.empty()) {
71 return 0u;
72 } else {
73 return *used_ids_.rbegin();
77 ResourceId IdAllocator::FindFirstUnusedId() const {
78 ResourceId id = 1;
79 for (ResourceIdSet::const_iterator it = used_ids_.begin();
80 it != used_ids_.end(); ++it) {
81 if ((*it) != id) {
82 return id;
84 ++id;
86 return id;
89 } // namespace gpu