Here’s a tight, single-function RLE encoder that works directly on std::vector<uint8_t>.
It emits (count, value) pairs where 1 ≤ count ≤ 255; longer runs are split automatically.
cpp
#include <vector>
#include <cstdint>
/// RLE encode: (count, value) pairs, count ∈ [1,255].
/// Worst-case output is 2×input, so we reserve that up-front.
inline std::vector<uint8_t> rle_encode(const std::vector<uint8_t>& in)
{
const std::size_t n = in.size();
if (n == 0) return {}; // nothing to do
std::vector<uint8_t> out;
out.reserve(n * 2); // worst-case (no compression)
const uint8_t* cur = in.data();
const uint8_t* end = cur + n;
uint8_t value = *cur++; // current run value
uint8_t run = 1; // current run length
while (cur != end)
{
if (*cur == value && run != 0xFF) // keep extending the run
{
++run;
}
else // flush current run
{
out.emplace_back(run);
out.emplace_back(value);
value = *cur;
run = 1;
}
++cur;
}
// flush final run
out.emplace_back(run);
out.emplace_back(value);
out.shrink_to_fit(); // drop spare capacity (optional)
return out;
}
Why this version is “effective”
• Single pass, O(n) time, branch-predictable.
• Pointer walking (in.data()) instead of iterator overhead.
• reserve(n*2) guarantees at most one reallocation.
• Split runs >255 automatically, so no UB on overflow.
• Inlined (inline) for zero call-overhead in headers / TUs.
Usage example
cpp
std::vector<uint8_t> raw = { 5,5,5,1,2,2,2,2,2,2,2,3 };
auto encoded = rle_encode(raw); // -> {3,5,1,1,7,2,1,3}
That’s it—drop the function into a header and you’re good to go. Happy encoding! 🚀