1
0

convtime.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. /*
  2. * Copyright (c) 2001 Kevin Steves. All rights reserved.
  3. *
  4. * Redistribution and use in source and binary forms, with or without
  5. * modification, are permitted provided that the following conditions
  6. * are met:
  7. * 1. Redistributions of source code must retain the above copyright
  8. * notice, this list of conditions and the following disclaimer.
  9. * 2. Redistributions in binary form must reproduce the above copyright
  10. * notice, this list of conditions and the following disclaimer in the
  11. * documentation and/or other materials provided with the distribution.
  12. *
  13. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
  14. * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
  15. * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
  16. * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
  17. * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
  18. * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  19. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  20. * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  21. * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
  22. * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  23. */
  24. #include "common.h"
  25. #include "convtime.h"
  26. #define SECONDS 1
  27. #define MINUTES (SECONDS * 60)
  28. #define HOURS (MINUTES * 60)
  29. #define DAYS (HOURS * 24)
  30. #define WEEKS (DAYS * 7)
  31. long int
  32. convtime(const char *s)
  33. {
  34. long total, secs;
  35. const char *p;
  36. char *endp;
  37. errno = 0;
  38. total = 0;
  39. p = s;
  40. if (p == NULL || *p == '\0')
  41. return -1;
  42. while (*p) {
  43. secs = strtol(p, &endp, 10);
  44. if (p == endp ||
  45. (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
  46. secs < 0)
  47. return -1;
  48. switch (*endp++) {
  49. case '\0':
  50. endp--;
  51. case 's':
  52. case 'S':
  53. break;
  54. case 'm':
  55. case 'M':
  56. secs *= MINUTES;
  57. break;
  58. case 'h':
  59. case 'H':
  60. secs *= HOURS;
  61. break;
  62. case 'd':
  63. case 'D':
  64. secs *= DAYS;
  65. break;
  66. case 'w':
  67. case 'W':
  68. secs *= WEEKS;
  69. break;
  70. default:
  71. return -1;
  72. }
  73. total += secs;
  74. if (total < 0)
  75. return -1;
  76. p = endp;
  77. }
  78. return total;
  79. }