Home | History | Annotate | Download | only in base
      1 /*
      2  * Copyright (C) 2013 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 #ifndef ART_RUNTIME_BASE_BOUNDED_FIFO_H_
     18 #define ART_RUNTIME_BASE_BOUNDED_FIFO_H_
     19 
     20 #include "cutils/atomic.h"
     21 #include "cutils/atomic-inline.h"
     22 
     23 namespace art {
     24 
     25 // A bounded fifo is a fifo which has a bounded size. The power of two version uses a bit mask to
     26 // avoid needing to deal with wrapping integers around or using a modulo operation.
     27 template <typename T, const size_t MaxSize>
     28 class BoundedFifoPowerOfTwo {
     29  public:
     30   BoundedFifoPowerOfTwo() {
     31     // TODO: Do this with a compile time check.
     32     CHECK(IsPowerOfTwo(MaxSize));
     33     clear();
     34   }
     35 
     36   void clear() {
     37     back_index_ = 0;
     38     size_ = 0;
     39   }
     40 
     41   bool empty() const {
     42     return size() == 0;
     43   }
     44 
     45   size_t size() const {
     46     return size_;
     47   }
     48 
     49   void push_back(const T& value) {
     50     ++size_;
     51     DCHECK_LE(size_, MaxSize);
     52     // Relies on integer overflow behaviour.
     53     data_[back_index_++ & mask_] = value;
     54   }
     55 
     56   const T& front() const {
     57     DCHECK_GT(size_, 0U);
     58     return data_[(back_index_ - size_) & mask_];
     59   }
     60 
     61   void pop_front() {
     62     DCHECK_GT(size_, 0U);
     63     --size_;
     64   }
     65 
     66  private:
     67   static const size_t mask_ = MaxSize - 1;
     68   size_t back_index_, size_;
     69   T data_[MaxSize];
     70 };
     71 
     72 }  // namespace art
     73 
     74 #endif  // ART_RUNTIME_BASE_BOUNDED_FIFO_H_
     75