1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
|
#include "message.hpp"
#include <iterator>
#include <ios>
#include <sstream>
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<std::string>(*this).size();
}
template <typename InputIt, typename OutputIt, typename UnaryPredicate>
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<char>{in};
auto end = std::istream_iterator<char>{};
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)};
}
in.clear(in.rdstate() ^ std::ios_base::failbit);
return in;
}
std::ostream & operator<<(std::ostream & out, message const & message)
{
return out << static_cast<std::string>(message);
}
} // namespace wanda
|