time.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. /* Part of Scheme 48 1.9. See file COPYING for notices and license.
  2. *
  3. * Authors: Michael Zabka, Marcus Crestani
  4. */
  5. #include <sys/time.h>
  6. #include <time.h>
  7. #include "scheme48.h"
  8. static s48_ref_t time_type_binding;
  9. /*
  10. * Install all exported functions in Scheme48.
  11. */
  12. void
  13. s48_init_time(void)
  14. {
  15. S48_EXPORT_FUNCTION(s48_get_current_time);
  16. S48_EXPORT_FUNCTION(s48_get_timezone);
  17. time_type_binding =
  18. s48_get_imported_binding_2("os-time-type");
  19. }
  20. /* ************************************************************ */
  21. /*
  22. * Convert a timeval into a Scheme time record.
  23. */
  24. s48_ref_t
  25. s48_enter_time(s48_call_t call, struct timeval *now)
  26. {
  27. s48_ref_t sch_time;
  28. sch_time = s48_make_record_2(call, time_type_binding);
  29. s48_unsafe_record_set_2(call, sch_time, 0, s48_enter_long_2(call, now->tv_sec));
  30. s48_unsafe_record_set_2(call, sch_time, 1, s48_enter_long_2(call, now->tv_usec));
  31. return sch_time;
  32. }
  33. /* returns a Scheme time record containing seconds since
  34. * midnight (00:00:00), January 1, 1970 (UTC) +
  35. * the fraction of a second in microseconds
  36. */
  37. s48_ref_t
  38. s48_get_current_time(s48_call_t call)
  39. {
  40. struct timeval now;
  41. gettimeofday(&now, NULL);
  42. return s48_enter_time(call, &now);
  43. }
  44. /* returns the difference in seconds between UTC and local time */
  45. s48_ref_t
  46. s48_get_timezone(s48_call_t call)
  47. {
  48. #ifdef HAVE_TM_GMTOFF
  49. time_t helper_time;
  50. struct tm broken_time;
  51. if ((helper_time = time(NULL)) == -1)
  52. s48_assertion_violation_2(call, "os_time", "unknown error calling time()", 0);
  53. localtime_r(&helper_time, &broken_time);
  54. return s48_enter_long_2(call, broken_time.tm_gmtoff);
  55. #else /* not HAVE_TM_GMTOFF */
  56. /* On systems that do not have the tm_gmtoff field in struct tm,
  57. there is no reliable way to get the timezone. We do not
  58. support timezones on these systems. */
  59. return s48_enter_long_2(call, 0);
  60. #endif /* not HAVE_TM_GMTOFF */
  61. }