xref: /netbsd-src/lib/libc/time/difftime.c (revision 4d12bfcd155352508213ace5ccc59ce930ea2974)
1 /*	$NetBSD: difftime.c,v 1.14 2013/07/17 20:13:04 christos Exp $	*/
2 
3 /*
4 ** This file is in the public domain, so clarified as of
5 ** 1996-06-05 by Arthur David Olson.
6 */
7 
8 #include <sys/cdefs.h>
9 #if defined(LIBC_SCCS) && !defined(lint)
10 #if 0
11 static char	elsieid[] = "@(#)difftime.c	8.1";
12 #else
13 __RCSID("$NetBSD: difftime.c,v 1.14 2013/07/17 20:13:04 christos Exp $");
14 #endif
15 #endif /* LIBC_SCCS and not lint */
16 
17 /*LINTLIBRARY*/
18 
19 #include "private.h"	/* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
20 
21 double ATTRIBUTE_CONST
22 difftime(const time_t time1, const time_t time0)
23 {
24 	/*
25 	** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
26 	** (assuming that the larger type has more precision).
27 	*/
28 	/*CONSTCOND*/
29 	if (sizeof (double) > sizeof (time_t))
30 		return (double) time1 - (double) time0;
31 	/*LINTED const not */
32 	if (!TYPE_INTEGRAL(time_t)) {
33 		/*
34 		** time_t is floating.
35 		*/
36 		return time1 - time0;
37 	}
38 	/*LINTED const not */
39 	if (!TYPE_SIGNED(time_t)) {
40 		/*
41 		** time_t is integral and unsigned.
42 		** The difference of two unsigned values can't overflow
43 		** if the minuend is greater than or equal to the subtrahend.
44 		*/
45 		if (time1 >= time0)
46 			return            time1 - time0;
47 		else	return -(double) (time0 - time1);
48 	}
49 	/*
50 	** time_t is integral and signed.
51 	** Handle cases where both time1 and time0 have the same sign
52 	** (meaning that their difference cannot overflow).
53 	*/
54 	if ((time1 < 0) == (time0 < 0))
55 		return time1 - time0;
56 	/*
57 	** time1 and time0 have opposite signs.
58 	** Punt if uintmax_t is too narrow.
59 	** This suffers from double rounding; attempt to lessen that
60 	** by using long double temporaries.
61 	*/
62 	/* CONSTCOND */
63 	if (sizeof (uintmax_t) < sizeof (time_t))
64 		return (double) time1 - (double) time0;
65 	/*
66 	** Stay calm...decent optimizers will eliminate the complexity below.
67 	*/
68 	if (time1 >= 0 /* && time0 < 0 */)
69 		return    (uintmax_t) time1 + (uintmax_t) (-(time0 + 1)) + 1;
70 	return -(double) ((uintmax_t) time0 + (uintmax_t) (-(time1 + 1)) + 1);
71 }
72