]> git.saurik.com Git - apple/libc.git/blob - stdtime/FreeBSD/difftime.c
Libc-763.11.tar.gz
[apple/libc.git] / stdtime / FreeBSD / difftime.c
1 /*
2 ** This file is in the public domain, so clarified as of
3 ** 1996-06-05 by Arthur David Olson.
4 */
5
6 #include <sys/cdefs.h>
7 #ifndef lint
8 #ifndef NOID
9 static char elsieid[] __unused = "@(#)difftime.c 8.1";
10 #endif /* !defined NOID */
11 #endif /* !defined lint */
12 __FBSDID("$FreeBSD: src/lib/libc/stdtime/difftime.c,v 1.9 2009/05/23 06:31:50 edwin Exp $");
13
14 /*LINTLIBRARY*/
15
16 #include "namespace.h"
17 #include "private.h" /* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
18 #include "un-namespace.h"
19
20 double
21 difftime(time1, time0)
22 const time_t time1;
23 const time_t time0;
24 {
25 /*
26 ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
27 ** (assuming that the larger type has more precision).
28 ** This is the common real-world case circa 2004.
29 */
30 if (sizeof (double) > sizeof (time_t))
31 return (double) time1 - (double) time0;
32 if (!TYPE_INTEGRAL(time_t)) {
33 /*
34 ** time_t is floating.
35 */
36 return time1 - time0;
37 }
38 if (!TYPE_SIGNED(time_t)) {
39 /*
40 ** time_t is integral and unsigned.
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 (time1 >= time0)
45 return time1 - time0;
46 else return -((double) (time0 - time1));
47 }
48 /*
49 ** time_t is integral and signed.
50 ** Handle cases where both time1 and time0 have the same sign
51 ** (meaning that their difference cannot overflow).
52 */
53 if ((time1 < 0) == (time0 < 0))
54 return time1 - time0;
55 /*
56 ** time1 and time0 have opposite signs.
57 ** Punt if unsigned long is too narrow.
58 */
59 if (sizeof (unsigned long) < sizeof (time_t))
60 return (double) time1 - (double) time0;
61 /*
62 ** Stay calm...decent optimizers will eliminate the complexity below.
63 */
64 if (time1 >= 0 /* && time0 < 0 */)
65 return (unsigned long) time1 +
66 (unsigned long) (-(time0 + 1)) + 1;
67 return -(double) ((unsigned long) time0 +
68 (unsigned long) (-(time1 + 1)) + 1);
69 }