Last active
November 17, 2023 19:39
-
-
Save ayushgun/225f0468e255e123cf8a8e5eb8135184 to your computer and use it in GitHub Desktop.
A simple, generic buffer that accumulates items in a queue and processes them when a specified capacity is reached.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#pragma once | |
#include <cstddef> | |
#include <functional> | |
#include <queue> | |
// A buffer class that accumulates items in a queue and processes them when a | |
// specified capacity is reached. | |
template <typename T, std::size_t Capacity> | |
class Buffer { | |
private: | |
std::function<void(std::deque<T>&)> handler; | |
public: | |
std::deque<T> data; | |
// Constructs a Buffer object with a given flush handler | |
Buffer(const std::function<void(std::deque<T>&)> flush_handler) | |
: handler{flush_handler} {} | |
// Adds an element to the buffer. Flushes the buffer if it reaches its | |
// capacity | |
void push(const T& value) { | |
data.push_back(value); | |
if (data.size() >= Capacity) { | |
flush(); | |
} | |
} | |
// Flushes the buffer by processing and emptying the queue. This method calls | |
// the handler function to process the queue's elements | |
void flush() { | |
handler(data); | |
data = std::deque<T>(); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment