1/* $NetBSD$ */ 2/* $OpenBSD: strtonum.c,v 1.6 2004/08/03 19:38:01 millert Exp $ */ 3 4/* 5 * Copyright (c) 2004 Ted Unangst and Todd Miller 6 * All rights reserved. 7 * 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. 11 * 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. 19 */ 20 21#include <errno.h> 22#include <limits.h> 23#include <stdlib.h> 24 25#define INVALID 1 26#define TOOSMALL 2 27#define TOOLARGE 3 28 29long long strtonum(const char *numstr, long long minval, long long maxval, 30 const char **errstrp); 31 32long long 33strtonum(const char *numstr, long long minval, long long maxval, 34 const char **errstrp) 35{ 36 long long ll = 0; 37 char *ep; 38 int error = 0; 39 struct errval { 40 const char *errstr; 41 int err; 42 } ev[4] = { 43 { NULL, 0 }, 44 { "invalid", EINVAL }, 45 { "too small", ERANGE }, 46 { "too large", ERANGE }, 47 }; 48 49 ev[0].err = errno; 50 errno = 0; 51 if (minval > maxval) 52 error = INVALID; 53 else { 54 ll = strtoll(numstr, &ep, 10); 55 if (numstr == ep || *ep != '\0') 56 error = INVALID; 57 else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval) 58 error = TOOSMALL; 59 else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval) 60 error = TOOLARGE; 61 } 62 if (errstrp != NULL) 63 *errstrp = ev[error].errstr; 64 errno = ev[error].err; 65 if (error) 66 ll = 0; 67 68 return (ll); 69} 70