blob: fcd18ceff045a94f5f4eb0131f9d94c3e65f310a [file] [log] [blame]
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08001/*
2** This file is in the public domain, so clarified as of
3** 1996-06-05 by Arthur David Olson.
4*/
5
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08006/*LINTLIBRARY*/
7
Elliott Hughesce4783c2013-07-12 17:31:11 -07008#include "private.h" /* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
The Android Open Source Project1dc9e472009-03-03 19:28:35 -08009
Elliott Hughesce4783c2013-07-12 17:31:11 -070010double ATTRIBUTE_CONST
11difftime(const time_t time1, const time_t time0)
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080012{
Elliott Hughesce4783c2013-07-12 17:31:11 -070013 /*
14 ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
15 ** (assuming that the larger type has more precision).
16 */
17 if (sizeof (double) > sizeof (time_t))
18 return (double) time1 - (double) time0;
19 if (!TYPE_INTEGRAL(time_t)) {
20 /*
21 ** time_t is floating.
22 */
23 return time1 - time0;
24 }
25 if (!TYPE_SIGNED(time_t)) {
26 /*
27 ** time_t is integral and unsigned.
28 ** The difference of two unsigned values can't overflow
29 ** if the minuend is greater than or equal to the subtrahend.
30 */
31 if (time1 >= time0)
32 return time1 - time0;
33 else return -(double) (time0 - time1);
34 }
35 /*
36 ** time_t is integral and signed.
37 ** Handle cases where both time1 and time0 have the same sign
38 ** (meaning that their difference cannot overflow).
39 */
40 if ((time1 < 0) == (time0 < 0))
41 return time1 - time0;
42 /*
43 ** time1 and time0 have opposite signs.
44 ** Punt if uintmax_t is too narrow.
45 ** This suffers from double rounding; attempt to lessen that
46 ** by using long double temporaries.
47 */
48 if (sizeof (uintmax_t) < sizeof (time_t))
49 return (long double) time1 - (long double) time0;
50 /*
51 ** Stay calm...decent optimizers will eliminate the complexity below.
52 */
53 if (time1 >= 0 /* && time0 < 0 */)
54 return (uintmax_t) time1 + (uintmax_t) (-1 - time0) + 1;
55 return -(double) ((uintmax_t) time0 + (uintmax_t) (-1 - time1) + 1);
The Android Open Source Project1dc9e472009-03-03 19:28:35 -080056}