Skip to content

Commit 1c5c79f

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 d689323 commit 1c5c79f

File tree

2 files changed

+23
-5
lines changed

2 files changed

+23
-5
lines changed

include/bencode.hpp

Lines changed: 19 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -344,6 +344,24 @@ namespace bencode {
344344
requires stringish<typename T::key_type>;
345345
};
346346

347+
template<typename T>
348+
std::string quoted_key(const T &key) {
349+
std::string s;
350+
s.reserve(key.size() + 2);
351+
s.push_back('"');
352+
for(auto &&i : key) {
353+
char c = static_cast<char>(i);
354+
switch(c) {
355+
case '\0': s.append("\\0"); break;
356+
case '\n': s.append("\\n"); break;
357+
case '"': s.append("\\\""); break;
358+
default: s.push_back(c);
359+
}
360+
}
361+
s.push_back('"');
362+
return s;
363+
}
364+
347365
template<std::integral Integer>
348366
inline void check_overflow(Integer value, Integer digit) {
349367
using limits = std::numeric_limits<Integer>;
@@ -523,7 +541,7 @@ namespace bencode {
523541
auto i = p->emplace(std::move(dict_key), std::move(thing));
524542
if(!i.second) {
525543
throw syntax_error(
526-
"duplicated key in dict: " + std::string(i.first->first)
544+
"duplicated key in dict: " + quoted_key(i.first->first)
527545
);
528546
}
529547
return &i.first->second;

test/test_decode.cpp

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

417417
_.test("duplicated key", []() {
418-
expect(
419-
[]() { bencode::decode("d3:fooi1e3:fooi1ee"); },
420-
decode_error<bencode::syntax_error>("duplicated key in dict: foo", 17)
421-
);
418+
expect([]() { bencode::decode("d3:fooi1e3:fooi1ee"); },
419+
decode_error<bencode::syntax_error>(
420+
"duplicated key in dict: \"foo\"", 17
421+
));
422422
});
423423
});
424424

0 commit comments

Comments
 (0)