blob: 87f2f24b25839d33c41587d7943416a5b0625052 [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"
Darren Tucker8a15f012006-08-05 16:27:20 +100023
Damien Millerde3cb0a2005-05-26 20:48:25 +100024#ifndef HAVE_STRTONUM
Darren Tucker8a15f012006-08-05 16:27:20 +100025#include <stdlib.h>
Damien Millerde3cb0a2005-05-26 20:48:25 +100026#include <limits.h>
Darren Tucker2c1a02a2006-07-12 22:40:50 +100027#include <errno.h>
Damien Millerde3cb0a2005-05-26 20:48:25 +100028
29#define INVALID 1
30#define TOOSMALL 2
31#define TOOLARGE 3
32
33long long
34strtonum(const char *numstr, long long minval, long long maxval,
35 const char **errstrp)
36{
37 long long ll = 0;
38 char *ep;
39 int error = 0;
40 struct errval {
41 const char *errstr;
42 int err;
43 } ev[4] = {
44 { NULL, 0 },
45 { "invalid", EINVAL },
46 { "too small", ERANGE },
47 { "too large", ERANGE },
48 };
49
50 ev[0].err = errno;
51 errno = 0;
52 if (minval > maxval)
53 error = INVALID;
54 else {
55 ll = strtoll(numstr, &ep, 10);
56 if (numstr == ep || *ep != '\0')
57 error = INVALID;
58 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
59 error = TOOSMALL;
60 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
61 error = TOOLARGE;
62 }
63 if (errstrp != NULL)
64 *errstrp = ev[error].errstr;
65 errno = ev[error].err;
66 if (error)
67 ll = 0;
68
69 return (ll);
70}
71
72#endif /* HAVE_STRTONUM */