Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove more regex (backport #2897) #2907

Merged
merged 1 commit into from
Jan 26, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 31 additions & 12 deletions src/value.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -758,28 +758,47 @@ int DateValue::read(const byte* buf, size_t len, ByteOrder /*byteOrder*/) {
int DateValue::read(const std::string& buf) {
// ISO 8601 date formats:
// https://web.archive.org/web/20171020084445/https://www.loc.gov/standards/datetime/ISO_DIS%208601-1.pdf
static const std::regex reExtended(R"(^(\d{4})-(\d{2})-(\d{2}))");
static const std::regex reBasic(R"(^(\d{4})(\d{2})(\d{2}))");
std::smatch sm;
size_t monthPos = 0;
size_t dayPos = 0;

auto printWarning = [] {
#ifndef SUPPRESS_WARNINGS
EXV_WARNING << Error(ErrorCode::kerUnsupportedDateFormat) << "\n";
#endif
};

// Note: We use here regex_search instead of regex_match, because the string can be longer than expected and
// also contain the time
if (std::regex_search(buf, sm, reExtended) || std::regex_search(buf, sm, reBasic)) {
date_.year = std::stoi(sm[1].str());
date_.month = std::stoi(sm[2].str());
if (date_.month > 12) {
date_.month = 0;
if (buf.size() < 8) {
printWarning();
return 1;
}

if ((buf.size() >= 10 && buf[4] == '-' && buf[7] == '-') || (buf.size() == 8)) {
if (buf.size() >= 10) {
monthPos = 5;
dayPos = 8;
} else {
monthPos = 4;
dayPos = 6;
}

auto checkDigits = [&buf, &printWarning](size_t start, size_t count, int32_t& dest) {
for (size_t i = start; i < start + count; ++i) {
if (!std::isdigit(buf[i])) {
printWarning();
return 1;
}
}
dest = std::stoul(buf.substr(start, count));
return 0;
};

if (checkDigits(0, 4, date_.year) || checkDigits(monthPos, 2, date_.month) || checkDigits(dayPos, 2, date_.day)) {
printWarning();
return 1;
}
date_.day = std::stoi(sm[3].str());
if (date_.day > 31) {

if (date_.month > 12 || date_.day > 31) {
date_.month = 0;
date_.day = 0;
printWarning();
return 1;
Expand Down
Loading