Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / gpu / command_buffer / common / id_allocator.cc
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.
4
5 // This file contains the implementation of IdAllocator.
6
7 #include "gpu/command_buffer/common/id_allocator.h"
8
9 #include "base/logging.h"
10
11 namespace gpu {
12
13 IdAllocator::IdAllocator() {}
14
15 IdAllocator::~IdAllocator() {}
16
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();
27     }
28   }
29   MarkAsUsed(id);
30   return id;
31 }
32
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();
45     }
46   }
47   MarkAsUsed(id);
48   return id;
49 }
50
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;
56 }
57
58 void IdAllocator::FreeID(ResourceId id) {
59   if (id) {
60     used_ids_.erase(id);
61     free_ids_.insert(id);
62   }
63 }
64
65 bool IdAllocator::InUse(ResourceId id) const {
66   return id == kInvalidResource || used_ids_.find(id) != used_ids_.end();
67 }
68
69 ResourceId IdAllocator::LastUsedId() const {
70   if (used_ids_.empty()) {
71     return 0u;
72   } else {
73     return *used_ids_.rbegin();
74   }
75 }
76
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;
83     }
84     ++id;
85   }
86   return id;
87 }
88
89 }  // namespace gpu