117209Swollman/*
217209Swollman** This file is in the public domain, so clarified as of
3192625Sedwin** 1996-06-05 by Arthur David Olson.
417209Swollman*/
515923Sscrappy
6111010Snectar#include <sys/cdefs.h>
72708Swollman#ifndef lint
82708Swollman#ifndef NOID
9192625Sedwinstatic char	elsieid[] __unused = "@(#)difftime.c	8.1";
102708Swollman#endif /* !defined NOID */
112708Swollman#endif /* !defined lint */
1292986Sobrien__FBSDID("$FreeBSD$");
132708Swollman
142708Swollman/*LINTLIBRARY*/
152708Swollman
1671579Sdeischen#include "namespace.h"
17192625Sedwin#include "private.h"	/* for time_t, TYPE_INTEGRAL, and TYPE_SIGNED */
1871579Sdeischen#include "un-namespace.h"
192708Swollman
202708Swollmandouble
212708Swollmandifftime(time1, time0)
222708Swollmanconst time_t	time1;
232708Swollmanconst time_t	time0;
242708Swollman{
25192625Sedwin	/*
26192625Sedwin	** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
27192625Sedwin	** (assuming that the larger type has more precision).
28192625Sedwin	** This is the common real-world case circa 2004.
29192625Sedwin	*/
30192625Sedwin	if (sizeof (double) > sizeof (time_t))
31192625Sedwin		return (double) time1 - (double) time0;
32192625Sedwin	if (!TYPE_INTEGRAL(time_t)) {
33192625Sedwin		/*
34192625Sedwin		** time_t is floating.
35192625Sedwin		*/
36192625Sedwin		return time1 - time0;
37130461Sstefanf	}
38192625Sedwin	if (!TYPE_SIGNED(time_t)) {
39192625Sedwin		/*
40192625Sedwin		** time_t is integral and unsigned.
41192625Sedwin		** The difference of two unsigned values can't overflow
42192625Sedwin		** if the minuend is greater than or equal to the subtrahend.
43192625Sedwin		*/
44192625Sedwin		if (time1 >= time0)
45192625Sedwin			return time1 - time0;
46192625Sedwin		else	return -((double) (time0 - time1));
47192625Sedwin	}
482708Swollman	/*
49192625Sedwin	** time_t is integral and signed.
50192625Sedwin	** Handle cases where both time1 and time0 have the same sign
51192625Sedwin	** (meaning that their difference cannot overflow).
522708Swollman	*/
53192625Sedwin	if ((time1 < 0) == (time0 < 0))
54192625Sedwin		return time1 - time0;
552708Swollman	/*
56192625Sedwin	** time1 and time0 have opposite signs.
57192625Sedwin	** Punt if unsigned long is too narrow.
582708Swollman	*/
59192625Sedwin	if (sizeof (unsigned long) < sizeof (time_t))
60192625Sedwin		return (double) time1 - (double) time0;
612708Swollman	/*
62192625Sedwin	** Stay calm...decent optimizers will eliminate the complexity below.
632708Swollman	*/
64192625Sedwin	if (time1 >= 0 /* && time0 < 0 */)
65192625Sedwin		return (unsigned long) time1 +
66192625Sedwin			(unsigned long) (-(time0 + 1)) + 1;
67192625Sedwin	return -(double) ((unsigned long) time0 +
68192625Sedwin		(unsigned long) (-(time1 + 1)) + 1);
692708Swollman}
70