summaryrefslogtreecommitdiffstats
path: root/src/util/timecmp.c
blob: 607a9ae6377672386a78d9653a51028cfd83a296 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
/*++
/* NAME
/*	timecmp 3
/* SUMMARY
/*	compare two time_t values
/* SYNOPSIS
/*	#include <timecmp.h>
/*
/*	int	timecmp(t1, t2)
/*	time_t	t1;
/*	time_t	t2;
/* DESCRIPTION
/*	The timecmp() function return an integer greater than, equal to, or
/*	less than 0, according as the time t1 is greater than, equal to, or
/*	less than the time t2.  The comparison is made in a manner that is
/*	insensitive to clock wrap-around, provided the underlying times are
/*	within half of the time interval between the smallest and largest
/*	representable time values.
/* LICENSE
/* .ad
/* .fi
/*	The Secure Mailer license must be distributed with this software.
/* AUTHOR(S)
/*	Wietse Venema
/*	IBM T.J. Watson Research
/*	P.O. Box 704
/*	Yorktown Heights, NY 10598, USA
/*
/*	Viktor Dukhovni
/*--*/

#include "timecmp.h"

/* timecmp - wrap-safe time_t comparison */

int     timecmp(time_t t1, time_t t2)
{
    time_t  delta = t1 - t2;

    if (delta == 0)
	return 0;

#define UNSIGNED(type) ( ((type)-1) > ((type)0) )

    /*
     * With a constant switch value, the compiler will emit only the code for
     * the correct case, so the signed/unsigned test happens at compile time.
     */
    switch (UNSIGNED(time_t) ? 0 : 1) {
    case 0:
	return ((2 * delta > delta) ? 1 : -1);
    case 1:
	return ((delta > (time_t) 0) ? 1 : -1);
    }
}

#ifdef TEST
#include <assert.h>

 /*
  * Bit banging!! There is no official constant that defines the INT_MAX
  * equivalent of the off_t type. Wietse came up with the following macro
  * that works as long as off_t is some two's complement number.
  * 
  * Note, however, that C99 permits signed integer representations other than
  * two's complement.
  */
#include <limits.h>
#define __MAXINT__(T) ((T) (((((T) 1) << ((sizeof(T) * CHAR_BIT) - 1)) ^ ((T) -1))))

int     main(void)
{
    time_t  now = time((time_t *) 0);

    /* Test that it works for normal times */
    assert(timecmp(now + 10, now) > 0);
    assert(timecmp(now, now) == 0);
    assert(timecmp(now - 10, now) < 0);

    /* Test that it works at a boundary time */
    if (UNSIGNED(time_t))
	now = (time_t) -1;
    else
	now = __MAXINT__(time_t);

    assert(timecmp(now + 10, now) > 0);
    assert(timecmp(now, now) == 0);
    assert(timecmp(now - 10, now) < 0);

    return (0);
}

#endif