-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathEncoder.cpp
54 lines (45 loc) · 1.19 KB
/
Encoder.cpp
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
#include "Encoder.h"
#include <stdexcept>
#include <sstream>
using namespace bencode;
class EncodeVisitor : public boost::static_visitor<std::string>
{
public:
std::string operator()(int value) const
{
std::stringstream stream;
stream << "i" << value << "e";
return stream.str();
}
std::string operator()(const std::string& value) const
{
std::stringstream stream;
stream << value.size() << ":" << value;
return stream.str();
}
std::string operator()(const ValueDictionary& dict) const
{
std::stringstream stream;
stream << "d";
for (ValueDictionary::const_iterator i = dict.begin();
i != dict.end(); ++i) {
stream << (*this)(i->first)
<< boost::apply_visitor(EncodeVisitor(), i->second);
}
stream << "e";
return stream.str();
}
std::string operator()(const ValueVector& vec) const
{
std::stringstream stream;
stream << "l";
for (ValueVector::const_iterator i = vec.begin(); i != vec.end(); ++i)
stream << boost::apply_visitor(EncodeVisitor(), *i);
stream << "e";
return stream.str();
}
};
std::string Encoder::encode(const Value& value)
{
return boost::apply_visitor(EncodeVisitor(), value);
}