diff --git a/include/sp/io/FileIO.h b/include/sp/io/FileIO.h new file mode 100644 index 0000000..23a659b --- /dev/null +++ b/include/sp/io/FileIO.h @@ -0,0 +1,35 @@ +#pragma once + +#include +#include + +namespace sp { + +struct FileTag {}; + +template <> +class IOInterface { + private: + std::ofstream m_FileOutput; + std::ifstream m_FileInput; + + public: + IOInterface(const std::string& filePath) : m_FileOutput(filePath), m_FileInput(filePath) {} + IOInterface(IOInterface&& other) : m_FileOutput(std::move(other.m_FileOutput)), m_FileInput(std::move(other.m_FileInput)) {} + + DataBuffer Read(std::size_t a_Amount) { + DataBuffer buffer; + buffer.Resize(a_Amount); + m_FileInput.read(reinterpret_cast(buffer.data()), a_Amount); + return buffer; + } + + void Write(const sp::DataBuffer& a_Data) { + m_FileOutput.write(reinterpret_cast(a_Data.data()), a_Data.GetSize()); + m_FileOutput.flush(); + } +}; + +using FileIO = IOInterface; + +} // namespace sp diff --git a/include/sp/io/IOInterface.h b/include/sp/io/IOInterface.h index 31b96a7..a749f54 100644 --- a/include/sp/io/IOInterface.h +++ b/include/sp/io/IOInterface.h @@ -74,6 +74,9 @@ void IOStream::RecieveMessages() { throw std::runtime_error("VarInt is too big"); } + // nothing to read + if (lenghtValue == 0) + return; DataBuffer buffer; buffer = m_Interface.Read(lenghtValue); diff --git a/test/test_file.cpp b/test/test_file.cpp new file mode 100644 index 0000000..35d9251 --- /dev/null +++ b/test/test_file.cpp @@ -0,0 +1,37 @@ +#include + +#include +#include + +class CustomPacketHandler : public sp::PacketHandler { + void Handle(const KeepAlivePacket& packet) { + std::cout << "KeepAlive handled ! " << packet.GetKeepAliveId() << "\n"; + } + + void Handle(const DisconnectPacket& packet) { + std::cout << "Disconnect handled ! " << packet.GetReason() << "\n"; + } + + void Handle(const UpgradeTowerPacket& packet) { + std::cout << "UpgradeTower handled !\n"; + } +}; + +using FileStream = sp::IOStream; + + +int main() { + auto handler = std::make_shared(); + + FileStream stream(sp::FileIO{"test.txt"}); + stream.GetDispatcher().RegisterHandler(PacketId::Disconnect, handler); + stream.GetDispatcher().RegisterHandler(PacketId::KeepAlive, handler); + + stream.SendMessage(KeepAlivePacket{96}); + stream.SendMessage(KeepAlivePacket{69}); + stream.SendMessage(DisconnectPacket{"This is in the file !"}); + + stream.RecieveMessages(); + + return 0; +} \ No newline at end of file