2000-05-15 Gary Houston <ghouston@arglist.com>
[bpt/guile.git] / libguile / stime.c
index 8db4992..03095d1 100644 (file)
  * If you write modifications of your own for GUILE, it is your choice
  * whether to permit this exception to apply to your modifications.
  * If you do not wish that, delete this exception notice.  */
+
+/* Software engineering face-lift by Greg J. Badros, 11-Dec-1999,
+   gjb@cs.washington.edu, http://www.cs.washington.edu/homes/gjb */
+
 \f
 
 #include <stdio.h>
-#include "_scm.h"
-#include "feature.h"
+#include "libguile/_scm.h"
+#include "libguile/feature.h"
+#include "libguile/strings.h"
+#include "libguile/vectors.h"
 
-#include "stime.h"
+#include "libguile/validate.h"
+#include "libguile/stime.h"
 
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
@@ -121,12 +128,17 @@ long mytime()
 extern int errno;
 
 #ifdef HAVE_FTIME
-
 struct timeb scm_your_base = {0};
-SCM_PROC(s_get_internal_real_time, "get-internal-real-time", 0, 0, 0, scm_get_internal_real_time);
-SCM
-scm_get_internal_real_time()
+#else
+timet scm_your_base = 0;
+#endif
+
+SCM_DEFINE (scm_get_internal_real_time, "get-internal-real-time", 0, 0, 0, 
+           (),
+           "Returns the number of time units since the interpreter was started.")
+#define FUNC_NAME s_scm_get_internal_real_time
 {
+#ifdef HAVE_FTIME
   struct timeb time_buffer;
 
   SCM tmp;
@@ -138,80 +150,93 @@ scm_get_internal_real_time()
                              SCM_MAKINUM (time_buffer.time)));
   return scm_quotient (scm_product (tmp, SCM_MAKINUM (CLKTCK)),
                       SCM_MAKINUM (1000));
-};
-
 #else
-
-timet scm_your_base = 0;
-SCM_PROC(s_get_internal_real_time, "get-internal-real-time", 0, 0, 0, scm_get_internal_real_time);
-SCM
-scm_get_internal_real_time()
-{
   return scm_long2num((time((timet*)0) - scm_your_base) * (int)CLKTCK);
+#endif /* HAVE_FTIME */
 }
-#endif
+#undef FUNC_NAME
+
 
-SCM_PROC (s_times, "times", 0, 0, 0, scm_times);
-SCM
-scm_times (void)
-{
 #ifdef HAVE_TIMES
+SCM_DEFINE (scm_times, "times", 0, 0, 0, 
+            (void),
+           "Returns an object with information about real and processor time.\n"
+           "The following procedures accept such an object as an argument and\n"
+           "return a selected component:\n\n"
+           "@table @code\n"
+           "@item tms:clock\n"
+           "The current real time, expressed as time units relative to an\n"
+           "arbitrary base.\n"
+           "@item tms:utime\n"
+           "The CPU time units used by the calling process.\n"
+           "@item tms:stime\n"
+           "The CPU time units used by the system on behalf of the calling process.\n"
+           "@item tms:cutime\n"
+           "The CPU time units used by terminated child processes of the calling\n"
+           "process, whose status has been collected (e.g., using @code{waitpid}).\n"
+           "@item tms:cstime\n"
+           "Similarly, the CPU times units used by the system on behalf of \n"
+           "terminated child processes.\n"
+           "@end table")
+#define FUNC_NAME s_scm_times
+{
   struct tms t;
   clock_t rv;
 
   SCM result = scm_make_vector (SCM_MAKINUM(5), SCM_UNDEFINED);
   rv = times (&t);
   if (rv == -1)
-    scm_syserror (s_times);
+    SCM_SYSERROR;
   SCM_VELTS (result)[0] = scm_long2num (rv);
   SCM_VELTS (result)[1] = scm_long2num (t.tms_utime);
   SCM_VELTS (result)[2] = scm_long2num (t.tms_stime);
   SCM_VELTS (result)[3] = scm_long2num (t.tms_cutime);
   SCM_VELTS (result)[4] = scm_long2num (t.tms_cstime);
   return result;
-#else
-  scm_sysmissing (s_times);
-#endif
 }
-
-#ifndef HAVE_TZSET
-/* GNU-WIN32's cygwin.dll doesn't have this. */
-#define tzset()
-#endif
-
+#undef FUNC_NAME
+#endif /* HAVE_TIMES */
 
 static long scm_my_base = 0;
 
-SCM_PROC(s_get_internal_run_time, "get-internal-run-time", 0, 0, 0, scm_get_internal_run_time);
-SCM
-scm_get_internal_run_time()
+SCM_DEFINE (scm_get_internal_run_time, "get-internal-run-time", 0, 0, 0, 
+           (void),
+           "Returns the number of time units of processor time used by the interpreter.\n"
+           "Both \"system\" and \"user\" time are included but subprocesses are not.")
+#define FUNC_NAME s_scm_get_internal_run_time
 {
   return scm_long2num(mytime()-scm_my_base);
 }
+#undef FUNC_NAME
 
-SCM_PROC(s_current_time, "current-time", 0, 0, 0, scm_current_time);
-SCM
-scm_current_time()
+SCM_DEFINE (scm_current_time, "current-time", 0, 0, 0, 
+           (void),
+           "Returns the number of seconds since 1970-01-01 00:00:00 UTC, excludingleap seconds.")
+#define FUNC_NAME s_scm_current_time
 {
   timet timv;
 
   SCM_DEFER_INTS;
   if ((timv = time (0)) == -1)
-    scm_syserror (s_current_time);
+    SCM_SYSERROR;
   SCM_ALLOW_INTS;
   return scm_long2num((long) timv);
 }
-
-SCM_PROC (s_gettimeofday, "gettimeofday", 0, 0, 0, scm_gettimeofday);
-SCM
-scm_gettimeofday (void)
+#undef FUNC_NAME
+
+SCM_DEFINE (scm_gettimeofday, "gettimeofday", 0, 0, 0, 
+            (void),
+           "Returns a pair containing the number of seconds and microseconds since\n"
+           "1970-01-01 00:00:00 UTC, excluding leap seconds.  Note: whether true\n"
+           "microsecond resolution is available depends on the operating system.")
+#define FUNC_NAME s_scm_gettimeofday
 {
 #ifdef HAVE_GETTIMEOFDAY
   struct timeval time;
 
   SCM_DEFER_INTS;
   if (gettimeofday (&time, NULL) == -1)
-    scm_syserror (s_gettimeofday);
+    SCM_SYSERROR;
   SCM_ALLOW_INTS;
   return scm_cons (scm_long2num ((long) time.tv_sec),
                   scm_long2num ((long) time.tv_usec));
@@ -227,12 +252,13 @@ scm_gettimeofday (void)
   
   SCM_DEFER_INTS;
   if ((timv = time (0)) == -1)
-    scm_syserror (s_gettimeofday);
+    SCM_SYSERROR;
   SCM_ALLOW_INTS;
   return scm_cons (scm_long2num (timv), SCM_MAKINUM (0));
 # endif
 #endif
 }
+#undef FUNC_NAME
 
 static SCM
 filltime (struct tm *bd_time, int zoff, char *zname)
@@ -256,6 +282,10 @@ filltime (struct tm *bd_time, int zoff, char *zname)
 static char tzvar[3] = "TZ";
 extern char ** environ;
 
+/* if zone is set, create a temporary environment with only a TZ
+   string.  other threads or interrupt handlers shouldn't be allowed
+   to run until the corresponding restorezone is called.  hence the use
+   of a static variable for tmpenv is no big deal.  */
 static char **
 setzone (SCM zone, int pos, const char *subr)
 {
@@ -266,8 +296,7 @@ setzone (SCM zone, int pos, const char *subr)
       static char *tmpenv[2];
       char *buf;
 
-      /* if zone was supplied, set the environment temporarily.  */
-      SCM_ASSERT (SCM_NIMP (zone) && SCM_ROSTRINGP (zone), zone, pos, subr);
+      SCM_ASSERT (SCM_ROSTRINGP (zone), zone, pos, subr);
       SCM_COERCE_SUBSTR (zone);
       buf = scm_must_malloc (SCM_LENGTH (zone) + sizeof (tzvar) + 1,
                             subr);
@@ -276,7 +305,6 @@ setzone (SCM zone, int pos, const char *subr)
       tmpenv[0] = buf;
       tmpenv[1] = 0;
       environ = tmpenv;
-      tzset();
     }
   return oldenv;
 }
