88 lines
2.3 KiB
C++
88 lines
2.3 KiB
C++
|
#pragma once
|
||
|
#include <stddef.h>
|
||
|
#include <string>
|
||
|
#include <filesystem>
|
||
|
#include <vector>
|
||
|
namespace fs = std::filesystem;
|
||
|
class MemoryCat {
|
||
|
const void *ptr;
|
||
|
size_t len;
|
||
|
bool owned;
|
||
|
public:
|
||
|
inline size_t get_len() {
|
||
|
return len;
|
||
|
}
|
||
|
inline const void *get_ptr() {
|
||
|
return (const void*)ptr;
|
||
|
}
|
||
|
inline ~MemoryCat() {
|
||
|
if (owned) free((void*)ptr);
|
||
|
}
|
||
|
/// \brief Constructor that doesn't take ownership of the pointer
|
||
|
inline MemoryCat(const void *ptr, size_t len) {
|
||
|
this->owned = false;
|
||
|
this->ptr = ptr;
|
||
|
this->len = len;
|
||
|
}
|
||
|
/// \brief Constructor that takes ownership of the pointer
|
||
|
inline MemoryCat(void *ptr, size_t len) {
|
||
|
this->owned = true;
|
||
|
this->ptr = ptr;
|
||
|
this->len = len;
|
||
|
}
|
||
|
};
|
||
|
enum class CatDataType {
|
||
|
Memory,
|
||
|
File
|
||
|
};
|
||
|
class CatData {
|
||
|
std::optional<MemoryCat> mem;
|
||
|
fs::path path;
|
||
|
std::string name;
|
||
|
CatDataType type;
|
||
|
public:
|
||
|
inline std::string get_name() {
|
||
|
return name;
|
||
|
}
|
||
|
inline CatDataType get_type() {
|
||
|
return type;
|
||
|
}
|
||
|
inline fs::path get_path() {
|
||
|
return path;
|
||
|
}
|
||
|
inline MemoryCat get_memory_cat() {
|
||
|
if (type == CatDataType::Memory) {
|
||
|
return mem.value();
|
||
|
} else {
|
||
|
throw std::exception();
|
||
|
}
|
||
|
}
|
||
|
inline MemoryCat as_memory_cat() {
|
||
|
if (mem.has_value()) return mem.value();
|
||
|
if (type == CatDataType::File) {
|
||
|
FILE *file = fopen(path.c_str(), "rb");
|
||
|
fseek(file, 0, SEEK_END);
|
||
|
size_t len = ftell(file);
|
||
|
fseek(file, 0, SEEK_SET);
|
||
|
void *ptr = malloc(len);
|
||
|
len = fread(ptr, 1, len, file);
|
||
|
ptr = realloc(ptr, len);
|
||
|
MemoryCat output(ptr, len);
|
||
|
this->mem = output;
|
||
|
return output;
|
||
|
}
|
||
|
throw std::exception();
|
||
|
}
|
||
|
inline CatData(const void *ptr, size_t len, std::string name, fs::path virtual_path) {
|
||
|
this->type = CatDataType::Memory;
|
||
|
this->name = name;
|
||
|
this->path = virtual_path;
|
||
|
this->mem = MemoryCat(ptr, len);
|
||
|
}
|
||
|
inline CatData(fs::path path) {
|
||
|
this->name = path.stem();
|
||
|
this->type = CatDataType::File;
|
||
|
this->path = path;
|
||
|
}
|
||
|
};
|
||
|
extern std::vector<CatData> &get_cat_data();
|