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 "base/bit_utils.h"
21 #include "base/logging.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 kMaxSize>
28 class BoundedFifoPowerOfTwo {
29   static_assert(IsPowerOfTwo(kMaxSize), "kMaxSize must be a power of 2.");
30 
31  public:
BoundedFifoPowerOfTwo()32   BoundedFifoPowerOfTwo() {
33     clear();
34   }
35 
clear()36   void clear() {
37     back_index_ = 0;
38     size_ = 0;
39   }
40 
empty()41   bool empty() const {
42     return size() == 0;
43   }
44 
size()45   size_t size() const {
46     return size_;
47   }
48 
push_back(const T & value)49   void push_back(const T& value) {
50     ++size_;
51     DCHECK_LE(size_, kMaxSize);
52     // Relies on integer overflow behavior.
53     data_[back_index_++ & mask_] = value;
54   }
55 
front()56   const T& front() const {
57     DCHECK_GT(size_, 0U);
58     return data_[(back_index_ - size_) & mask_];
59   }
60 
pop_front()61   void pop_front() {
62     DCHECK_GT(size_, 0U);
63     --size_;
64   }
65 
66  private:
67   static const size_t mask_ = kMaxSize - 1;
68   size_t back_index_, size_;
69   T data_[kMaxSize];
70 };
71 
72 }  // namespace art
73 
74 #endif  // ART_RUNTIME_BASE_BOUNDED_FIFO_H_
75