@@ -288,14 +316,21 @@ restorezone (SCM zone, char **oldenv, const char *subr)
     {
       scm_must_free (environ[0]);
       environ = oldenv;
+#ifdef HAVE_TZSET
+      /* for the possible benefit of user code linked with libguile.  */
       tzset();
+#endif
     }
 }
 
-
-SCM_PROC (s_localtime, "localtime", 1, 1, 0, scm_localtime);
-SCM
-scm_localtime (SCM time, SCM zone)
+SCM_DEFINE (scm_localtime, "localtime", 1, 1, 0, 
+            (SCM time, SCM zone),
+           "Returns an object representing the broken down components of @var{time},\n"
+           "an integer like the one returned by @code{current-time}.  The time zone\n"
+           "for the calculation is optionally specified by @var{zone} (a string),\n"
+           "otherwise the @code{TZ} environment variable or the system default is\n"
+           "used.")
+#define FUNC_NAME s_scm_localtime
 {
   timet itime;
   struct tm *ltptr, lt, *utc;
@@ -305,27 +340,30 @@ scm_localtime (SCM time, SCM zone)
   char **oldenv;
   int err;
 
-  itime = scm_num2long (time, (char *) SCM_ARG1, s_localtime);
+  itime = SCM_NUM2LONG (1,time);
+
+  /* deferring interupts is essential since a) setzone may install a temporary
+     environment b) localtime uses a static buffer.  */
   SCM_DEFER_INTS;
-  oldenv = setzone (zone, SCM_ARG2, s_localtime);
+  oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
+#ifdef LOCALTIME_CACHE
+  tzset ();
+#endif
   ltptr = localtime (&itime);
   err = errno;
   if (ltptr)
     {
       const char *ptr;
 
-      /* copy zone name before calling gmtime or tzset.  */
-#ifdef HAVE_TM_ZONE
+      /* copy zone name before calling gmtime or restoring zone.  */
+#if defined (HAVE_TM_ZONE)
       ptr = ltptr->tm_zone;
-#else
-# ifdef HAVE_TZNAME
+#elif defined (HAVE_TZNAME)
       ptr = tzname[ (ltptr->tm_isdst == 1) ? 1 : 0 ];
-# else
-      scm_misc_error (s_localtime, "Not fully implemented on this platform",
-                     SCM_EOL);
-# endif
+#else
+      ptr = "";
 #endif
-      zname = scm_must_malloc (strlen (ptr) + 1, s_localtime);
+      zname = SCM_MUST_MALLOC (strlen (ptr) + 1);
       strcpy (zname, ptr);
     }
   /* the struct is copied in case localtime and gmtime share a buffer.  */
@@ -334,11 +372,11 @@ scm_localtime (SCM time, SCM zone)
   utc = gmtime (&itime);
   if (utc == NULL)
     err = errno;
-  restorezone (zone, oldenv, s_localtime);
+  restorezone (zone, oldenv, FUNC_NAME);
   /* delayed until zone has been restored.  */
   errno = err;
   if (utc == NULL || ltptr == NULL)
-    scm_syserror (s_localtime);
+    SCM_SYSERROR;
 
   /* calculate timezone offset in seconds west of UTC.  */
   zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
@@ -357,24 +395,29 @@ scm_localtime (SCM time, SCM zone)
   scm_must_free (zname);
   return result;
 }
