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 namespace art { 21 22 // A bounded fifo is a fifo which has a bounded size. The power of two version uses a bit mask to 23 // avoid needing to deal with wrapping integers around or using a modulo operation. 24 template <typename T, const size_t MaxSize> 25 class BoundedFifoPowerOfTwo { 26 public: BoundedFifoPowerOfTwo()27 BoundedFifoPowerOfTwo() { 28 // TODO: Do this with a compile time check. 29 CHECK(IsPowerOfTwo(MaxSize)); 30 clear(); 31 } 32 clear()33 void clear() { 34 back_index_ = 0; 35 size_ = 0; 36 } 37 empty()38 bool empty() const { 39 return size() == 0; 40 } 41 size()42 size_t size() const { 43 return size_; 44 } 45 push_back(const T & value)46 void push_back(const T& value) { 47 ++size_; 48 DCHECK_LE(size_, MaxSize); 49 // Relies on integer overflow behavior. 50 data_[back_index_++ & mask_] = value; 51 } 52 front()53 const T& front() const { 54 DCHECK_GT(size_, 0U); 55 return data_[(back_index_ - size_) & mask_]; 56 } 57 pop_front()58 void pop_front() { 59 DCHECK_GT(size_, 0U); 60 --size_; 61 } 62 63 private: 64 static const size_t mask_ = MaxSize - 1; 65 size_t back_index_, size_; 66 T data_[MaxSize]; 67 }; 68 69 } // namespace art 70 71 #endif // ART_RUNTIME_BASE_BOUNDED_FIFO_H_ 72