MSVC: compat: implement localtime_r

The Windows version of localtime_s swaps the argument order and has a
different return type for increased level of fun.
diff --git a/CMakeModules/UseCompat.cmake b/CMakeModules/UseCompat.cmake
index 31bd59f..d81f28c 100644
--- a/CMakeModules/UseCompat.cmake
+++ b/CMakeModules/UseCompat.cmake
@@ -52,6 +52,7 @@
     check_symbol_exists(timezone time.h HAVE_TIME_H_TIMEZONE)
 
     check_symbol_exists(realpath "stdlib.h" HAVE_REALPATH)
+    check_symbol_exists(localtime_r "time.h" HAVE_LOCALTIME_R)
 
     unset(CMAKE_REQUIRED_DEFINITIONS)
     unset(CMAKE_REQUIRED_LIBRARIES)
diff --git a/compat/compat.c b/compat/compat.c
index d721616..fe50092 100644
--- a/compat/compat.c
+++ b/compat/compat.c
@@ -268,3 +268,22 @@
 #error No realpath() implementation for this platform is available.
 #endif
 #endif
+
+#ifndef HAVE_LOCALTIME_R
+#ifdef _WIN32
+struct tm *
+localtime_r(const time_t *timep, struct tm *result)
+{
+    errno_t res = localtime_s(result, timep);
+
+    if (res) {
+        return NULL;
+    } else {
+        return result;
+    }
+}
+
+#else
+#error No localtime_r() implementation for this platform is available.
+#endif
+#endif
diff --git a/compat/compat.h.in b/compat/compat.h.in
index d84eeb4..64c916b 100644
--- a/compat/compat.h.in
+++ b/compat/compat.h.in
@@ -62,6 +62,7 @@
 #cmakedefine HAVE_TM_GMTOFF
 #cmakedefine HAVE_TIME_H_TIMEZONE
 #cmakedefine HAVE_REALPATH
+#cmakedefine HAVE_LOCALTIME_R
 
 #ifndef bswap64
 #define bswap64(val) \
@@ -163,4 +164,8 @@
 char *realpath(const char *path, char *resolved_path);
 #endif
 
+#ifndef HAVE_LOCALTIME_R
+struct tm *localtime_r(const time_t *timep, struct tm *result);
+#endif
+
 #endif /* _COMPAT_H_ */