2021-02-14 01:11:55 +01:00
|
|
|
#include "helpers/encoding_file.hpp"
|
|
|
|
|
|
|
|
#include <hex/helpers/utils.hpp>
|
|
|
|
|
|
|
|
#include <fstream>
|
|
|
|
|
|
|
|
namespace hex {
|
|
|
|
|
2021-09-08 15:18:24 +02:00
|
|
|
EncodingFile::EncodingFile(Type type, const std::string &path) {
|
|
|
|
std::ifstream encodingFile(path.c_str());
|
2021-02-14 01:11:55 +01:00
|
|
|
|
|
|
|
switch (type) {
|
|
|
|
case Type::Thingy: parseThingyFile(encodingFile); break;
|
|
|
|
default: throw std::runtime_error("Invalid encoding file type");
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
std::pair<std::string_view, size_t> EncodingFile::getEncodingFor(const std::vector<u8> &buffer) const {
|
2021-10-09 23:07:58 +02:00
|
|
|
for (auto riter = this->m_mapping.crbegin(); riter != this->m_mapping.crend(); ++riter) {
|
|
|
|
const auto &[size, mapping] = *riter;
|
|
|
|
|
2021-02-14 01:11:55 +01:00
|
|
|
if (size > buffer.size()) continue;
|
|
|
|
|
|
|
|
auto key = std::vector<u8>(buffer.begin(), buffer.begin() + size);
|
|
|
|
if (mapping.contains(key))
|
|
|
|
return { mapping.at(key), size };
|
|
|
|
}
|
|
|
|
|
|
|
|
return { ".", 1 };
|
|
|
|
}
|
|
|
|
|
|
|
|
void EncodingFile::parseThingyFile(std::ifstream &content) {
|
|
|
|
for (std::string line; std::getline(content, line);) {
|
|
|
|
|
2021-02-14 12:05:58 +01:00
|
|
|
std::string from, to;
|
|
|
|
{
|
|
|
|
auto delimiterPos = line.find('=', 0);
|
2021-02-14 01:11:55 +01:00
|
|
|
|
2021-02-14 12:05:58 +01:00
|
|
|
if (delimiterPos == std::string::npos)
|
|
|
|
continue;
|
2021-02-14 01:11:55 +01:00
|
|
|
|
2021-02-14 12:05:58 +01:00
|
|
|
from = line.substr(0, delimiterPos);
|
|
|
|
to = line.substr(delimiterPos + 1);
|
|
|
|
|
|
|
|
hex::trim(from);
|
|
|
|
hex::trim(to);
|
|
|
|
|
2021-02-14 12:32:48 +01:00
|
|
|
if (from.empty()) continue;
|
2021-02-14 12:05:58 +01:00
|
|
|
if (to.empty()) to = " ";
|
|
|
|
}
|
2021-02-14 01:11:55 +01:00
|
|
|
|
|
|
|
auto fromBytes = hex::parseByteString(from);
|
2021-02-14 12:32:48 +01:00
|
|
|
if (fromBytes.empty()) continue;
|
|
|
|
|
2021-02-14 01:11:55 +01:00
|
|
|
if (!this->m_mapping.contains(fromBytes.size()))
|
|
|
|
this->m_mapping.insert({ fromBytes.size(), { } });
|
|
|
|
this->m_mapping[fromBytes.size()].insert({ fromBytes, to });
|
|
|
|
|
|
|
|
this->m_longestSequence = std::max(this->m_longestSequence, fromBytes.size());
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|