spdlog/include/spdlog/details/circular_q.h

63 lines
1.3 KiB
C
Raw Normal View History

2018-07-03 17:38:23 -04:00
//
// Copyright(c) 2018 Gabi Melman.
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
//
// cirucal q view of std::vector.
#pragma once
namespace spdlog {
namespace details {
template<typename T>
class circular_q
{
public:
using item_type = T;
explicit circular_q(size_t max_items)
: max_items_(max_items + 1) // one item is reserved as marker for full q
2018-07-03 17:38:23 -04:00
, v_(max_items_)
{
}
// push back, overrun (oldest) item if no room left
2018-07-03 17:38:23 -04:00
void push_back(T &&item)
{
v_[tail_] = std::move(item);
tail_ = (tail_ + 1) % max_items_;
2018-07-03 17:38:23 -04:00
if (tail_ == head_) // overrun last item if full
2018-07-03 17:38:23 -04:00
{
head_ = (head_ + 1) % max_items_;
2018-07-03 17:38:23 -04:00
}
}
// Pop item from front.
// If there are no elements in the container, the behavior is undefined.
void pop_front(T &popped_item)
{
popped_item = std::move(v_[head_]);
head_ = (head_ + 1) % max_items_;
2018-07-03 17:38:23 -04:00
}
bool empty()
{
return tail_ == head_;
2018-07-03 17:38:23 -04:00
}
bool full()
{
// head is ahead of the tail by 1
return ((tail_ + 1) % max_items_) == head_;
2018-07-03 17:38:23 -04:00
}
private:
size_t max_items_;
typename std::vector<T>::size_type head_ = 0;
typename std::vector<T>::size_type tail_ = 0;
2018-07-03 17:38:23 -04:00
std::vector<T> v_;
};
} // namespace details
} // namespace spdlog