blob: 35c5c18b9520165241d4804d3be402fd4cfa9f0a [file] [log] [blame]
Damien Millerde3cb0a2005-05-26 20:48:25 +10001/* $OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert Exp $ */
2
3/*
4 * Copyright (c) 2004 Ted Unangst and Todd Miller
5 * All rights reserved.
6 *
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.
10 *
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.
18 */
19
Darren Tucker7f24a0e2005-11-10 16:18:56 +110020/* OPENBSD ORIGINAL: lib/libc/stdlib/strtonum.c */
21
Damien Millerde3cb0a2005-05-26 20:48:25 +100022#include "includes.h"
23#ifndef HAVE_STRTONUM
24#include <limits.h>
Darren Tucker2c1a02a2006-07-12 22:40:50 +100025#include <errno.h>
Damien Millerde3cb0a2005-05-26 20:48:25 +100026
27#define INVALID 1
28#define TOOSMALL 2
29#define TOOLARGE 3
30
31long long
32strtonum(const char *numstr, long long minval, long long maxval,
33 const char **errstrp)
34{
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 },
46 };
47
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;
60 }
61 if (errstrp != NULL)
62 *errstrp = ev[error].errstr;
63 errno = ev[error].err;
64 if (error)
65 ll = 0;
66
67 return (ll);
68}
69
70#endif /* HAVE_STRTONUM */