strtonum.c 1.7 KB

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