1 /* $NetBSD: difftime.c,v 1.16 2015/08/13 11:21:18 christos Exp $ */ 2 3 /* 4 ** This file is in the public domain, so clarified as of 5 ** 1996-06-05 by Arthur David Olson. 6 */ 7 8 #include <sys/cdefs.h> 9 #if defined(LIBC_SCCS) && !defined(lint) 10 #if 0 11 static char elsieid[] = "@(#)difftime.c 8.1"; 12 #else 13 __RCSID("$NetBSD: difftime.c,v 1.16 2015/08/13 11:21:18 christos Exp $"); 14 #endif 15 #endif /* LIBC_SCCS and not lint */ 16 17 /*LINTLIBRARY*/ 18 19 #include "private.h" /* for time_t and TYPE_SIGNED */ 20 21 /* Return -X as a double. Using this avoids casting to 'double'. */ 22 static double dminus(double x)23dminus(double x) 24 { 25 return -x; 26 } 27 28 double ATTRIBUTE_CONST difftime(time_t time1,time_t time0)29difftime(time_t time1, time_t time0) 30 { 31 /* 32 ** If double is large enough, simply convert and subtract 33 ** (assuming that the larger type has more precision). 34 */ 35 if (sizeof (time_t) < sizeof (double)) { 36 double t1 = time1, t0 = time0; 37 return t1 - t0; 38 } 39 40 /* 41 ** The difference of two unsigned values can't overflow 42 ** if the minuend is greater than or equal to the subtrahend. 43 */ 44 if (!TYPE_SIGNED(time_t)) 45 return time0 <= time1 ? time1 - time0 : dminus(time0 - time1); 46 47 /* Use uintmax_t if wide enough. */ 48 if (sizeof (time_t) <= sizeof (uintmax_t)) { 49 uintmax_t t1 = time1, t0 = time0; 50 return time0 <= time1 ? t1 - t0 : dminus(t0 - t1); 51 } 52 53 /* 54 ** Handle cases where both time1 and time0 have the same sign 55 ** (meaning that their difference cannot overflow). 56 */ 57 if ((time1 < 0) == (time0 < 0)) 58 return time1 - time0; 59 60 /* 61 ** The values have opposite signs and uintmax_t is too narrow. 62 ** This suffers from double rounding; attempt to lessen that 63 ** by using long double temporaries. 64 */ 65 { 66 long double t1 = time1, t0 = time0; 67 return t1 - t0; 68 } 69 } 70