-
-SCM_PROC (s_gmtime, "gmtime", 1, 0, 0, scm_gmtime);
-SCM
-scm_gmtime (SCM time)
+#undef FUNC_NAME
+
+SCM_DEFINE (scm_gmtime, "gmtime", 1, 0, 0, 
+            (SCM time),
+           "Returns an object representing the broken down components of @var{time},\n"
+           "an integer like the one returned by @code{current-time}.  The values\n"
+           "are calculated for UTC.")
+#define FUNC_NAME s_scm_gmtime
 {
   timet itime;
   struct tm *bd_time;
   SCM result;
 
-  itime = scm_num2long (time, (char *) SCM_ARG1, s_gmtime);
+  itime = SCM_NUM2LONG (1,time);
   SCM_DEFER_INTS;
   bd_time = gmtime (&itime);
   if (bd_time == NULL)
-    scm_syserror (s_gmtime);
+    SCM_SYSERROR;
   result = filltime (bd_time, 0, "GMT");
   SCM_ALLOW_INTS;
   return result;
 }
+#undef FUNC_NAME
 
 /* copy time components from a Scheme object to a struct tm.  */
 static void
@@ -383,7 +426,7 @@ bdtime2c (SCM sbd_time, struct tm *lt, int pos, const char *subr)
   SCM *velts;
   int i;
 
