Created
March 22, 2020 22:10
-
-
Save devimc/54ad017fdb0109728c29576d21033be2 to your computer and use it in GitHub Desktop.
metaprogramming: parse 24-hour clock to seconds
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Copyright (c) 2020 Julio Montes | |
// | |
// SPDX-License-Identifier: Apache-2.0 | |
// | |
// convert a string in format 24h to seconds at compile time | |
#include <stdexcept> | |
#include <string> | |
using namespace std; | |
namespace time_parse { | |
// HH:MM:SS | |
// ^ | |
constexpr const char hoursOffset = 0; | |
// HH:MM:SS | |
// ^ | |
constexpr const char minutesOffset = 3; | |
// HH:MM:SS | |
// ^ | |
constexpr const char secondsOffset = 6; | |
// HH:MM:SS | |
constexpr const char timeLength = 8; | |
constexpr time_t parseDigit(char d) { | |
return ('0' <= d && d <= '9') | |
? d - '0' | |
: throw std::domain_error{"invalid character in time"}; | |
} | |
constexpr time_t parseTime(const char *t, time_t multipler) { | |
return (parseDigit(t[0]) * 10 * multipler) + (parseDigit(t[1]) * multipler); | |
} | |
template <size_t N> constexpr time_t format24hToSeconds(const char (&s)[N]) { | |
return (N - 1 != timeLength) | |
? throw std:: | |
domain_error{"expecting string in the form hh:mm:ss"} | |
: parseTime(s + hoursOffset, 60 * 60) + | |
parseTime(s + minutesOffset, 60) + | |
parseTime(s + secondsOffset, 1); | |
} | |
} // namespace time_parse | |
int main() { | |
constexpr const char t[] = "01:01:20"; | |
constexpr const time_t v = time_parse::format24hToSeconds(t); | |
printf("%s to seconds: %ld\n", t, v); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment