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