Improve parsing of date-only iso8601 strings
[platform/upstream/glib.git] / glib / gtimer.c
index 30e249e..05fcbc5 100644 (file)
  * MT safe
  */
 
-#ifdef HAVE_CONFIG_H
-#include <config.h>
-#endif
+#include "config.h"
+#include "glibconfig.h"
+
+#include <stdlib.h>
 
-#include "glib.h"
 #ifdef HAVE_UNISTD_H
 #include <unistd.h>
 #endif /* HAVE_UNISTD_H */
+
 #ifndef G_OS_WIN32
 #include <sys/time.h>
 #include <time.h>
 #include <windows.h>
 #endif /* G_OS_WIN32 */
 
+#include "glib.h"
+#include "gthread.h"
+
+/**
+ * SECTION: timers
+ * @title: Timers
+ * @short_description: keep track of elapsed time
+ *
+ * #GTimer records a start time, and counts microseconds elapsed since
+ * that time. This is done somewhat differently on different platforms,
+ * and can be tricky to get exactly right, so #GTimer provides a
+ * portable/convenient interface.
+ *
+ * <note><para>
+ *  #GTimer uses a higher-quality clock when thread support is available.
+ *  Therefore, calling g_thread_init() while timers are running may lead to
+ *  unreliable results. It is best to call g_thread_init() before starting any
+ *  timers, if you are using threads at all.
+ * </para></note>
+ **/
+
+#define G_NSEC_PER_SEC 1000000000
+
+#define GETTIME(v) (v = g_thread_gettime ())
+
+/**
+ * GTimer:
+ *
+ * Opaque datatype that records a start time.
+ **/
 struct _GTimer
 {
-#ifdef G_OS_WIN32
-  DWORD start;
-  DWORD end;
-#else /* !G_OS_WIN32 */
-  struct timeval start;
-  struct timeval end;
-#endif /* !G_OS_WIN32 */
+  guint64 start;
+  guint64 end;
 
   guint active : 1;
 };
 
-#ifdef G_OS_WIN32
-#  define GETTIME(v) \
-     v = GetTickCount ()
-#else /* !G_OS_WIN32 */
-#  define GETTIME(v) \
-     gettimeofday (&v, NULL)
-#endif /* !G_OS_WIN32 */
-
+/**
+ * g_timer_new:
+ * @Returns: a new #GTimer.
+ *
+ * Creates a new timer, and starts timing (i.e. g_timer_start() is
+ * implicitly called for you).
+ **/
 GTimer*
 g_timer_new (void)
 {
@@ -80,6 +105,12 @@ g_timer_new (void)
   return timer;
 }
 
+/**
+ * g_timer_destroy:
+ * @timer: a #GTimer to destroy.
+ *
+ * Destroys a timer, freeing associated resources.
+ **/
 void
 g_timer_destroy (GTimer *timer)
 {
@@ -88,6 +119,15 @@ g_timer_destroy (GTimer *timer)
   g_free (timer);
 }
 
+/**
+ * g_timer_start:
+ * @timer: a #GTimer.
+ *
+ * Marks a start time, so that future calls to g_timer_elapsed() will
+ * report the time since g_timer_start() was called. g_timer_new()
+ * automatically marks the start time, so no need to call
+ * g_timer_start() immediately after creating the timer.
+ **/
 void
 g_timer_start (GTimer *timer)
 {
@@ -98,6 +138,13 @@ g_timer_start (GTimer *timer)
   GETTIME (timer->start);
 }
 
+/**
+ * g_timer_stop:
+ * @timer: a #GTimer.
+ *
+ * Marks an end time, so calls to g_timer_elapsed() will return the
+ * difference between this end time and the start time.
+ **/
 void
 g_timer_stop (GTimer *timer)
 {
@@ -105,9 +152,17 @@ g_timer_stop (GTimer *timer)
 
   timer->active = FALSE;
 
-  GETTIME(timer->end);
+  GETTIME (timer->end);
 }
 
