convtime.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. RCSID("$Id: convtime.c,v 1.2 2004/09/10 09:08:08 djm Exp $");
  27. #define SECONDS 1
  28. #define MINUTES (SECONDS * 60)
  29. #define HOURS (MINUTES * 60)
  30. #define DAYS (HOURS * 24)
  31. #define WEEKS (DAYS * 7)
  32. long int
  33. convtime(const char *s)
  34. {
  35. long total, secs;
  36. const char *p;
  37. char *endp;
  38. errno = 0;
  39. total = 0;
  40. p = s;
  41. if (p == NULL || *p == '\0')
  42. return -1;
  43. while (*p) {
  44. secs = strtol(p, &endp, 10);
  45. if (p == endp ||
  46. (errno == ERANGE && (secs == LONG_MIN || secs == LONG_MAX)) ||
  47. secs < 0)
  48. return -1;
  49. switch (*endp++) {
  50. case '\0':
  51. endp--;
  52. case 's':
  53. case 'S':
  54. break;
  55. case 'm':
  56. case 'M':
  57. secs *= MINUTES;
  58. break;
  59. case 'h':
  60. case 'H':
  61. secs *= HOURS;
  62. break;
  63. case 'd':
  64. case 'D':
  65. secs *= DAYS;
  66. break;
  67. case 'w':
  68. case 'W':
  69. secs *= WEEKS;
  70. break;
  71. default:
  72. return -1;
  73. }
  74. total += secs;
  75. if (total < 0)
  76. return -1;
  77. p = endp;
  78. }
  79. return total;
  80. }