Last active
October 11, 2020 10:27
-
-
Save JuanDiegoMontoya/5a4150467465136cadeca7733a8f414f to your computer and use it in GitHub Desktop.
An implementation of run-length encoding for arbitrary types in C++20.
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 <span> | |
#include <vector> | |
namespace Compression | |
{ | |
template<typename T> | |
struct RLEelement | |
{ | |
uint32_t count{}; | |
T value{}; | |
}; | |
template<typename T> | |
std::vector<RLEelement<T>> EncodeRLE(std::span<T> array) | |
{ | |
std::vector<RLEelement<T>> data; | |
RLEelement<T> curElement{ .value = array[0] }; | |
for (auto value : array) | |
{ | |
if (value != curElement.value) | |
{ | |
data.push_back(curElement); | |
curElement = RLEelement<T>{ .count = 0, .value = value }; | |
} | |
curElement.count++; | |
} | |
if (curElement.count > 0) | |
data.push_back(curElement); | |
return data; | |
} | |
template<typename T> | |
std::vector<T> DecodeRLE(std::span<RLEelement<T>> data) | |
{ | |
std::vector<T> array; | |
for (auto rlee : data) | |
{ | |
array.insert(array.end(), rlee.count, rlee.value); | |
} | |
return array; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment