- jmc@cvs.openbsd.org 2006/07/18 08:03:09
[openssh-git.git] / openbsd-compat / strtonum.c
blob35c5c18b9520165241d4804d3be402fd4cfa9f0a
1 /* $OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert Exp $ */
3 /*
4 * Copyright (c) 2004 Ted Unangst and Todd Miller
5 * All rights reserved.
7 * Permission to use, copy, modify, and distribute this software for any
8 * purpose with or without fee is hereby granted, provided that the above
9 * copyright notice and this permission notice appear in all copies.
11 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
12 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
13 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
14 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
15 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
16 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
17 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
20 /* OPENBSD ORIGINAL: lib/libc/stdlib/strtonum.c */
22 #include "includes.h"
23 #ifndef HAVE_STRTONUM
24 #include <limits.h>
25 #include <errno.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);
70 #endif /* HAVE_STRTONUM */