1/*	$NetBSD: difftime.c,v 1.9 2002/01/29 12:58:32 kleink 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
11static char	elsieid[] = "@(#)difftime.c	8.1";
12#else
13__RCSID("$NetBSD: difftime.c,v 1.9 2002/01/29 12:58:32 kleink 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
21double
22difftime(time1, time0)
23const time_t	time1;
24const time_t	time0;
25{
26	/*
27	** If (sizeof (double) > sizeof (time_t)) simply convert and subtract
28	** (assuming that the larger type has more precision).
29	** This is the common real-world case circa 2004.
30	*/
31/* LINTED constant */
32	if (sizeof (double) > sizeof (time_t))
33		return (double) time1 - (double) time0;
34/* LINTED constant */
35	if (!TYPE_INTEGRAL(time_t)) {
36		/*
37		** time_t is floating.
38		*/
39		return time1 - time0;
40	}
41/* LINTED constant */
42	if (!TYPE_SIGNED(time_t)) {
43		/*
44		** time_t is integral and unsigned.
45		** The difference of two unsigned values can't overflow
46		** if the minuend is greater than or equal to the subtrahend.
47		*/
48		if (time1 >= time0)
49			return time1 - time0;
50		else	return -((double) (time0 - time1));
51	}
52	/*
53	** time_t is integral and signed.
54	** Handle cases where both time1 and time0 have the same sign
55	** (meaning that their difference cannot overflow).
56	*/
57	if ((time1 < 0) == (time0 < 0))
58		return time1 - time0;
59	/*
60	** time1 and time0 have opposite signs.
61	** Punt if unsigned long is too narrow.
62	*/
63/* CONSTCOND */
64	if (sizeof (unsigned long) < sizeof (time_t))
65		return (double) time1 - (double) time0;
66	/*
67	** Stay calm...decent optimizers will eliminate the complexity below.
68	*/
69	if (time1 >= 0 /* && time0 < 0 */)
70		return (unsigned long) time1 +
71			(unsigned long) (-(time0 + 1)) + 1;
72	return -(double) ((unsigned long) time0 +
73		(unsigned long) (-(time1 + 1)) + 1);
74}
75