1
0
mirror of synced 2024-11-15 11:33:23 +01:00
ImHex/source/helpers/encoding_file.cpp
WerWolv e74c0f5cf5 sys: Tons of long overdue cleanup
- std::string -> const std::string& where needed
- Added a FileIO abstraction class
- Fixed recent files not updating
- Removed localization file from global include
- Renamed lang to pattern_language/pl
- Renamed EventFileDropped to RequestFileOpen
2021-09-08 15:18:24 +02:00

62 lines
1.8 KiB
C++

#include "helpers/encoding_file.hpp"
#include <ranges>
#include <hex/helpers/utils.hpp>
#include <fstream>
namespace hex {
EncodingFile::EncodingFile(Type type, const std::string &path) {
std::ifstream encodingFile(path.c_str());
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 {
for (const auto &[size, mapping] : this->m_mapping | std::views::reverse) {
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);) {
std::string from, to;
{
auto delimiterPos = line.find('=', 0);
if (delimiterPos == std::string::npos)
continue;
from = line.substr(0, delimiterPos);
to = line.substr(delimiterPos + 1);
hex::trim(from);
hex::trim(to);
if (from.empty()) continue;
if (to.empty()) to = " ";
}
auto fromBytes = hex::parseByteString(from);
if (fromBytes.empty()) continue;
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());
}
}
}