looper/cats.hpp
Zachary Hall 9899794b81
Some checks failed
Build / build-gentoo (push) Failing after 1m11s
Build / download-system-deps (push) Successful in 3m44s
Build / get-source-code (push) Successful in 13m23s
Build / build-deb (push) Successful in 11m40s
Build / build-appimage (push) Successful in 4m53s
Build / build-android (push) Failing after 3m19s
Build / build-windows (push) Failing after 8m9s
Add cat support
2024-12-21 14:23:00 -08:00

88 lines
No EOL
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();