1 1.1.1.3 wiz /* Id: compat_strtonum.c,v 1.2 2020/06/15 01:37:15 schwarze Exp */ 2 1.1.1.3 wiz /* $OpenBSD: strtonum.c,v 1.8 2015/09/13 08:31:48 guenther Exp $ */ 3 1.1 christos 4 1.1 christos /* 5 1.1 christos * Copyright (c) 2004 Ted Unangst and Todd Miller 6 1.1 christos * All rights reserved. 7 1.1 christos * 8 1.1 christos * Permission to use, copy, modify, and distribute this software for any 9 1.1 christos * purpose with or without fee is hereby granted, provided that the above 10 1.1 christos * copyright notice and this permission notice appear in all copies. 11 1.1 christos * 12 1.1 christos * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES 13 1.1 christos * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF 14 1.1 christos * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR 15 1.1 christos * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES 16 1.1 christos * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN 17 1.1 christos * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF 18 1.1 christos * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. 19 1.1 christos */ 20 1.1.1.3 wiz #include "config.h" 21 1.1 christos 22 1.1 christos #include <errno.h> 23 1.1 christos #include <limits.h> 24 1.1 christos #include <stdlib.h> 25 1.1 christos 26 1.1 christos #define INVALID 1 27 1.1 christos #define TOOSMALL 2 28 1.1 christos #define TOOLARGE 3 29 1.1 christos 30 1.1 christos long long 31 1.1 christos strtonum(const char *numstr, long long minval, long long maxval, 32 1.1 christos const char **errstrp) 33 1.1 christos { 34 1.1 christos long long ll = 0; 35 1.1 christos int error = 0; 36 1.1 christos char *ep; 37 1.1 christos struct errval { 38 1.1 christos const char *errstr; 39 1.1 christos int err; 40 1.1 christos } ev[4] = { 41 1.1 christos { NULL, 0 }, 42 1.1 christos { "invalid", EINVAL }, 43 1.1 christos { "too small", ERANGE }, 44 1.1 christos { "too large", ERANGE }, 45 1.1 christos }; 46 1.1 christos 47 1.1 christos ev[0].err = errno; 48 1.1 christos errno = 0; 49 1.1 christos if (minval > maxval) { 50 1.1 christos error = INVALID; 51 1.1 christos } else { 52 1.1 christos ll = strtoll(numstr, &ep, 10); 53 1.1 christos if (numstr == ep || *ep != '\0') 54 1.1 christos error = INVALID; 55 1.1 christos else if ((ll == LLONG_MIN && errno == ERANGE) || ll < minval) 56 1.1 christos error = TOOSMALL; 57 1.1 christos else if ((ll == LLONG_MAX && errno == ERANGE) || ll > maxval) 58 1.1 christos error = TOOLARGE; 59 1.1 christos } 60 1.1 christos if (errstrp != NULL) 61 1.1 christos *errstrp = ev[error].errstr; 62 1.1 christos errno = ev[error].err; 63 1.1 christos if (error) 64 1.1 christos ll = 0; 65 1.1 christos 66 1.1 christos return (ll); 67 1.1 christos } 68