xref: /dragonfly/lib/libc/stdtime/difftime.c (revision 78478697)
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 1996-06-05 by Arthur David Olson.
4 **
5 ** $FreeBSD: head/contrib/tzcode/stdtime/difftime.c 192625 2009-05-23 06:31:50Z edwin $
6 */
7 /*LINTLIBRARY*/
8 
9 #include "namespace.h"
10 #include "private.h"	/* for time_t and TYPE_SIGNED */
11 #include "un-namespace.h"
12 
13 double
14 difftime(time_t time1, time_t time0)
15 {
16 	/*
17 	** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
18 	** (assuming that the larger type has more precision).
19 	*/
20 	if (sizeof (double) > sizeof (time_t))
21 		return (double) time1 - (double) time0;
22 	if (!TYPE_SIGNED(time_t)) {
23 		/*
24 		** The difference of two unsigned values can't overflow
25 		** if the minuend is greater than or equal to the subtrahend.
26 		*/
27 		if (time1 >= time0)
28 			return            time1 - time0;
29 		else	return -(double) (time0 - time1);
30 	}
31 	/*
32 	** Handle cases where both time1 and time0 have the same sign
33 	** (meaning that their difference cannot overflow).
34 	*/
35 	if ((time1 < 0) == (time0 < 0))
36 		return time1 - time0;
37 	/*
38 	** time1 and time0 have opposite signs.
39 	** Punt if uintmax_t is too narrow.
40 	** This suffers from double rounding; attempt to lessen that
41 	** by using long double temporaries.
42 	*/
43 	if (sizeof (uintmax_t) < sizeof (time_t))
44 		return (long double) time1 - (long double) time0;
45 	/*
46 	** Stay calm...decent optimizers will eliminate the complexity below.
47 	*/
48 	if (time1 >= 0 /* && time0 < 0 */)
49 		return    (uintmax_t) time1 + (uintmax_t) (-1 - time0) + 1;
50 	return -(double) ((uintmax_t) time0 + (uintmax_t) (-1 - time1) + 1);
51 }
52