DF-0
DF-0: Data processing Framework with Zero-overhead
Loading...
Searching...
No Matches
plain_text_exporter.h
1/**************************************************************************/
2/* */
3/* DF-0: Data processing Framework with Zero-overhead */
4/* */
5/* Copyright (c) DF-0 Team https://github.com/df0-io/df0 */
6/* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-DF0-Commercial */
7/* */
8/**************************************************************************/
9
10#ifndef DF0_PLAIN_TEXT_EXPORTER_H
11#define DF0_PLAIN_TEXT_EXPORTER_H
12
13#include "pipeline/element_base.hpp"
14#include <functional>
15#include <memory>
16#include <sstream>
17#include "document_elements.h"
18#include "error_tags.h"
19#include "plain_text/output_width.h"
20#include "plain_text_writer.h"
21#include "data_source.h"
22#include "throw_if.h"
23
24namespace df0
25{
26using df0::plain_text::output_width;
27
28struct eol_sequence { std::string v; };
29
31{
32 std::function<std::string(const document::link&)> format_opening;
33 std::function<std::string(const document::close_link&)> format_closing;
34};
35
39class plain_text_exporter : public pipeline::transformer_element<plain_text_exporter>
40{
41public:
42 plain_text_exporter(eol_sequence eol = eol_sequence{"\n"},
43 link_formatter formatter = default_link_formatter,
44 output_width max_output_width = output_width{80})
45 : m_writer{eol.v, formatter.format_opening, formatter.format_closing, max_output_width}
46 {}
47
48 continuation operator()(message_ptr msg, const message_callbacks& emit_message);
49
50private:
51 inline static const link_formatter default_link_formatter =
52 {
53 .format_opening = [](const document::link& link)
54 {
55 return link.url ? "<" + *link.url + ">" : "";
56 },
57 .format_closing = [](const document::close_link&)
58 {
59 return "";
60 }
61 };
62
63 std::shared_ptr<std::stringstream> m_stream;
64 plain_text_writer m_writer;
65 int m_nested_docs_level{0};
66};
67
68inline continuation plain_text_exporter::operator()(message_ptr msg, const message_callbacks& emit_message)
69{
70 if (msg->is<std::exception_ptr>())
71 return emit_message(std::move(msg));
72 if (msg->is<document::document>() || !m_stream)
73 {
74 ++m_nested_docs_level;
75 if (m_nested_docs_level == 1)
76 m_stream = std::make_shared<std::stringstream>();
77 }
78 m_writer.write_to(msg, *m_stream);
79 if (msg->is<document::close_document>())
80 {
81 DF0_THROW_IF(m_nested_docs_level <= 0, errors::program_logic{});
82 --m_nested_docs_level;
83 if (m_nested_docs_level == 0)
84 {
85 emit_message(data_source{seekable_stream_ptr{m_stream}, mime_type{"text/plain"}, confidence::highest});
86 m_stream.reset();
87 }
88 }
89 return continuation::proceed;
90}
91
92} // namespace df0
93
94#endif //DF0_PLAIN_TEXT_EXPORTER_H
void write_to(const message_ptr &msg, std::ostream &stream) override
Converts text from callback to plain text format.
Callback bundle used by pipeline elements to emit messages.
Definition message.h:90