blob: 444f31a55bd8a7a9b7c6fc995d71d835ff7f8be0 [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
David Sehrc431b9d2018-03-02 12:01:51 -080017#ifndef ART_LIBARTBASE_BASE_BOUNDED_FIFO_H_
18#define ART_LIBARTBASE_BASE_BOUNDED_FIFO_H_
Mathieu Chartier94c32c52013-08-09 11:14:04 -070019
Andreas Gampe57943812017-12-06 21:39:13 -080020#include <android-base/logging.h>
21
Vladimir Marko80afd022015-05-19 18:08:00 +010022#include "base/bit_utils.h"
Vladimir Marko80afd022015-05-19 18:08:00 +010023
Mathieu Chartier94c32c52013-08-09 11:14:04 -070024namespace art {
25
26// A bounded fifo is a fifo which has a bounded size. The power of two version uses a bit mask to
27// avoid needing to deal with wrapping integers around or using a modulo operation.
Vladimir Marko80afd022015-05-19 18:08:00 +010028template <typename T, const size_t kMaxSize>
Mathieu Chartier94c32c52013-08-09 11:14:04 -070029class BoundedFifoPowerOfTwo {
Vladimir Marko80afd022015-05-19 18:08:00 +010030 static_assert(IsPowerOfTwo(kMaxSize), "kMaxSize must be a power of 2.");
31
Mathieu Chartier94c32c52013-08-09 11:14:04 -070032 public:
33 BoundedFifoPowerOfTwo() {
Mathieu Chartier94c32c52013-08-09 11:14:04 -070034 clear();
35 }
36
37 void clear() {
38 back_index_ = 0;
39 size_ = 0;
40 }
41
42 bool empty() const {
43 return size() == 0;
44 }
45
46 size_t size() const {
47 return size_;
48 }
49
50 void push_back(const T& value) {
51 ++size_;
Vladimir Marko80afd022015-05-19 18:08:00 +010052 DCHECK_LE(size_, kMaxSize);
Ian Rogersb122a4b2013-11-19 18:00:50 -080053 // Relies on integer overflow behavior.
Mathieu Chartier94c32c52013-08-09 11:14:04 -070054 data_[back_index_++ & mask_] = value;
55 }
56
57 const T& front() const {
58 DCHECK_GT(size_, 0U);
59 return data_[(back_index_ - size_) & mask_];
60 }
61
62 void pop_front() {
63 DCHECK_GT(size_, 0U);
64 --size_;
65 }
66
67 private:
Vladimir Marko80afd022015-05-19 18:08:00 +010068 static const size_t mask_ = kMaxSize - 1;
Mathieu Chartier94c32c52013-08-09 11:14:04 -070069 size_t back_index_, size_;
Vladimir Marko80afd022015-05-19 18:08:00 +010070 T data_[kMaxSize];
Mathieu Chartier94c32c52013-08-09 11:14:04 -070071};
72
73} // namespace art
74
David Sehrc431b9d2018-03-02 12:01:51 -080075#endif // ART_LIBARTBASE_BASE_BOUNDED_FIFO_H_