From 9c2231c8fb45f32c7b1d23e14125bc58ea405e60 Mon Sep 17 00:00:00 2001 From: Felix Morgner Date: Fri, 30 Nov 2018 15:53:53 +0100 Subject: core: implement basic message type --- src/message.cpp | 75 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 src/message.cpp (limited to 'src/message.cpp') diff --git a/src/message.cpp b/src/message.cpp new file mode 100644 index 0000000..ad76897 --- /dev/null +++ b/src/message.cpp @@ -0,0 +1,75 @@ +#include "message.hpp" + +#include +#include +#include + +namespace wanda +{ + +message::operator std::string() const +{ + std::ostringstream buffer{}; + buffer << source + << ':' + << command; + if(argument.has_value()) + { + buffer << ':' << *argument; + } + return buffer.str(); +} + +std::size_t message::size() const +{ + return static_cast(*this).size(); +} + +template +OutputIt copy_until(InputIt first, InputIt last, OutputIt out, UnaryPredicate predicate) +{ + while (first != last && !predicate(*first)) + { + *out++ = *first++; + } + return out; +} + +std::istream &operator>>(std::istream &in, message &message) +{ + auto pos = std::istream_iterator{in}; + auto end = std::istream_iterator{}; + auto buffer = std::string{}; + + copy_until(pos, end, std::back_inserter(buffer), [](auto const &c) { return c == ':'; }); + if (in.eof() || buffer.size() != 1) + { + in.setstate(std::ios_base::failbit); + return in; + } + message.source = buffer; + + buffer.clear(); + copy_until(++pos, end, std::back_inserter(buffer), [](auto const &c) { return c == ':'; }); + if (in.eof()) + { + in.setstate(std::ios_base::failbit); + } + message.command = buffer; + + buffer.clear(); + copy(++pos, end, std::back_inserter(buffer)); + if (buffer.size()) + { + message.argument = std::optional{std::move(buffer)}; + } + + return in; +} + +std::ostream & operator<<(std::ostream & out, message const & message) +{ + return out << static_cast(message); +} + +} // namespace wanda \ No newline at end of file -- cgit v1.2.3