Home | History | Annotate | Download | only in gfx
      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>
     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 
     30 SequentialIDGenerator::SequentialIDGenerator(uint32 min_id)
     31     : min_id_(min_id),
     32       min_available_id_(min_id) {
     33 }
     34 
     35 SequentialIDGenerator::~SequentialIDGenerator() {
     36 }
     37 
     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 
     49 bool SequentialIDGenerator::HasGeneratedIDFor(uint32 number) const {
     50   return number_to_id_.find(number) != number_to_id_.end();
     51 }
     52 
     53 void SequentialIDGenerator::ReleaseGeneratedID(uint32 id) {
     54   UpdateNextAvailableIDAfterRelease(id);
     55   Remove(id, &id_to_number_, &number_to_id_);
     56 }
     57 
     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 
     64 uint32 SequentialIDGenerator::GetNextAvailableID() {
     65   const uint32 kMaxID = 128;
     66   while (id_to_number_.count(min_available_id_) > 0 &&
     67          min_available_id_ < kMaxID) {
     68     ++min_available_id_;
     69   }
     70   if (min_available_id_ >= kMaxID)
     71     min_available_id_ = min_id_;
     72   return min_available_id_;
     73 }
     74 
     75 void SequentialIDGenerator::UpdateNextAvailableIDAfterRelease(uint32 id) {
     76   if (id < min_available_id_) {
     77     min_available_id_ = id;
     78     DCHECK_GE(min_available_id_, min_id_);
     79   }
     80 }
     81 
     82 }  // namespace ui
     83