From 7de3b20a6ccf527743d18be5ca3d74dc749cb083 Mon Sep 17 00:00:00 2001 From: Redbeanw44602 Date: Sat, 1 Mar 2025 00:43:01 +0800 Subject: [PATCH] feat: add streamed_io. --- src/data_format/io/streamed_io.cpp | 17 ++++++++++++ src/data_format/io/streamed_io.h | 43 ++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+) create mode 100644 src/data_format/io/streamed_io.cpp create mode 100644 src/data_format/io/streamed_io.h diff --git a/src/data_format/io/streamed_io.cpp b/src/data_format/io/streamed_io.cpp new file mode 100644 index 0000000..4f2c398 --- /dev/null +++ b/src/data_format/io/streamed_io.cpp @@ -0,0 +1,17 @@ +#include "data_format/io/streamed_io.h" + +namespace di { + +void StreamedIO::read(const fs::path& path) { + m_file_stream.open(path, std::ios::binary); + if (!m_file_stream) { + throw std::runtime_error("Failed to open file!"); + } +} + +void StreamedIO::write(const fs::path& path) const { + std::fstream ofs(path, std::ios::binary); + ofs << m_file_stream.rdbuf(); +} + +} // namespace di \ No newline at end of file diff --git a/src/data_format/io/streamed_io.h b/src/data_format/io/streamed_io.h new file mode 100644 index 0000000..42c97b8 --- /dev/null +++ b/src/data_format/io/streamed_io.h @@ -0,0 +1,43 @@ +#pragma once + +#include "data_format/io/io_base.h" + +namespace di { + +class StreamedIO : public IOBase { +public: + void read(const fs::path& path) override; + void write(const fs::path& path) const override; + + constexpr auto next() { return m_file_stream.peek(); } + + // Avoid confusion with the function that opens a file, so use eat + // instead of read. Maybe come up with another name for write as well. + // + // TODO: write() method. + + template + constexpr T eat() { + T value; + m_file_stream.read((char*)&value, sizeof(T)); + return value; + } + + template + constexpr T eat_varint() { + T res = 0; + int shift = 0; + while (true) { + auto byte = m_file_stream.get(); + res |= static_cast(byte & 0x7F) << shift; + if ((byte & 0x80) == 0) break; + shift += 7; + } + return res; + } + +private: + std::ifstream m_file_stream; +}; + +} // namespace di