diff options
author | Mattias Andrée <maandree@kth.se> | 2024-01-09 22:04:24 +0100 |
---|---|---|
committer | Mattias Andrée <maandree@kth.se> | 2024-01-09 22:04:24 +0100 |
commit | ae850b1ac755f471beac4dbfef4654fe3fbaaae9 (patch) | |
tree | 319e7f7f1b99cd1ee75e100f0a29b0f7c827ccea /libpatch_create_timestamp.c | |
download | libpatch-ae850b1ac755f471beac4dbfef4654fe3fbaaae9.tar.gz libpatch-ae850b1ac755f471beac4dbfef4654fe3fbaaae9.tar.bz2 libpatch-ae850b1ac755f471beac4dbfef4654fe3fbaaae9.tar.xz |
First commit
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to 'libpatch_create_timestamp.c')
-rw-r--r-- | libpatch_create_timestamp.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/libpatch_create_timestamp.c b/libpatch_create_timestamp.c new file mode 100644 index 0000000..54b6d91 --- /dev/null +++ b/libpatch_create_timestamp.c @@ -0,0 +1,58 @@ +/* See LICENSE file for copyright and license details. */ +#include "common.h" + + +size_t +libpatch_create_timestamp(char *buf, size_t bufsize, const struct tm *tm, + uintmax_t subseconds, unsigned subseconds_decimals, + unsigned frac, int zone, enum libpatch_style style) +{ + size_t guess, len, r; + const char *fmt; + + frac = MIN(frac, subseconds_decimals); + + if (style == LIBPATCH_STYLE_COPIED) { + fmt = "%a %b %e %T %Y"; + guess = sizeof("aaa bbb 00 00:00:00 0000"); + } else if (style == LIBPATCH_STYLE_UNIFIED) { + fmt = "%Y-%m-%d %H:%M:%S"; + zone = 1; + guess = sizeof("0000-00-00 00:00:00"); + } else { + errno = EINVAL; + return 0; + } + + if (zone) + guess += sizeof(" +0000"); + guess += (size_t)frac + (size_t)(frac > 0); + + if (!bufsize) + return guess; + + while (subseconds_decimals != frac) { + subseconds /= 10; + subseconds_decimals -= 1; + } + + len = strftime(buf, bufsize, fmt, tm); + if (!len) + return bufsize < guess ? guess : bufsize + 16U; + + if (frac) { + if (len < bufsize) + snprintf(&buf[len], bufsize - len, ".%0*ju", (int)frac, subseconds); + len += (size_t)frac + (size_t)(frac > 0); + } + + if (zone) { + if (len < bufsize) + return bufsize < len + 7U ? len + 7U : bufsize + 16U; + len += r = strftime(&buf[len], bufsize - len, " %z", tm); + if (!r) + return bufsize < len + 7U ? len + 7U : bufsize + 16U; + } + + return len + 1; +} |