Skip to content

Commit fc1c3fe

Browse files
authored
Reject trailing characters when parsing rfl::Timestamp (#736)
1 parent e01b193 commit fc1c3fe

2 files changed

Lines changed: 17 additions & 2 deletions

File tree

‎include/rfl/Timestamp.hpp‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
#ifndef RFL_TIMESTAMP_HPP_
22
#define RFL_TIMESTAMP_HPP_
33

4+
#include <cstring>
45
#include <ctime>
56
#include <iomanip>
67
#include <sstream>
@@ -35,7 +36,7 @@ class Timestamp {
3536
/// @throws std::runtime_error if the string doesn't match the format
3637
Timestamp(const char* _str) : tm_(std::tm{}) {
3738
const auto r = strptime(_str, _format.str().c_str(), &tm_);
38-
if (r == NULL) {
39+
if (r == NULL || *r != '\0') {
3940
throw std::runtime_error("String '" + std::string(_str) +
4041
"' did not match format '" + Format().str() +
4142
"'.");
@@ -169,7 +170,12 @@ class Timestamp {
169170
if (input.fail()) {
170171
return NULL;
171172
}
172-
return (char*)(_s + input.tellg());
173+
const auto pos = input.tellg();
174+
if (pos == std::streampos(-1)) {
175+
// The stream reached EOF, so all of the input was consumed.
176+
return (char*)(_s + std::strlen(_s));
177+
}
178+
return (char*)(_s + static_cast<std::ptrdiff_t>(pos));
173179
}
174180
#endif
175181

‎tests/json/test_timestamp.cpp‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,4 +25,13 @@ TEST(json, test_timestamp) {
2525
bart,
2626
R"({"firstName":"Bart","lastName":"Simpson","birthday":"1987-04-19"})");
2727
}
28+
29+
TEST(json, test_timestamp_trailing_characters) {
30+
EXPECT_TRUE(!TS::from_string("1987-04-19T10:00:00"));
31+
EXPECT_TRUE(!TS::from_string("1987-04-19x"));
32+
33+
const auto res = rfl::json::read<Person>(
34+
R"({"firstName":"Bart","lastName":"Simpson","birthday":"1987-04-19x"})");
35+
EXPECT_TRUE(!res);
36+
}
2837
} // namespace test_timestamp

0 commit comments

Comments
 (0)