From 9ec06749f253c6a2b0ecea10fffc0022acd930ca Mon Sep 17 00:00:00 2001 From: Jose Marcial Vieira Bisneto Date: Tue, 13 Dec 2016 22:16:51 -0300 Subject: [PATCH] Initial implementation of util/time.c --- include/ipfs/util/time.h | 12 ++++++++ util/time.c | 59 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 71 insertions(+) create mode 100644 include/ipfs/util/time.h create mode 100644 util/time.c diff --git a/include/ipfs/util/time.h b/include/ipfs/util/time.h new file mode 100644 index 0000000..3d49f5c --- /dev/null +++ b/include/ipfs/util/time.h @@ -0,0 +1,12 @@ +#ifndef IPFS_TIME_H + #define IPFS_TIME_H + + struct stime { + time_t t; + struct timespec ts; + }; + + int get_gmttime(struct stime *st); + int ipfs_util_time_parse_RFC3339 (struct stime *st, char *s); + char *ipfs_util_time_format_RFC3339 (struct stime *st); +#endif // IPFS_TIME_H diff --git a/util/time.c b/util/time.c new file mode 100644 index 0000000..b438eb8 --- /dev/null +++ b/util/time.c @@ -0,0 +1,59 @@ +#include +#include +#include + +#ifndef __USE_XOPEN + #define __USE_XOPEN +#endif // __USE_XOPEN + +#ifndef __USE_ISOC11 + #define __USE_ISOC11 +#endif // __USE_ISOC11 + +#include +#include "ipfs/util/time.h" + +int get_gmttime(struct stime *st) { + if (!st) { + return 1; + } + if (!timespec_get(&st->ts, TIME_UTC) || + !time(&st->t)) { + return 2; + } + return 0; +} + +int ipfs_util_time_parse_RFC3339 (struct stime *st, char *s) +{ + char *r; + struct tm tm; + + if (!st || !s || strlen(s) != 35) { + return 1; + } + r = strptime (s, "%Y-%m-%dT%H:%M:%S", &tm); + if (!r || *r != '.') { + return 2; + } + st->t = mktime(&tm); + st->ts.tv_nsec = atoll(++r); + return 0; +} + +char *ipfs_util_time_format_RFC3339 (struct stime *st) +{ + char buf[31], *ret; + + ret = malloc(36); + if (!ret) { + return NULL; + } + + if (strftime(buf, sizeof(buf), "%Y-%m-%dT%H:%M:%S.%%09dZ00:00", gmtime(&st->t)) != sizeof(buf)-1 || + snprintf(ret, 36, buf, st->ts.tv_nsec) != 35) { + free (ret); + return NULL; + } + return ret; +}