medfall

A super great game engine
Log | Files | Refs

strtonum.cc (1766B)


      1 /*	$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 
     20 #include <errno.h>
     21 #include <limits.h>
     22 #include <stdlib.h>
     23 
     24 #define INVALID 	1
     25 #define TOOSMALL 	2
     26 #define TOOLARGE 	3
     27 
     28 long long
     29 strtonum(const char *numstr, long long minval, long long maxval, const char **errstrp)
     30 {
     31 	long long ll = 0;
     32 	char *ep;
     33 	int error = 0;
     34 	struct errval {
     35 		const char *errstr;
     36 		int err;
     37 	} ev[4] = {
     38 		{ NULL,		0 },
     39 		{ "invalid",	EINVAL },
     40 		{ "too small",	ERANGE },
     41 		{ "too large",	ERANGE },
     42 	};
     43 
     44 	ev[0].err = errno;
     45 	errno = 0;
     46 	if (minval > maxval)
     47 		error = INVALID;
     48 	else {
     49 		ll = strtoll(numstr, &ep, 10);
     50 		if (numstr == ep || *ep != '\0')
     51 			error = INVALID;
     52 		else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval)
     53 			error = TOOSMALL;
     54 		else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval)
     55 			error = TOOLARGE;
     56 	}
     57 	if (errstrp != NULL)
     58 		*errstrp = ev[error].errstr;
     59 	errno = ev[error].err;
     60 	if (error)
     61 		ll = 0;
     62 
     63 	return (ll);
     64 }
     65