strtonum.c 1.7 KB

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