1 /* 2 * timetoa.h -- time_t related string formatting 3 * 4 * Written by Juergen Perlinger (perlinger@ntp.org) for the NTP project. 5 * The contents of 'html/copyright.html' apply. 6 * 7 * Printing a 'time_t' has some portability pitfalls, due to it's opaque 8 * base type. The only requirement imposed by the standard is that it 9 * must be a numeric type. For all practical purposes it's a signed int, 10 * and 32 bits are common. 11 * 12 * Since the UN*X time epoch will cause a signed integer overflow for 13 * 32-bit signed int values in the year 2038, implementations slowly 14 * move to 64bit base types for time_t, even in 32-bit environments. In 15 * such an environment sizeof(time_t) could be bigger than sizeof(long) 16 * and the commonly used idiom of casting to long leads to truncation. 17 * 18 * As the printf() family has no standardised type specifier for time_t, 19 * guessing the right output format specifier is a bit troublesome and 20 * best done with the help of the preprocessor and "config.h". 21 */ 22 #ifndef TIMETOA_H 23 #define TIMETOA_H 24 25 #include "ntp_fp.h" 26 #include "ntp_stdlib.h" 27 #include "ntp_unixtime.h" 28 29 /* 30 * Given the size of time_t, guess what can be used as an unsigned value 31 * to hold a time_t and the printf() format specifcation. 32 * 33 * These should be used with the string constant concatenation feature 34 * of the compiler like this: 35 * 36 * printf("a time stamp: %" TIME_FORMAT " and more\n", a_time_t_value); 37 * 38 * It's not exactly nice, but there's not much leeway once we want to 39 * use the printf() family on time_t values. 40 */ 41 42 #if SIZEOF_TIME_T <= SIZEOF_INT 43 44 typedef unsigned int u_time; 45 #define TIME_FORMAT "d" 46 #define UTIME_FORMAT "u" 47 48 #elif SIZEOF_TIME_T <= SIZEOF_LONG 49 50 typedef unsigned long u_time; 51 #define TIME_FORMAT "ld" 52 #define UTIME_FORMAT "lu" 53 54 #elif defined(SIZEOF_LONG_LONG) && SIZEOF_TIME_T <= SIZEOF_LONG_LONG 55 56 typedef unsigned long long u_time; 57 #define TIME_FORMAT "lld" 58 #define UTIME_FORMAT "llu" 59 60 #else 61 #include "GRONK: what size has a time_t here?" 62 #endif 63 64 /* 65 * general fractional time stamp formatting. 66 * 67 * secs - integral seconds of time stamp 68 * frac - fractional units 69 * prec - log10 of units per second (3=milliseconds, 6=microseconds,..) 70 * or in other words: the count of decimal digits required. 71 * If prec is < 0, abs(prec) is taken for the precision and secs 72 * is treated as an unsigned value. 73 * 74 * The function will eventually normalise the fraction and adjust the 75 * seconds accordingly. 76 * 77 * This function uses the string buffer library for the return value, 78 * so do not keep the resulting pointers around. 79 */ 80 extern const char * 81 format_time_fraction(time_t secs, long frac, int prec); 82 83 #endif /* !defined(TIMETOA_H) */ 84