// Copyright 2024 The DMBMX2Tools Authors // SPDX-License-Identifier: MIT #include #include namespace dmtools::io { constexpr auto DmToLibc(StreamSeekDirection dir) { using enum StreamSeekDirection; switch(dir) { case Beg: return SEEK_SET; case Cur: return SEEK_CUR; case End: return SEEK_END; default: return SEEK_SET; } } constexpr auto DmOpenMode(FileStream::OpenMode mode) { using enum FileStream::OpenMode; switch(mode) { case Read: return "rb"; case ReadWrite: return "wb+"; } } FileStream::~FileStream() { Close(); } bool FileStream::Open(const std::string& filename, OpenMode mode) { file = std::fopen(filename.c_str(), DmOpenMode(mode)); return Ok(); } void FileStream::Flush() { fflush(static_cast(file)); } void FileStream::Close() { if(Ok()) { fclose(static_cast(file)); } } StreamDiff FileStream::ReadSome(u8* buffer, usize length) { if(Ok()) return std::fread(static_cast(buffer), 1, length, static_cast(file)); return -1; } StreamDiff FileStream::WriteSome(const u8* buffer, usize length) { if(Ok()) return std::fwrite(static_cast(buffer), length, 1, static_cast(file)); return -1; } StreamDiff FileStream::Seek(StreamDiff where, StreamSeekDirection dir) { if(!Ok()) return -1; #ifdef __GLIBC__ return fseeko64(static_cast(file), where, DmToLibc(dir)); #else return fseek(static_cast(file), where, DmToLibc(dir)); #endif } StreamDiff FileStream::Tell() const { if(!Ok()) return -1; #ifdef __GLIBC__ return ftello64(static_cast(file)); #else return ftell(static_cast(file)); #endif } bool FileStream::Ok() const { return file != nullptr; } bool FileStream::Eof() const { if(!Ok()) return true; return feof(static_cast(file)); } } // namespace dmtools::io