summaryrefslogtreecommitdiffstats
path: root/src/global/conv_time.c
blob: 78a40b56510624c5344012f6bed0bacc3583eed9 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*++
/* NAME
/*	conv_time 3
/* SUMMARY
/*	time value conversion
/* SYNOPSIS
/*	#include <conv_time.h>
/*
/*	int	conv_time(strval, timval, def_unit);
/*	const char *strval;
/*	int	*timval;
/*	int	def_unit;
/* DESCRIPTION
/*	conv_time() converts a numerical time value with optional
/*	one-letter suffix that specifies an explicit time unit: s
/*	(seconds), m (minutes), h (hours), d (days) or w (weeks).
/*	Internally, time is represented in seconds.
/*
/*	Arguments:
/* .IP strval
/*	Input value.
/* .IP timval
/*	Result pointer.
/* .IP def_unit
/*	The default time unit suffix character.
/* DIAGNOSTICS
/*	The result value is non-zero in case of success, zero in
/*	case of a bad time value or a bad time unit suffix.
/* 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
/*
/*	Wietse Venema
/*	Google, Inc.
/*	111 8th Avenue
/*	New York, NY 10011, USA
/*--*/

/* System library. */

#include <sys_defs.h>
#include <limits.h>			/* INT_MAX */
#include <stdlib.h>
#include <errno.h>

/* Utility library. */

#include <msg.h>

/* Global library. */

#include <conv_time.h>

#define MINUTE	(60)
#define HOUR	(60 * MINUTE)
#define DAY	(24 * HOUR)
#define WEEK	(7 * DAY)

/* conv_time - convert time value */

int     conv_time(const char *strval, int *timval, int def_unit)
{
    char   *end;
    int     intval;
    long    longval;

    errno = 0;
    intval = longval = strtol(strval, &end, 10);
    if (*strval == 0 || errno == ERANGE || longval != intval || intval < 0
	/* || (*end != 0 && end[1] != 0) */)
	return (0);

    switch (*end ? *end : def_unit) {
    case 'w':
	if (intval < INT_MAX / WEEK) {
	    *timval = intval * WEEK;
	    return (1);
	} else {
	    return (0);
	}
    case 'd':
	if (intval < INT_MAX / DAY) {
	    *timval = intval * DAY;
	    return (1);
	} else {
	    return (0);
	}
    case 'h':
	if (intval < INT_MAX / HOUR) {
	    *timval = intval * HOUR;
	    return (1);
	} else {
	    return (0);
	}
    case 'm':
	if (intval < INT_MAX / MINUTE) {
	    *timval = intval * MINUTE;
	    return (1);
	} else {
	    return (0);
	}
    case 's':
	*timval = intval;
	return (1);
    }
    return (0);
}