+/**
+ * g_timer_reset:
+ * @timer: a #GTimer.
+ *
+ * This function is useless; it's fine to call g_timer_start() on an
+ * already-started timer to reset the start time, so g_timer_reset()
+ * serves no purpose.
+ **/
 void
 g_timer_reset (GTimer *timer)
 {
@@ -116,61 +171,77 @@ g_timer_reset (GTimer *timer)
   GETTIME (timer->start);
 }
 
+/**
+ * g_timer_continue:
+ * @timer: a #GTimer.
+ *
+ * Resumes a timer that has previously been stopped with
+ * g_timer_stop(). g_timer_stop() must be called before using this
+ * function.
+ *
+ * Since: 2.4
+ **/
+void
+g_timer_continue (GTimer *timer)
+{
+  guint64 elapsed;
+
+  g_return_if_fail (timer != NULL);
+  g_return_if_fail (timer->active == FALSE);
+
+  /* Get elapsed time and reset timer start time
+   *  to the current time minus the previously
+   *  elapsed interval.
+   */
+
+  elapsed = timer->end - timer->start;
+
+  GETTIME (timer->start);
+
+  timer->start -= elapsed;
+
+  timer->active = TRUE;
+}
+
+/**
+ * g_timer_elapsed:
+ * @timer: a #GTimer.
+ * @microseconds: return location for the fractional part of seconds
+ *                elapsed, in microseconds (that is, the total number
+ *                of microseconds elapsed, modulo 1000000), or %NULL
+ * @Returns: seconds elapsed as a floating point value, including any
+ *           fractional part.
+ *
+ * If @timer has been started but not stopped, obtains the time since
+ * the timer was started. If @timer has been stopped, obtains the
+ * elapsed time between the time it was started and the time it was
+ * stopped. The return value is the number of seconds elapsed,
+ * including any fractional part. The @microseconds out parameter is
+ * essentially useless.
+ *
+ * <warning><para>
+ *  Calling initialization functions, in particular g_thread_init(), while a
+ *  timer is running will cause invalid return values from this function.
+ * </para></warning>
+ **/
 gdouble
 g_timer_elapsed (GTimer *timer,
                 gulong *microseconds)
 {
   gdouble total;
-#ifndef G_OS_WIN32
-  struct timeval elapsed;
-#endif /* G_OS_WIN32 */
+  gint64 elapsed;
 
   g_return_val_if_fail (timer != NULL, 0);
 
-#ifdef G_OS_WIN32
   if (timer->active)
-    timer->end = GetTickCount ();
+    GETTIME (timer->end);
 
-  /* Check for wraparound, which happens every 49.7 days. */
-  if (timer->end < timer->start)
-    total = (UINT_MAX - (timer->start - timer->end)) / 1000.0;
-  else
-    total = (timer->end - timer->start) / 1000.0;
+  elapsed = timer->end - timer->start;
 
-  if (microseconds)
-    {
-      if (timer->end < timer->start)
-       *microseconds =
-         ((UINT_MAX - (timer->start - timer->end)) % 1000) * 1000;
-      else
-       *microseconds =
-         ((timer->end - timer->start) % 1000) * 1000;
-    }
-#else /* !G_OS_WIN32 */
-  if (timer->active)
-    gettimeofday (&timer->end, NULL);
+  total = elapsed / 1e9;
 
-  if (timer->start.tv_usec > timer->end.tv_usec)
-    {
-      timer->end.tv_usec += G_USEC_PER_SEC;
-      timer->end.tv_sec--;
-    }
-
-  elapsed.tv_usec = timer->end.tv_usec - timer->start.tv_usec;
-  elapsed.tv_sec = timer->end.tv_sec - timer->start.tv_sec;
-
-  total = elapsed.tv_sec + ((gdouble) elapsed.tv_usec / 1e6);
-  if (total < 0)
-    {
-      total = 0;
-
-      if (microseconds)
-       *microseconds = 0;
-    }
-  else if (microseconds)
-    *microseconds = elapsed.tv_usec;
-
-#endif /* !G_OS_WIN32 */
+  if (microseconds)
+    *microseconds = (elapsed / 1000) % 1000000;
 
   return total;
 }
