Skip to content

Commit 3f185f8

Browse files
committed
Quote the dict key in exceptions
(This is really mainly important because we'll be able to stringify other character types, e.g. bytes.)
1 parent a0751b5 commit 3f185f8

File tree

2 files changed

+27
-5
lines changed

2 files changed

+27
-5
lines changed

include/bencode.hpp

Lines changed: 23 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -346,6 +346,28 @@ namespace bencode {
346346
template<typename T>
347347
inline constexpr bool is_iterable_v = is_iterable<T>::value;
348348

349+
template<typename T>
350+
std::string quoted_key(const T &key) {
351+
std::string s;
352+
s.reserve(key.size() + 2);
353+
s.push_back('"');
354+
for (auto &&i : key) {
355+
char c = static_cast<char>(i);
356+
switch(c) {
357+
case '\n':
358+
s.append("\\n");
359+
break;
360+
case '"':
361+
s.append("\\\"");
362+
break;
363+
default:
364+
s.push_back(c);
365+
}
366+
}
367+
s.push_back('"');
368+
return s;
369+
}
370+
349371
template<typename Integer>
350372
inline void check_overflow(Integer value, Integer digit) {
351373
using limits = std::numeric_limits<Integer>;
@@ -541,7 +563,7 @@ namespace bencode {
541563
auto i = p->emplace(std::move(dict_key), std::move(thing));
542564
if(!i.second) {
543565
throw syntax_error(
544-
"duplicated key in dict: " + std::string(i.first->first)
566+
"duplicated key in dict: " + quoted_key(i.first->first)
545567
);
546568
}
547569
return &i.first->second;

test/test_decode.cpp

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -417,10 +417,10 @@ suite<> test_decode("test decoder", [](auto &_) {
417417
});
418418

419419
_.test("duplicated key", []() {
420-
expect(
421-
[]() { bencode::decode("d3:fooi1e3:fooi1ee"); },
422-
decode_error<bencode::syntax_error>("duplicated key in dict: foo", 17)
423-
);
420+
expect([]() { bencode::decode("d3:fooi1e3:fooi1ee"); },
421+
decode_error<bencode::syntax_error>(
422+
"duplicated key in dict: \"foo\"", 17
423+
));
424424
});
425425
});
426426

0 commit comments

Comments
 (0)