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: releng/11.0/contrib/tzcode/stdtime/difftime.c 289027 2015-10-08 11:42:15Z rodrigc $"); 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 21289027Srodrigcdifftime(const time_t time1, const time_t time0) 222708Swollman{ 23192625Sedwin /* 24192625Sedwin ** If (sizeof (double) > sizeof (time_t)) simply convert and subtract 25192625Sedwin ** (assuming that the larger type has more precision). 26192625Sedwin ** This is the common real-world case circa 2004. 27192625Sedwin */ 28192625Sedwin if (sizeof (double) > sizeof (time_t)) 29192625Sedwin return (double) time1 - (double) time0; 30192625Sedwin if (!TYPE_INTEGRAL(time_t)) { 31192625Sedwin /* 32192625Sedwin ** time_t is floating. 33192625Sedwin */ 34192625Sedwin return time1 - time0; 35130461Sstefanf } 36192625Sedwin if (!TYPE_SIGNED(time_t)) { 37192625Sedwin /* 38192625Sedwin ** time_t is integral and unsigned. 39192625Sedwin ** The difference of two unsigned values can't overflow 40192625Sedwin ** if the minuend is greater than or equal to the subtrahend. 41192625Sedwin */ 42192625Sedwin if (time1 >= time0) 43192625Sedwin return time1 - time0; 44192625Sedwin else return -((double) (time0 - time1)); 45192625Sedwin } 462708Swollman /* 47192625Sedwin ** time_t is integral and signed. 48192625Sedwin ** Handle cases where both time1 and time0 have the same sign 49192625Sedwin ** (meaning that their difference cannot overflow). 502708Swollman */ 51192625Sedwin if ((time1 < 0) == (time0 < 0)) 52192625Sedwin return time1 - time0; 532708Swollman /* 54192625Sedwin ** time1 and time0 have opposite signs. 55192625Sedwin ** Punt if unsigned long is too narrow. 562708Swollman */ 57192625Sedwin if (sizeof (unsigned long) < sizeof (time_t)) 58192625Sedwin return (double) time1 - (double) time0; 592708Swollman /* 60192625Sedwin ** Stay calm...decent optimizers will eliminate the complexity below. 612708Swollman */ 62192625Sedwin if (time1 >= 0 /* && time0 < 0 */) 63192625Sedwin return (unsigned long) time1 + 64192625Sedwin (unsigned long) (-(time0 + 1)) + 1; 65192625Sedwin return -(double) ((unsigned long) time0 + 66192625Sedwin (unsigned long) (-(time1 + 1)) + 1); 672708Swollman} 68