@@ -185,9 +256,17 @@ g_usleep (gulong microseconds)
   struct timespec request, remaining;
   request.tv_sec = microseconds / G_USEC_PER_SEC;
   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
-  while (nanosleep (&request, &remaining) == EINTR)
+  while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
     request = remaining;
 # else /* !HAVE_NANOSLEEP */
+#  ifdef HAVE_NSLEEP
+  /* on AIX, nsleep is analogous to nanosleep */
+  struct timespec request, remaining;
+  request.tv_sec = microseconds / G_USEC_PER_SEC;
+  request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
+  while (nsleep (&request, &remaining) == -1 && errno == EINTR)
+    request = remaining;
+#  else /* !HAVE_NSLEEP */
   if (g_thread_supported ())
     {
       static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
@@ -220,6 +299,7 @@ g_usleep (gulong microseconds)
       tv.tv_usec = microseconds % G_USEC_PER_SEC;
       select(0, NULL, NULL, NULL, &tv);
     }
+#  endif /* !HAVE_NSLEEP */
 # endif /* !HAVE_NANOSLEEP */
 #endif /* !G_OS_WIN32 */
 }
@@ -259,3 +339,237 @@ g_time_val_add (GTimeVal *time_, glong microseconds)
        }      
     }
 }
+
+/* converts a broken down date representation, relative to UTC, to
+ * a timestamp; it uses timegm() if it's available.
+ */
+static time_t
+mktime_utc (struct tm *tm)
+{
+  time_t retval;
+  
+#ifndef HAVE_TIMEGM
+  static const gint days_before[] =
+  {
+    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
+  };
+#endif
+
+#ifndef HAVE_TIMEGM
+  if (tm->tm_mon < 0 || tm->tm_mon > 11)
+    return (time_t) -1;
+
+  retval = (tm->tm_year - 70) * 365;
+  retval += (tm->tm_year - 68) / 4;
+  retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
+  
+  if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
+    retval -= 1;
+  
+  retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
+#else
+  retval = timegm (tm);
+#endif /* !HAVE_TIMEGM */
+  
+  return retval;
+}
+
+/**
+ * g_time_val_from_iso8601:
+ * @iso_date: an ISO 8601 encoded date string
+ * @time_: a #GTimeVal
+ *
+ * Converts a string containing an ISO 8601 encoded date and time
+ * to a #GTimeVal and puts it into @time_.
+ *
+ * Return value: %TRUE if the conversion was successful.
+ *
+ * Since: 2.12
+ */
+gboolean
+g_time_val_from_iso8601 (const gchar *iso_date,
+                        GTimeVal    *time_)
+{
+  struct tm tm = {0};
+  long val;
+
+  g_return_val_if_fail (iso_date != NULL, FALSE);
+  g_return_val_if_fail (time_ != NULL, FALSE);
+
+  /* Ensure that the first character is a digit,
+   * the first digit of the date, otherwise we don't
+   * have an ISO 8601 date */
+  while (g_ascii_isspace (*iso_date))
+    iso_date++;
+
+  if (*iso_date == '\0')
+    return FALSE;
+
+  if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
+    return FALSE;
+
+  val = strtoul (iso_date, (char **)&iso_date, 10);
+  if (*iso_date == '-')
+    {
+      /* YYYY-MM-DD */
+      tm.tm_year = val - 1900;
+      iso_date++;
+      tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
+      
+      if (*iso_date++ != '-')
+        return FALSE;
+      
+      tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
+    }
+  else
+    {
+      /* YYYYMMDD */
+      tm.tm_mday = val % 100;
+      tm.tm_mon = (val % 10000) / 100 - 1;
+      tm.tm_year = val / 10000 - 1900;
+    }
+
+  if (*iso_date != 'T')
+    {
+      /* Date only */
+      if (*iso_date == '\0')
+        return TRUE;
+      return FALSE;
+    }
+
+  *iso_date++;
+
+  /* If there is a 'T' then there has to be a time */
+  if (!g_ascii_isdigit (*iso_date))
+    return FALSE;
+
+  val = strtoul (iso_date, (char **)&iso_date, 10);
+  if (*iso_date == ':')
+    {
+      /* hh:mm:ss */
+      tm.tm_hour = val;
+      iso_date++;
+      tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
+      
+      if (*iso_date++ != ':')
+        return FALSE;
+      
+      tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
+    }
+  else
+    {
+      /* hhmmss */
+      tm.tm_sec = val % 100;
+      tm.tm_min = (val % 10000) / 100;
+      tm.tm_hour = val / 10000;
+    }
+
+  time_->tv_usec = 0;
+  
+  if (*iso_date == ',' || *iso_date == '.')
+    {
+      glong mul = 100000;
+
+      while (g_ascii_isdigit (*++iso_date))
+        {
+          time_->tv_usec += (*iso_date - '0') * mul;
+          mul /= 10;
+        }
+    }
+    
+  /* Now parse the offset and convert tm to a time_t */
+  if (*iso_date == 'Z')
+    {
+      iso_date++;
+      time_->tv_sec = mktime_utc (&tm);
+    }
+  else if (*iso_date == '+' || *iso_date == '-')
+    {
+      gint sign = (*iso_date == '+') ? -1 : 1;
+      
+      val = strtoul (iso_date + 1, (char **)&iso_date, 10);
+      
+      if (*iso_date == ':')
+        val = 60 * val + strtoul (iso_date + 1, (char **)&iso_date, 10);
+      else
+        val = 60 * (val / 100) + (val % 100);
+
+      time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * val * sign);
+    }
+  else
+    {
+      /* No "Z" or offset, so local time */
+      tm.tm_isdst = -1; /* locale selects DST */
+      time_->tv_sec = mktime (&tm);
+    }
+
+  while (g_ascii_isspace (*iso_date))
+    iso_date++;
+
+  return *iso_date == '\0';
+}
+
+/**
+ * g_time_val_to_iso8601:
+ * @time_: a #GTimeVal
+ * 
+ * Converts @time_ into an ISO 8601 encoded string, relative to the
+ * Coordinated Universal Time (UTC).
+ *
+ * Return value: a newly allocated string containing an ISO 8601 date
+ *
+ * Since: 2.12
+ */
+gchar *
+g_time_val_to_iso8601 (GTimeVal *time_)
+{
+  gchar *retval;
+  struct tm *tm;
+#ifdef HAVE_GMTIME_R
+  struct tm tm_;
+#endif
+  time_t secs;
+  
+  g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
+
+ secs = time_->tv_sec;
+#ifdef _WIN32
+ tm = gmtime (&secs);
+#else
+#ifdef HAVE_GMTIME_R
+  tm = gmtime_r (&secs, &tm_);
+#else
+  tm = gmtime (&secs);
+#endif
+#endif
+
+  if (time_->tv_usec != 0)
+    {
+      /* ISO 8601 date and time format, with fractionary seconds:
+       *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
+       */
+      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
+                                tm->tm_year + 1900,
+                                tm->tm_mon + 1,
+                                tm->tm_mday,
+                                tm->tm_hour,
+                                tm->tm_min,
+                                tm->tm_sec,
+                                time_->tv_usec);
+    }
+  else
+    {
+      /* ISO 8601 date and time format:
+       *   YYYY-MM-DDTHH:MM:SSZ
+       */
+      retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
+                                tm->tm_year + 1900,
+                                tm->tm_mon + 1,
+                                tm->tm_mday,
+                                tm->tm_hour,
+                                tm->tm_min,
+                                tm->tm_sec);
+    }
+  
+  return retval;
+}