SRS-control 0.1.4
 
Loading...
Searching...
No Matches
BinaryFileWriter.hpp
Go to the documentation of this file.
1#pragma once
2
3#include <string>
4
5#include <boost/asio.hpp>
6#include <boost/asio/experimental/coro.hpp>
7
11
12namespace srs::writer
13{
15 {
16 public:
17 using InputType = std::string_view;
18 using OutputType = int;
19 using CoroType = asio::experimental::coro<OutputType(std::optional<InputType>)>;
20 using InputFuture = boost::shared_future<std::optional<InputType>>;
21 using OutputFuture = boost::unique_future<std::optional<OutputType>>;
22 static constexpr auto IsStructType = false;
23
24 explicit BinaryFile(asio::thread_pool& thread_pool,
25 const std::string& filename,
27 : convert_mode_{ deser_mode }
28 , file_name_{ filename }
29 , ofstream_{ filename, std::ios::trunc }
30 {
31 if (not ofstream_.is_open())
32 {
33 throw std::runtime_error(fmt::format("Filename {:?} cannot be open!", filename));
34 }
35 coro_ = generate_coro(thread_pool.get_executor());
36 common::coro_sync_start(coro_, std::optional<InputType>{}, asio::use_awaitable);
37 }
38 auto write(auto pre_future) -> OutputFuture { return common::create_coro_future(coro_, pre_future); }
39 auto get_convert_mode() const -> process::DataConvertOptions { return convert_mode_; }
40 void close() { ofstream_.close(); }
41
42 private:
44 std::string file_name_;
45 std::ofstream ofstream_;
47
48 // NOLINTNEXTLINE(readability-static-accessed-through-instance)
49 auto generate_coro(asio::any_io_executor /*unused*/) -> CoroType
50 {
51 auto write_msg = std::string_view{};
52 while (true)
53 {
54 if (not write_msg.empty())
55 {
56 ofstream_ << write_msg;
57 }
58 auto msg = co_yield static_cast<int>(write_msg.size());
59
60 if (msg.has_value())
61 {
62 write_msg = msg.value();
63 }
64 else
65 {
66 close();
67 spdlog::info("Binary file {} is closed successfully", file_name_);
68 co_return;
69 }
70 }
71 }
72 };
73} // namespace srs::writer
auto generate_coro(asio::any_io_executor) -> CoroType
auto get_convert_mode() const -> process::DataConvertOptions
BinaryFile(asio::thread_pool &thread_pool, const std::string &filename, process::DataConvertOptions deser_mode)
auto write(auto pre_future) -> OutputFuture
process::DataConvertOptions convert_mode_
asio::experimental::coro< OutputType(std::optional< InputType >)> CoroType
boost::unique_future< std::optional< OutputType > > OutputFuture
boost::shared_future< std::optional< InputType > > InputFuture
static constexpr auto IsStructType
auto create_coro_future(auto &coro, auto &&pre_fut)
void coro_sync_start(auto &coro, auto &&... args)