sad

simple audio daemon
git clone git://git.2f30.org/sad
Log | Files | Refs | LICENSE

strtonum.c (1873B)


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