|
| 1 | +/* |
| 2 | + * Copyright (c) 2024 Meta Platforms |
| 3 | + * |
| 4 | + * SPDX-License-Identifier: Apache-2.0 |
| 5 | + */ |
| 6 | + |
| 7 | +#include <stdio.h> |
| 8 | +#include <string.h> |
| 9 | +#include <time.h> |
| 10 | + |
| 11 | +#include <zephyr/sys/util.h> |
| 12 | + |
| 13 | +#define DATE_STRING_BUF_SZ 26U |
| 14 | +#define DATE_WDAY_STRING_SZ 7U |
| 15 | +#define DATE_MON_STRING_SZ 12U |
| 16 | +#define DATE_TM_YEAR_BASE 1900 |
| 17 | + |
| 18 | +static char *asctime_impl(const struct tm *tp, char *buf) |
| 19 | +{ |
| 20 | + static const char wday_str[DATE_WDAY_STRING_SZ][3] = { |
| 21 | + "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", |
| 22 | + }; |
| 23 | + static const char mon_str[DATE_MON_STRING_SZ][3] = { |
| 24 | + "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", |
| 25 | + }; |
| 26 | + |
| 27 | + if ((buf == NULL) || (tp == NULL) || ((unsigned int)tp->tm_wday >= DATE_WDAY_STRING_SZ) || |
| 28 | + ((unsigned int)tp->tm_mon >= DATE_MON_STRING_SZ)) { |
| 29 | + return NULL; |
| 30 | + } |
| 31 | + |
| 32 | + unsigned int n = (unsigned int)snprintf( |
| 33 | + buf, DATE_STRING_BUF_SZ, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n", wday_str[tp->tm_wday], |
| 34 | + mon_str[tp->tm_mon], tp->tm_mday, tp->tm_hour, tp->tm_min, tp->tm_sec, |
| 35 | + DATE_TM_YEAR_BASE + tp->tm_year); |
| 36 | + |
| 37 | + if (n >= DATE_STRING_BUF_SZ) { |
| 38 | + return NULL; |
| 39 | + } |
| 40 | + |
| 41 | + return buf; |
| 42 | +} |
| 43 | + |
| 44 | +char *asctime(const struct tm *tp) |
| 45 | +{ |
| 46 | + static char buf[DATE_STRING_BUF_SZ]; |
| 47 | + |
| 48 | + return asctime_impl(tp, buf); |
| 49 | +} |
| 50 | + |
| 51 | +#if defined(CONFIG_COMMON_LIBC_ASCTIME_R) |
| 52 | +char *asctime_r(const struct tm *tp, char *buf) |
| 53 | +{ |
| 54 | + return asctime_impl(tp, buf); |
| 55 | +} |
| 56 | +#endif /* CONFIG_COMMON_LIBC_ASCTIME_R */ |
0 commit comments