Patrick Welche <prlw1@cam.ac.uk>
[netbsd-mini2440.git] / usr.bin / sdiff / strtonum.c
blob97f92c5c462d0341f55fe1eb135271da20379002
1 /* $NetBSD$ */
2 /* $OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert Exp $ */
4 /*
5 * Copyright (c) 2004 Ted Unangst and Todd Miller
6 * All rights reserved.
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
21 #include <errno.h>
22 #include <limits.h>
23 #include <stdlib.h>
25 #include "common.h"
27 #define INVALID 1
28 #define TOOSMALL 2
29 #define TOOLARGE 3
31 long long
32 strtonum(const char *numstr, long long minval, long long maxval,
33 const char **errstrp)
35 long long ll = 0;
36 char *ep;
37 int error = 0;
38 struct errval {
39 const char *errstr;
40 int err;
41 } ev[4] = {
42 { NULL, 0 },
43 { "invalid", EINVAL },
44 { "too small", ERANGE },
45 { "too large", ERANGE },
48 ev[0].err = errno;
49 errno = 0;
50 if (minval > maxval)
51 error = INVALID;
52 else {
53 ll = strtoll(numstr, &ep, 10);
54 if (numstr == ep || *ep != '\0')
55 error = INVALID;
56 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
57 error = TOOSMALL;
58 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
59 error = TOOLARGE;
61 if (errstrp != NULL)
62 *errstrp = ev[error].errstr;
63 errno = ev[error].err;
64 if (error)
65 ll = 0;
67 return (ll);