Rindro-Plugins/Include/IO_Ex.hpp

126 lines
3.0 KiB
C++

#pragma once
#include <iostream>
#include <fstream>
#include <cctype>
#include <algorithm>
#include <vector>
using namespace std;
// 定义宏用于注册获取不同类型值的函数
#define REGISTER_GET_FUNCTION(Type, FunctionName) \
Type Get##FunctionName() { \
char buffer[sizeof(Type)]; \
read(buffer, sizeof(Type)); \
Type result; \
std::memcpy(&result, buffer, sizeof(Type)); \
return result; \
}
class IO_Ex
{
public:
//原始数据
char* _Data;
//最大长度
int _MaxLen = 0;
//当前位置
int _CurPos = 0;
//上一次读取的实际大小
int _LastReadSize = 0;
public:
IO_Ex(char* data,int len) {
_Data = data;
_MaxLen = len;
}
~IO_Ex();
public:
int tellg() {
return _CurPos;
}
void read(char* ptr, int size) {
if ((size + _CurPos) > _MaxLen) {
size = _MaxLen - _CurPos;
}
memcpy(ptr, _Data + _CurPos, size);
_CurPos += size;
_LastReadSize = size;
}
int gcount() {
return _LastReadSize;
}
void seek(int _jidx) {
_CurPos = _jidx;
}
public:
unsigned int charPtrToInt(const char* bytes) {
unsigned int result;
std::memcpy(&result, bytes, sizeof(int));
return result;
}
void CrcDecode(const int Length, const int crc32) {
int num = 0x81A79011;
for (int i = 0; i < Length; i += 4)
{
int Pos = tellg();
char buffer[4];
read(buffer, 4);
unsigned int anInt = charPtrToInt(buffer);
unsigned int val = (anInt ^ num ^ crc32);
unsigned int jiemi = (val >> 6) | ((val << (32 - 6)) & 0xFFFFFFFF);
_Data[Pos] = ((jiemi >> 0) & 0xFF);;
_Data[Pos + 1] = ((jiemi >> 8) & 0xFF);
_Data[Pos + 2] = ((jiemi >> 16) & 0xFF);
_Data[Pos + 3] = ((jiemi >> 24) & 0xFF);
}
}
std::string tolower(std::string str) {
for (size_t i = 0; i < str.length(); ++i) {
str[i] = std::tolower(str[i]);
}
return str;
}
std::vector<std::string> split(const std::string& str, const std::string& delimiter) {
std::vector<std::string> tokens;
size_t pos = 0;
size_t found;
while ((found = str.find(delimiter, pos)) != std::string::npos) {
tokens.push_back(str.substr(pos, found - pos));
pos = found + delimiter.length();
}
tokens.push_back(str.substr(pos));
return tokens;
}
public:
REGISTER_GET_FUNCTION(int, Int);
REGISTER_GET_FUNCTION(short, Short);
REGISTER_GET_FUNCTION(unsigned short, UShort);
std::string GetString(const int size) {
char* buffer = new char[size];
read(buffer, size);
if (gcount() != size) {
std::cerr << "未能成功读取指定字节数的数据!" << std::endl;
delete[] buffer;
return "";
}
std::string result(buffer, size);
delete[] buffer;
return result;
}
private:
};
IO_Ex::~IO_Ex()
{
}