From 926c2766b03c1fc09a5b5de08021d9ed048d821d Mon Sep 17 00:00:00 2001 From: Chloe Kudryavtsev Date: Sat, 13 May 2023 10:56:58 -0400 Subject: add shortcuts for *time(mktime) --- src/date.h | 5 +++++ src/tm.c | 75 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++---- 2 files changed, 76 insertions(+), 4 deletions(-) diff --git a/src/date.h b/src/date.h index 3661421..615b2bc 100644 --- a/src/date.h +++ b/src/date.h @@ -17,7 +17,12 @@ JANET_CFUN(jd_time); // tm.c extern const JanetRegExt jd_tm_cfuns[]; struct tm *jd_gettm(Janet *argv, int32_t n); +struct tm *jd_opttm(Janet *argv, int32_t argc, int32_t n); struct tm *jd_maketm(void); JANET_CFUN(jd_mktime); JANET_CFUN(jd_mktime_inplace); +JANET_CFUN(jd_time_localtime); +JANET_CFUN(jd_time_localtime_inplace); +JANET_CFUN(jd_time_utc); +JANET_CFUN(jd_time_utc_inplace); JANET_CFUN(jd_strftime); diff --git a/src/tm.c b/src/tm.c index d078def..6f245eb 100644 --- a/src/tm.c +++ b/src/tm.c @@ -4,10 +4,16 @@ // wrappers around struct tm static JanetMethod jd_tm_methods[] = { - {"mktime", jd_mktime}, - {"mktime!", jd_mktime_inplace}, - {"normalize", jd_mktime_inplace}, - {"strftime", jd_strftime}, + // raw mktime, returning time_t + {"mktime", jd_mktime}, + {"mktime!", jd_mktime_inplace}, + // shortcut for localtime(mktime) + {"localtime", jd_time_localtime}, + {"localtime!", jd_time_localtime_inplace}, + // shortcut for gmtime(mktime) + {"utc", jd_time_utc}, + {"utc!", jd_time_utc_inplace}, + {"strftime", jd_strftime}, {NULL, NULL}, }; @@ -155,6 +161,13 @@ struct tm *jd_maketm(void) { return janet_abstract(&jd_tm_t, sizeof(struct tm)); } +struct tm *jd_opttm(Janet *argv, int32_t argc, int32_t n) { + if (n >= argc || janet_checktype(argv[n], JANET_NIL)) { + return NULL; + } + return jd_gettm(argv, n); +} + JANET_FN(jd_mktime, "", "") { @@ -177,6 +190,60 @@ JANET_FN(jd_mktime_inplace, return janet_wrap_abstract(time); } +JANET_FN(jd_time_utc, + "", + "") { + janet_arity(argc, 0, 1); + struct tm *tm = jd_opttm(argv, argc, 0); + struct tm *nw = jd_maketm(); + time_t t; + if (tm) { + *nw = *tm; + t = mktime(nw); + } else { + t = time(NULL); + } + *nw = *(gmtime(&t)); + return janet_wrap_abstract(nw); +} + +JANET_FN(jd_time_utc_inplace, + "", + "") { + janet_fixarity(argc, 1); + struct tm *tm = jd_gettm(argv, 0); + time_t t = mktime(tm); + *tm = *(gmtime(&t)); + return janet_wrap_abstract(tm); +} + +JANET_FN(jd_time_localtime, + "", + "") { + janet_arity(argc, 0, 1); + struct tm *tm = jd_opttm(argv, argc, 0); + struct tm *nw = jd_maketm(); + time_t t; + if (tm) { + *nw = *tm; + t = mktime(nw); + } else { + t = time(NULL); + } + *nw = *(localtime(&t)); + return janet_wrap_abstract(nw); +} + +JANET_FN(jd_time_localtime_inplace, + "", + "") { + janet_fixarity(argc, 1); + struct tm *tm = jd_gettm(argv, 0); + time_t t = mktime(tm); + *tm = *(localtime(&t)); + return janet_wrap_abstract(tm); +} + // strftime struct strftime_format { const char *keyword; -- cgit v1.2.3