xref: /dragonfly/lib/libc/stdtime/difftime.c (revision e65bc1c3)
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 1996-06-05 by Arthur David Olson.
4 **
5 ** $FreeBSD: src/lib/libc/stdtime/difftime.c,v 1.4.8.1 2001/03/05 11:37:21 obrien Exp $
6 */
7 /*LINTLIBRARY*/
8 
9 #include "namespace.h"
10 #include "private.h"
11 #include "un-namespace.h"
12 
13 double
14 difftime(const time_t time1, const 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 	** This is the common real-world case circa 2004.
20 	*/
21 	if (sizeof (double) > sizeof (time_t))
22 		return (double) time1 - (double) time0;
23 	if (!TYPE_INTEGRAL(time_t)) {
24 		/*
25 		** time_t is floating.
26 		*/
27 		return time1 - time0;
28 	}
29 	if (!TYPE_SIGNED(time_t)) {
30 		/*
31 		** time_t is integral and unsigned.
32 		** The difference of two unsigned values can't overflow
33 		** if the minuend is greater than or equal to the subtrahend.
34 		*/
35 		if (time1 >= time0)
36 			return time1 - time0;
37 		else	return -((double) (time0 - time1));
38 	}
39 	/*
40 	** time_t is integral and signed.
41 	** Handle cases where both time1 and time0 have the same sign
42 	** (meaning that their difference cannot overflow).
43 	*/
44 	if ((time1 < 0) == (time0 < 0))
45 		return time1 - time0;
46 	/*
47 	** time1 and time0 have opposite signs.
48 	** Punt if unsigned long is too narrow.
49 	*/
50 	if (sizeof (unsigned long) < sizeof (time_t))
51 		return (double) time1 - (double) time0;
52 	/*
53 	** Stay calm...decent optimizers will eliminate the complexity below.
54 	*/
55 	if (time1 >= 0 /* && time0 < 0 */)
56 		return (unsigned long) time1 +
57 			(unsigned long) (-(time0 + 1)) + 1;
58 	return -(double) ((unsigned long) time0 +
59 		(unsigned long) (-(time1 + 1)) + 1);
60 }
61