-  SCM_ASSERT (SCM_NIMP (sbd_time) && SCM_VECTORP (sbd_time)
+  SCM_ASSERT (SCM_VECTORP (sbd_time)
              && SCM_LENGTH (sbd_time) == 11,
              sbd_time, pos, subr);
   velts = SCM_VELTS (sbd_time);
@@ -391,8 +434,7 @@ bdtime2c (SCM sbd_time, struct tm *lt, int pos, const char *subr)
     {
       SCM_ASSERT (SCM_INUMP (velts[i]), sbd_time, pos, subr);
     }
-  SCM_ASSERT (SCM_FALSEP (velts[10])
-             || (SCM_NIMP (velts[10]) && SCM_STRINGP (velts[10])),
+  SCM_ASSERT (SCM_FALSEP (velts[10]) || SCM_STRINGP (velts[10]),
              sbd_time, pos, subr);
 
   lt->tm_sec = SCM_INUM (velts[0]);
@@ -413,9 +455,16 @@ bdtime2c (SCM sbd_time, struct tm *lt, int pos, const char *subr)
 #endif
 }
 
-SCM_PROC (s_mktime, "mktime", 1, 1, 0, scm_mktime);
-SCM
-scm_mktime (SCM sbd_time, SCM zone)
+SCM_DEFINE (scm_mktime, "mktime", 1, 1, 0, 
+            (SCM sbd_time, SCM zone),
+           "@var{bd-time} is an object representing broken down time and @code{zone}\n"
+           "is an optional time zone specifier (otherwise the TZ environment variable\n"
+           "or the system default is used).\n\n"
+           "Returns a pair: the CAR is a corresponding\n"
+           "integer time value like that returned\n"
+           "by @code{current-time}; the CDR is a broken down time object, similar to\n"
+           "as @var{bd-time} but with normalized values.")
+#define FUNC_NAME s_scm_mktime
 {
   timet itime;
   struct tm lt, *utc;
@@ -425,10 +474,13 @@ scm_mktime (SCM sbd_time, SCM zone)
   char **oldenv;
   int err;
 
-  bdtime2c (sbd_time, &lt, SCM_ARG1, s_mktime);
+  bdtime2c (sbd_time, &lt, SCM_ARG1, FUNC_NAME);
 
   SCM_DEFER_INTS;
-  oldenv = setzone (zone, SCM_ARG2, s_mktime);
+  oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
+#ifdef LOCALTIME_CACHE
+  tzset ();
+#endif
   itime = mktime (&lt);
   err = errno;
 
@@ -436,18 +488,15 @@ scm_mktime (SCM sbd_time, SCM zone)
     {
       const char *ptr;
 
-      /* copy zone name before calling gmtime or tzset.  */
-#ifdef HAVE_TM_ZONE
+      /* copy zone name before calling gmtime or restoring the zone.  */
+#if defined (HAVE_TM_ZONE)
       ptr = lt.tm_zone;
-#else
-# ifdef HAVE_TZNAME
+#elif defined (HAVE_TZNAME)
       ptr = tzname[ (lt.tm_isdst == 1) ? 1 : 0 ];
-# else
-      scm_misc_error (s_mktime, "Not fully implemented on this platform",
-                     SCM_EOL);
-# endif
+#else
+      ptr = "";
 #endif
-      zname = scm_must_malloc (strlen (ptr) + 1, s_mktime);
+      zname = SCM_MUST_MALLOC (strlen (ptr) + 1);
       strcpy (zname, ptr);
     }
 
@@ -456,11 +505,11 @@ scm_mktime (SCM sbd_time, SCM zone)
   if (utc == NULL)
     err = errno;
 
-  restorezone (zone, oldenv, s_mktime);
+  restorezone (zone, oldenv, FUNC_NAME);
   /* delayed until zone has been restored.  */
   errno = err;
   if (utc == NULL || itime == -1)
-    scm_syserror (s_mktime);
+    SCM_SYSERROR;
 
   zoff = (utc->tm_hour - lt.tm_hour) * 3600 + (utc->tm_min - lt.tm_min) * 60
     + utc->tm_sec - lt.tm_sec;
@@ -479,21 +528,33 @@ scm_mktime (SCM sbd_time, SCM zone)
   scm_must_free (zname);
   return result;
 }
-
-SCM_PROC (s_tzset, "tzset", 0, 0, 0, scm_tzset);
-SCM
-scm_tzset (void)
+#undef FUNC_NAME
+
+#ifdef HAVE_TZSET
+SCM_DEFINE (scm_tzset, "tzset", 0, 0, 0, 
+            (void),
+           "Initialize the timezone from the TZ environment variable\n"
+           "or the system default.  It's not usually necessary to call this procedure\n"
+           "since it's done automatically by other procedures that depend on the\n"
+           "timezone.")
+#define FUNC_NAME s_scm_tzset
 {
   tzset();
   return SCM_UNSPECIFIED;
 }
-
-SCM_PROC (s_strftime, "strftime", 2, 0, 0, scm_strftime);
-
-SCM
-scm_strftime (format, stime)
-     SCM format;
-     SCM stime;
+#undef FUNC_NAME
+#endif /* HAVE_TZSET */
+
+SCM_DEFINE (scm_strftime, "strftime", 2, 0, 0,
+            (SCM format, SCM stime),
+           "Formats a time specification @var{time} using @var{template}.  @var{time}\n"
+           "is an object with time components in the form returned by @code{localtime}\n"
+           "or @code{gmtime}.  @var{template} is a string which can include formatting\n"
+           "specifications introduced by a @code{%} character.  The formatting of\n"
+           "month and day names is dependent on the current locale.  The value returned\n"
+           "is the formatted string.\n"
+           "@xref{Formatting Date and Time, , , libc, The GNU C Library Reference Manual}.)")
+#define FUNC_NAME s_scm_strftime
 {
   struct tm t;
 
@@ -503,41 +564,87 @@ scm_strftime (format, stime)
   int len;
   SCM result;
 
-  SCM_ASSERT (SCM_NIMP (format) && SCM_ROSTRINGP (format), format, SCM_ARG1,
-             s_strftime);
-  bdtime2c (stime, &t, SCM_ARG2, s_strftime);
+  SCM_VALIDATE_ROSTRING (1,format);
+  bdtime2c (stime, &t, SCM_ARG2, FUNC_NAME);
 
   SCM_COERCE_SUBSTR (format);
   fmt = SCM_ROCHARS (format);
   len = SCM_ROLENGTH (format);
 
-  tbuf = scm_must_malloc (size, s_strftime);
-  while ((len = strftime (tbuf, size, fmt, &t)) == size)
-    {
-      scm_must_free (tbuf);
-      size *= 2;
-      tbuf = scm_must_malloc (size, s_strftime);
+  tbuf = SCM_MUST_MALLOC (size);
+  {
+#if !defined (HAVE_TM_ZONE)
+    /* it seems the only way to tell non-GNU versions of strftime what
+       zone to use (for the %Z format) is to set TZ in the
+       environment.  interrupts and thread switching must be deferred
+       until TZ is restored.  */
+    char **oldenv = NULL;
+    SCM *velts = SCM_VELTS (stime);
+    int have_zone = 0;
+
+    if (SCM_NFALSEP (velts[10]) && *SCM_CHARS (velts[10]) != 0)
+      {
+       /* it's not required that the TZ setting be correct, just that
+          it has the right name.  so try something like TZ=EST0.
+          using only TZ=EST would be simpler but it doesn't work on
+          some OSs, e.g., Solaris.  */
+       SCM zone =
+         scm_string_append (scm_cons (velts[10],
+                                      scm_cons (scm_makfrom0str ("0"),
+                                                SCM_EOL)));
+       
+       have_zone = 1;
+       SCM_DEFER_INTS;
+       oldenv = setzone (zone, SCM_ARG2, FUNC_NAME);
+      }
+#endif
+
+#ifdef LOCALTIME_CACHE
+    tzset ();
+#endif
+
+    while ((len = strftime (tbuf, size, fmt, &t)) == size)
+      {
+       scm_must_free (tbuf);
+       size *= 2;
+       tbuf = SCM_MUST_MALLOC (size);
+      }
+
+#if !defined (HAVE_TM_ZONE)
+    if (have_zone)
+      {
+       restorezone (velts[10], oldenv, FUNC_NAME);
+       SCM_ALLOW_INTS;
+      }
+#endif
     }
+
   result = scm_makfromstr (tbuf, len, 0);
   scm_must_free (tbuf);
   return result;
 }
+#undef FUNC_NAME
 
-SCM_PROC (s_strptime, "strptime", 2, 0, 0, scm_strptime);
-
-SCM
-scm_strptime (format, string)
-     SCM format;
-     SCM string;
-{
 #ifdef HAVE_STRPTIME
+SCM_DEFINE (scm_strptime, "strptime", 2, 0, 0,
+            (SCM format, SCM string),
+           "Performs the reverse action to @code{strftime}, parsing @var{string}\n"
+           "according to the specification supplied in @var{template}.  The\n"
+           "interpretation of month and day names is dependent on the current\n"
+           "locale.  The\n"
+           "value returned is a pair.  The CAR has an object with time components \n"
+           "in the form returned by @code{localtime} or @code{gmtime},\n"
+           "but the time zone components\n"
+           "are not usefully set.\n"
+           "The CDR reports the number of characters from @var{string} which\n"
+           "vwere used for the conversion.")
+#define FUNC_NAME s_scm_strptime
+{
   struct tm t;
   char *fmt, *str, *rest;
 
-  SCM_ASSERT (SCM_NIMP (format) && SCM_ROSTRINGP (format), format, SCM_ARG1,
-             s_strptime);
-  SCM_ASSERT (SCM_NIMP (string) && SCM_ROSTRINGP (string), string, SCM_ARG2,
-             s_strptime);
+  SCM_VALIDATE_ROSTRING (1,format);
+  SCM_VALIDATE_ROSTRING (2,string);
 
   SCM_COERCE_SUBSTR (format);
   SCM_COERCE_SUBSTR (string);
@@ -559,15 +666,13 @@ scm_strptime (format, string)
   t.tm_isdst = -1;
   SCM_DEFER_INTS;
   if ((rest = strptime (str, fmt, &t)) == NULL)
-    scm_syserror (s_strptime);
+    SCM_SYSERROR;
 
   SCM_ALLOW_INTS;
   return scm_cons (filltime (&t, 0, NULL),  SCM_MAKINUM (rest - str));
-
-#else
-  scm_sysmissing (s_strptime);
-#endif
 }
+#undef FUNC_NAME
+#endif /* HAVE_STRPTIME */
 
 void
 scm_init_stime()
@@ -584,6 +689,12 @@ scm_init_stime()
   if (!scm_my_base) scm_my_base = mytime();
 
   scm_add_feature ("current-time");
-#include "stime.x"
+#include "libguile/stime.x"
 }
 
+
+/*
+  Local Variables:
+  c-file-style: "gnu"
+  End:
+*/