blob: 7bcd38202297e1cff3a41a45f394c77c3e4ae6d2 [file] [log] [blame]
Mathieu Chartier94c32c52013-08-09 11:14:04 -07001/*
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
Vladimir Marko80afd022015-05-19 18:08:00 +010020#include "base/bit_utils.h"
21#include "base/logging.h"
22
Mathieu Chartier94c32c52013-08-09 11:14:04 -070023namespace 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.
Vladimir Marko80afd022015-05-19 18:08:00 +010027template <typename T, const size_t kMaxSize>
Mathieu Chartier94c32c52013-08-09 11:14:04 -070028class BoundedFifoPowerOfTwo {
Vladimir Marko80afd022015-05-19 18:08:00 +010029 static_assert(IsPowerOfTwo(kMaxSize), "kMaxSize must be a power of 2.");
30
Mathieu Chartier94c32c52013-08-09 11:14:04 -070031 public:
32 BoundedFifoPowerOfTwo() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -070033 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_;
Vladimir Marko80afd022015-05-19 18:08:00 +010051 DCHECK_LE(size_, kMaxSize);
Ian Rogersb122a4b2013-11-19 18:00:50 -080052 // Relies on integer overflow behavior.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070053 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:
Vladimir Marko80afd022015-05-19 18:08:00 +010067 static const size_t mask_ = kMaxSize - 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070068 size_t back_index_, size_;
Vladimir Marko80afd022015-05-19 18:08:00 +010069 T data_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -070070};
71
72} // namespace art
73
74#endif // ART_RUNTIME_BASE_BOUNDED_FIFO_H_