2021-12-05 17:54:36 +00:00
|
|
|
#pragma once
|
2023-12-23 17:24:16 +00:00
|
|
|
|
2024-10-30 07:30:20 +00:00
|
|
|
#ifndef BINARYIO_H
|
|
|
|
#define BINARYIO_H
|
2023-12-23 17:24:16 +00:00
|
|
|
|
2021-12-05 17:54:36 +00:00
|
|
|
#include <iostream>
|
|
|
|
#include <fstream>
|
2023-12-23 17:24:16 +00:00
|
|
|
#include <string>
|
|
|
|
|
|
|
|
#include "Game.h"
|
|
|
|
#include "Logger.h"
|
2021-12-05 17:54:36 +00:00
|
|
|
|
|
|
|
namespace BinaryIO {
|
2023-12-23 17:24:16 +00:00
|
|
|
|
2021-12-05 17:54:36 +00:00
|
|
|
template<typename T>
|
|
|
|
std::ostream& BinaryWrite(std::ostream& stream, const T& value) {
|
|
|
|
return stream.write(reinterpret_cast<const char*>(&value), sizeof(T));
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename T>
|
|
|
|
std::istream& BinaryRead(std::istream& stream, T& value) {
|
2022-11-01 18:21:26 +00:00
|
|
|
if (!stream.good()) throw std::runtime_error("Failed to read from istream.");
|
2021-12-05 17:54:36 +00:00
|
|
|
|
|
|
|
return stream.read(reinterpret_cast<char*>(&value), sizeof(T));
|
|
|
|
}
|
|
|
|
|
2023-12-23 17:24:16 +00:00
|
|
|
enum class ReadType : int8_t {
|
|
|
|
WideString = 0,
|
|
|
|
String = 1,
|
|
|
|
};
|
|
|
|
|
|
|
|
template<typename SizeType>
|
|
|
|
inline void ReadString(std::istream& stream, std::u16string& value) {
|
|
|
|
static_assert(std::is_integral<SizeType>::value, "SizeType must be an integral type.");
|
|
|
|
|
|
|
|
SizeType size;
|
|
|
|
BinaryRead(stream, size);
|
|
|
|
|
|
|
|
if (!stream.good()) throw std::runtime_error("Failed to read from istream.");
|
|
|
|
value.resize(size);
|
|
|
|
stream.read(reinterpret_cast<char*>(value.data()), size * sizeof(uint16_t));
|
|
|
|
}
|
|
|
|
|
|
|
|
template<typename SizeType>
|
|
|
|
inline void ReadString(std::istream& stream, std::string& value, ReadType readType) {
|
|
|
|
static_assert(std::is_integral<SizeType>::value, "SizeType must be an integral type.");
|
|
|
|
|
|
|
|
SizeType size;
|
|
|
|
BinaryRead(stream, size);
|
|
|
|
|
|
|
|
if (!stream.good()) throw std::runtime_error("Failed to read from istream.");
|
|
|
|
value.resize(size);
|
|
|
|
if (readType == ReadType::WideString) {
|
|
|
|
uint16_t wideChar;
|
|
|
|
|
|
|
|
// Faster to do this than to read a u16string and convert it to a string since we only go through allocator once
|
|
|
|
for (SizeType i = 0; i < size; ++i) {
|
|
|
|
BinaryRead(stream, wideChar);
|
|
|
|
value[i] = static_cast<char>(wideChar);
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
stream.read(value.data(), size);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-11-01 18:21:26 +00:00
|
|
|
std::string ReadString(std::istream& instream);
|
2021-12-05 17:54:36 +00:00
|
|
|
|
|
|
|
inline bool DoesFileExist(const std::string& name) {
|
|
|
|
std::ifstream f(name.c_str());
|
|
|
|
return f.good();
|
|
|
|
}
|
|
|
|
}
|
2023-12-23 17:24:16 +00:00
|
|
|
|
2024-10-30 07:30:20 +00:00
|
|
|
#endif //!BINARYIO_H
|