60 lines
1.7 KiB
C++
60 lines
1.7 KiB
C++
#pragma once
|
|
#include <ircolib/types.hpp>
|
|
#include <fstream>
|
|
#include <vector>
|
|
#include <filesystem>
|
|
|
|
namespace ircolib {
|
|
namespace fs = std::filesystem;
|
|
|
|
static inline std::vector<u8> read_file_binary(const std::string &path) {
|
|
std::ifstream file(path, std::ios::binary);
|
|
return {std::istreambuf_iterator{file}, {}};
|
|
}
|
|
|
|
static inline std::vector<u8> read_file_binary(const std::string &path, uint32_t size, uint32_t offset = 0) {
|
|
FILE *file = fopen(path.c_str(), "rb");
|
|
if (!file)
|
|
return {};
|
|
|
|
std::vector<u8> res;
|
|
|
|
fseek(file, offset, SEEK_SET);
|
|
|
|
res.resize(size);
|
|
fread(res.data(), 1, size, file);
|
|
fclose(file);
|
|
|
|
return res;
|
|
}
|
|
|
|
static inline void write_file_binary(const std::vector<u8> &data, const std::string &path) {
|
|
std::ofstream file(path, std::ios::binary);
|
|
std::copy(data.begin(), data.end(), std::ostreambuf_iterator{file});
|
|
}
|
|
|
|
static inline void write_file_binary(const u8 *data, const u32 size, const std::string &path) {
|
|
FILE *out = fopen(path.c_str(), "wb");
|
|
fwrite(data, size, 1, out);
|
|
fclose(out);
|
|
}
|
|
|
|
template <size_t Size>
|
|
static inline void write_file_binary(const std::array<u8, Size> &data, const std::string &path) {
|
|
std::ofstream file(path, std::ios::binary);
|
|
std::copy(data.begin(), data.end(), std::ostreambuf_iterator{file});
|
|
}
|
|
|
|
static inline u32 next_pow2(u32 num) {
|
|
// Taken from "Bit Twiddling Hacks" by Sean Anderson:
|
|
// https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
|
|
--num;
|
|
num |= num >> 1;
|
|
num |= num >> 2;
|
|
num |= num >> 4;
|
|
num |= num >> 8;
|
|
num |= num >> 16;
|
|
return num + 1;
|
|
}
|
|
} // namespace ircolib
|