Skip to content

Commit

Permalink
feat(Stream): implement write to path
Browse files Browse the repository at this point in the history
  • Loading branch information
lmichaelis committed Dec 27, 2023
1 parent 46e9ea4 commit fc75d4b
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
1 change: 1 addition & 0 deletions include/zenkit/Stream.hh
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ namespace zenkit {
virtual void seek(ssize_t off, Whence whence) noexcept = 0;
[[nodiscard]] virtual size_t tell() const noexcept = 0;

[[nodiscard]] static std::unique_ptr<Write> to(std::filesystem::path const& path);
[[nodiscard]] static std::unique_ptr<Write> to(::FILE* stream);
[[nodiscard]] static std::unique_ptr<Write> to(std::ostream* stream);
[[nodiscard]] static std::unique_ptr<Write> to(std::byte* bytes, size_t len);
Expand Down
18 changes: 17 additions & 1 deletion src/Stream.cc
Original file line number Diff line number Diff line change
Expand Up @@ -373,7 +373,18 @@ namespace zenkit {

class WriteStream ZKINT : public Write {
public:
explicit WriteStream(std::ostream* stream) : _m_stream(stream) {}
explicit WriteStream(std::ostream* stream) : _m_stream(stream), _m_own(false) {}
explicit WriteStream(std::filesystem::path const& path)
: _m_stream(new std::ofstream(path)), _m_own(true) {}

~WriteStream() noexcept override {
if (_m_own) {
delete _m_stream;

_m_own = false;
_m_stream = nullptr;
}
}

size_t write(void const* buf, size_t len) noexcept override {
_m_stream->write(static_cast<char const*>(buf), static_cast<long>(len));
Expand All @@ -390,6 +401,7 @@ namespace zenkit {

private:
std::ostream* _m_stream;
bool _m_own;
};

class WriteStatic ZKINT : public Write {
Expand Down Expand Up @@ -492,6 +504,10 @@ namespace zenkit {
return std::make_unique<detail::ReadBuffer>(buf);
}

std::unique_ptr<Write> Write::to(std::filesystem::path const& path) {
return std::make_unique<detail::WriteStream>(path);
}

std::unique_ptr<Write> Write::to(::FILE* stream) {
return std::make_unique<detail::WriteFile>(stream);
}
Expand Down

0 comments on commit fc75d4b

Please sign in to comment.