环形缓冲区
英文: Circular buffer, Ring buffer.
实现
template <typename T>
class Circular {
public:
using value_type = T;
Circular(std::size_t max_size) : max_size_(max_size) {
data_ = std::make_unique<value_type[]>(max_size_);
}
void push_front(const value_type& value) {
assert(size() < max_size());
size_++;
const auto front = (back_ + (size_ - 1)) % max_size_;
data_[front] = value;
}
value_type pop_back() {
assert(!empty());
const auto value = data_[back_];
back_ = (back_ + 1) % max_size_;
size_--;
return value;
}
std::size_t size() const noexcept { return size_; }
std::size_t size_bytes() const noexcept { return size() * sizeof(value_type); }
bool empty() const noexcept { return size_ == 0; }
std::size_t max_size() const noexcept { return max_size_; }
std::size_t max_size_bytes() const noexcept { return max_size() * sizeof(value_type); }
private:
std::unique_ptr<value_type[]> data_;
std::size_t back_ = 0;
std::size_t size_ = 0;
std::size_t max_size_;
};