1 /*
2 Copyright (c) 1994 Cygnus Support.
3 All rights reserved.
4 
5 Redistribution and use in source and binary forms are permitted
6 provided that the above copyright notice and this paragraph are
7 duplicated in all such forms and that any documentation,
8 and/or other materials related to such
9 distribution and use acknowledge that the software was developed
10 at Cygnus Support, Inc.  Cygnus Support, Inc. may not be used to
11 endorse or promote products derived from this software without
12 specific prior written permission.
13 THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
14 IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
15 WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
16  */
17 /*
18  * asctime_r.c
19  */
20 
21 #define _DEFAULT_SOURCE
22 #include <stdio.h>
23 #include <time.h>
24 #include <errno.h>
25 
26 #define oob(x,a) ((unsigned)(x) >= sizeof(a)/sizeof(a[0]))
27 #define valid(x,a)   (oob(x,a) ? "???" : a[x])
28 
29 char *
asctime_r(const struct tm * __restrict tim_p,char result[__restrict static __ASCTIME_SIZE])30 asctime_r (const struct tm *__restrict tim_p,
31            char result[__restrict static __ASCTIME_SIZE])
32 {
33   static const char day_name[7][3] = {
34 	"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
35   };
36   static const char mon_name[12][3] = {
37 	"Jan", "Feb", "Mar", "Apr", "May", "Jun",
38 	"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
39   };
40 
41   int n;
42 
43   n = snprintf (result, __ASCTIME_SIZE, "%.3s %.3s%3d %.2d:%.2d:%.2d %d\n",
44                 valid(tim_p->tm_wday, day_name),
45                 valid(tim_p->tm_mon, mon_name),
46                 tim_p->tm_mday, tim_p->tm_hour, tim_p->tm_min,
47                 tim_p->tm_sec, 1900 + tim_p->tm_year);
48 
49   if (n < 0)
50       return NULL;
51 
52   if (n >= __ASCTIME_SIZE)
53       goto eoverflow;
54 
55   return result;
56 
57 eoverflow:
58   errno = EOVERFLOW;
59   return NULL;
60 }
61