/*
 * Copyright (c) 1994, 2021 Alex Leigh, All Rights Reserved
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE OF ALEX LEIGH The copyright
 * notice above does not evidence any actual or intended publication of such
 * source code.
 *
 * Disclosure, copying, distribution, or transmission of this code without
 * express permission is prohibited.
 */

#include "tme.h"

#include <time.h>
#include <assert.h>
#include <string.h>

#define ASCII_ZERO 48

static const char months[48] = "Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec ";
static struct tm cache_tm;

/**
 * High-performance function which returns a volatile pointer to the current time of day, accurate to the second. The
 * buffer is written to in such a manner as to be somewhat safe for concurrent use.
 *
 * Do not use this function unless
 * you know you need to use this function.
 */
volatile const char *mFtme_asctime(void) {
    volatile const struct tm *t;
    char *p;
    unsigned int a;
    static char buf[30];
    time_t ltime;
    time(&ltime);

#ifndef _WIN32
    gmtime_r(&ltime, &cache_tm);
#else
    gmtime_s(&cache_tm, &ltime);
#endif // _WIN32

    t = &cache_tm;
    assert(t != NULL);

    p = buf + 29;
    *p-- = '\0';
    *p-- = ']';

    a = t->tm_sec;
    *p-- = ASCII_ZERO + a % 10;
    *p-- = ASCII_ZERO + a / 10;
    *p-- = ':';
    a = t->tm_min;
    *p-- = ASCII_ZERO + a % 10;
    *p-- = ASCII_ZERO + a / 10;
    *p-- = ':';
    a = t->tm_hour;
    *p-- = ASCII_ZERO + a % 10;
    *p-- = ASCII_ZERO + a / 10;
    *p-- = ':';
    a = 1900 + t->tm_year;
    while (a) {
        *p-- = ASCII_ZERO + a % 10;
        a /= 10;
    }
    /* p points to an unused spot */
    *p-- = '/';
    p -= 2;
    memcpy(p--, months + 4 * (t->tm_mon), 3);
    *p-- = '/';
    a = t->tm_mday;
    *p-- = ASCII_ZERO + a % 10;
    *p-- = ASCII_ZERO + a / 10;
    *p = '[';
    return p; /* should be same as returning buf */
}