Files

104 lines
2.1 KiB
C++
Raw Permalink Normal View History

2026-03-10 18:49:34 -07:00
#include "FileIO.hpp"
#include <SDL3/SDL_iostream.h>
#include <cstdint>
#include <utility>
namespace aurora::card {
FileIO::FileIO(std::string_view filename, bool truncate) {
m_path = filename;
SDL_IOStream* stream = nullptr;
2026-03-10 18:49:34 -07:00
stream = fileOpen(m_path.c_str(), truncate ? "w+b" : "r+b");
if (stream != nullptr) {
SDL_FlushIO(stream);
SDL_CloseIO(stream);
m_ready = true;
2026-03-10 18:49:34 -07:00
}
}
FileIO::FileIO(FileIO&& other) noexcept {
m_path = std::move(other.m_path);
m_ready = std::exchange(other.m_ready, false);
2026-03-10 18:49:34 -07:00
}
FileIO& FileIO::operator=(FileIO&& other) noexcept {
if (this != &other) {
m_path = std::move(other.m_path);
m_ready = std::exchange(other.m_ready, false);
2026-03-10 18:49:34 -07:00
}
return *this;
}
bool FileIO::fileRead(void* buf, size_t length, off_t offset) {
if (!isReady()) {
return false;
}
SDL_IOStream* stream = fileOpen(m_path, "rb");
if (stream == nullptr) {
return false;
}
if (SDL_SeekIO(stream, offset, SDL_IO_SEEK_SET) < 0) {
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return false;
}
size_t total = 0;
auto* dst = static_cast<uint8_t*>(buf);
while (total < length) {
const size_t read = SDL_ReadIO(stream, dst + total, length - total);
2026-03-10 18:49:34 -07:00
if (read == 0) {
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return false;
}
total += read;
}
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return true;
}
bool FileIO::fileWrite(const void* buf, size_t length, off_t offset) {
if (!isReady()) {
return false;
}
SDL_IOStream* stream = fileOpen(m_path, "r+b");
if (stream == nullptr) {
stream = fileOpen(m_path, "w+b");
}
if (stream == nullptr) {
return false;
}
if (SDL_SeekIO(stream, offset, SDL_IO_SEEK_SET) < 0) {
SDL_FlushIO(stream);
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return false;
}
size_t total = 0;
auto* src = static_cast<const uint8_t*>(buf);
while (total < length) {
const size_t written = SDL_WriteIO(stream, src + total, length - total);
2026-03-10 18:49:34 -07:00
if (written == 0) {
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return false;
}
total += written;
}
SDL_FlushIO(stream);
SDL_CloseIO(stream);
2026-03-10 18:49:34 -07:00
return true;
}
FileIO::operator bool() const { return isReady(); }
} // namespace aurora::card