From 0aaba7a461341916f61929e0a8ea871055d8dd73 Mon Sep 17 00:00:00 2001 From: Dmitry Frank Date: Tue, 12 Sep 2017 19:08:43 +0300 Subject: [PATCH] Add cs_timegm Which is a slightly modified version from https://stackoverflow.com/questions/283166/easy-way-to-convert-a-struct-tm-expressed-in-utc-to-time-t-type PUBLISHED_FROM=b73f920ca42c45473c23337782e815306bdf69f1 --- mongoose.c | 35 +++++++++++++++++++++++++++++++++++ mongoose.h | 8 ++++++++ 2 files changed, 43 insertions(+) diff --git a/mongoose.c b/mongoose.c index d7599397..b3461bf7 100644 --- a/mongoose.c +++ b/mongoose.c @@ -780,6 +780,41 @@ double cs_time(void) { #endif /* _WIN32 */ return now; } + +double cs_timegm(const struct tm *tm) { + /* Month-to-day offset for non-leap-years. */ + static const int month_day[12] = {0, 31, 59, 90, 120, 151, + 181, 212, 243, 273, 304, 334}; + + /* Most of the calculation is easy; leap years are the main difficulty. */ + int month = tm->tm_mon % 12; + int year = tm->tm_year + tm->tm_mon / 12; + int year_for_leap; + int64_t rt; + + if (month < 0) { /* Negative values % 12 are still negative. */ + month += 12; + --year; + } + + /* This is the number of Februaries since 1900. */ + year_for_leap = (month > 1) ? year + 1 : year; + + rt = + tm->tm_sec /* Seconds */ + + + 60 * + (tm->tm_min /* Minute = 60 seconds */ + + + 60 * (tm->tm_hour /* Hour = 60 minutes */ + + + 24 * (month_day[month] + tm->tm_mday - 1 /* Day = 24 hours */ + + 365 * (year - 70) /* Year = 365 days */ + + (year_for_leap - 69) / 4 /* Every 4 years is leap... */ + - (year_for_leap - 1) / 100 /* Except centuries... */ + + (year_for_leap + 299) / 400))); /* Except 400s. */ + return rt < 0 ? -1 : (double) rt; +} #ifdef MG_MODULE_LINES #line 1 "common/cs_endian.h" #endif diff --git a/mongoose.h b/mongoose.h index 78482c2e..2822d9bc 100644 --- a/mongoose.h +++ b/mongoose.h @@ -1797,6 +1797,8 @@ void cs_hmac_sha1(const unsigned char *key, size_t key_len, #ifndef CS_COMMON_CS_TIME_H_ #define CS_COMMON_CS_TIME_H_ +#include + /* Amalgamated: #include "common/platform.h" */ #ifdef __cplusplus @@ -1806,6 +1808,12 @@ extern "C" { /* Sub-second granularity time(). */ double cs_time(void); +/* + * Similar to (non-standard) timegm, converts broken-down time into the number + * of seconds since Unix Epoch. + */ +double cs_timegm(const struct tm *tm); + #ifdef __cplusplus } #endif /* __cplusplus */