From 50f153df882c59e6ba4ec56d1b7ec81ba95f3dd0 Mon Sep 17 00:00:00 2001 From: Sebastian Reimers Date: Wed, 7 Feb 2024 13:24:41 +0100 Subject: [PATCH] fmt/time: add fmt_timestamp_us --- cmake/re-config.cmake | 1 + include/re_fmt.h | 7 ++++--- src/fmt/time.c | 40 ++++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 3 deletions(-) diff --git a/cmake/re-config.cmake b/cmake/re-config.cmake index 68c0c80cd..023714475 100644 --- a/cmake/re-config.cmake +++ b/cmake/re-config.cmake @@ -140,6 +140,7 @@ if(WIN32) list(APPEND RE_DEFINITIONS WIN32 _WIN32_WINNT=0x0600 + _UCRT ) unset(CMAKE_EXTRA_INCLUDE_FILES) diff --git a/include/re_fmt.h b/include/re_fmt.h index af4cd1841..2f4cdfbe2 100644 --- a/include/re_fmt.h +++ b/include/re_fmt.h @@ -179,9 +179,10 @@ static inline bool str_isset(const char *s) /* time */ -int fmt_gmtime(struct re_printf *pf, void *ts); -int fmt_timestamp(struct re_printf *pf, void *ts); -int fmt_human_time(struct re_printf *pf, const uint32_t *seconds); +int fmt_gmtime(struct re_printf *pf, void *ts); +int fmt_timestamp(struct re_printf *pf, void *ts); +int fmt_timestamp_us(struct re_printf *pf, void *arg); +int fmt_human_time(struct re_printf *pf, const uint32_t *seconds); void hexdump(FILE *f, const void *p, size_t len); diff --git a/src/fmt/time.c b/src/fmt/time.c index a0001fd89..ecf5873f6 100644 --- a/src/fmt/time.c +++ b/src/fmt/time.c @@ -4,6 +4,10 @@ * Copyright (C) 2010 Creytiv.com */ +#ifdef __MINGW32__ +#define _POSIX_C_SOURCE +#endif + #include #ifdef WIN32 @@ -129,3 +133,39 @@ int fmt_timestamp(struct re_printf *pf, void *arg) return re_hprintf(pf, "%02u:%02u:%02u.%03llu", h, m, s, ms); } + + +/** + * Print local time stamp including microseconds relative to user's timezone + * + * @param pf Print function for output + * @param arg Not used + * + * @return 0 if success, otherwise errorcode + */ +int fmt_timestamp_us(struct re_printf *pf, void *arg) +{ + int h, m, s; + uint64_t us; + struct timespec tspec; + struct tm tm; + +#if defined(WIN32) && !defined(__MINGW32__) + timespec_get(&tspec, TIME_UTC); + int err = localtime_s(&tm, &tspec.tv_sec); + if (err) + return err; +#else + (void)clock_gettime(CLOCK_REALTIME, &tspec); + if (!localtime_r(&tspec.tv_sec, &tm)) + return EINVAL; +#endif + + h = tm.tm_hour; + m = tm.tm_min; + s = tm.tm_sec; + us = tspec.tv_nsec / 1000; + (void)arg; + + return re_hprintf(pf, "%02u:%02u:%02u.%06llu", h, m, s, us); +}