Improve parsing of date-only iso8601 strings
[platform/upstream/glib.git] / glib / gtimer.c
1 /* GLIB - Library of useful routines for C programming
2  * Copyright (C) 1995-1997  Peter Mattis, Spencer Kimball and Josh MacDonald
3  *
4  * This library is free software; you can redistribute it and/or
5  * modify it under the terms of the GNU Lesser General Public
6  * License as published by the Free Software Foundation; either
7  * version 2 of the License, or (at your option) any later version.
8  *
9  * This library is distributed in the hope that it will be useful,
10  * but WITHOUT ANY WARRANTY; without even the implied warranty of
11  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12  * Lesser General Public License for more details.
13  *
14  * You should have received a copy of the GNU Lesser General Public
15  * License along with this library; if not, write to the
16  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
17  * Boston, MA 02111-1307, USA.
18  */
19
20 /*
21  * Modified by the GLib Team and others 1997-2000.  See the AUTHORS
22  * file for a list of people on the GLib Team.  See the ChangeLog
23  * files for a list of changes.  These files are distributed with
24  * GLib at ftp://ftp.gtk.org/pub/gtk/. 
25  */
26
27 /* 
28  * MT safe
29  */
30
31 #include "config.h"
32 #include "glibconfig.h"
33
34 #include <stdlib.h>
35
36 #ifdef HAVE_UNISTD_H
37 #include <unistd.h>
38 #endif /* HAVE_UNISTD_H */
39
40 #ifndef G_OS_WIN32
41 #include <sys/time.h>
42 #include <time.h>
43 #include <errno.h>
44 #endif /* G_OS_WIN32 */
45
46 #ifdef G_OS_WIN32
47 #include <windows.h>
48 #endif /* G_OS_WIN32 */
49
50 #include "glib.h"
51 #include "gthread.h"
52
53 /**
54  * SECTION: timers
55  * @title: Timers
56  * @short_description: keep track of elapsed time
57  *
58  * #GTimer records a start time, and counts microseconds elapsed since
59  * that time. This is done somewhat differently on different platforms,
60  * and can be tricky to get exactly right, so #GTimer provides a
61  * portable/convenient interface.
62  *
63  * <note><para>
64  *  #GTimer uses a higher-quality clock when thread support is available.
65  *  Therefore, calling g_thread_init() while timers are running may lead to
66  *  unreliable results. It is best to call g_thread_init() before starting any
67  *  timers, if you are using threads at all.
68  * </para></note>
69  **/
70
71 #define G_NSEC_PER_SEC 1000000000
72
73 #define GETTIME(v) (v = g_thread_gettime ())
74
75 /**
76  * GTimer:
77  *
78  * Opaque datatype that records a start time.
79  **/
80 struct _GTimer
81 {
82   guint64 start;
83   guint64 end;
84
85   guint active : 1;
86 };
87
88 /**
89  * g_timer_new:
90  * @Returns: a new #GTimer.
91  *
92  * Creates a new timer, and starts timing (i.e. g_timer_start() is
93  * implicitly called for you).
94  **/
95 GTimer*
96 g_timer_new (void)
97 {
98   GTimer *timer;
99
100   timer = g_new (GTimer, 1);
101   timer->active = TRUE;
102
103   GETTIME (timer->start);
104
105   return timer;
106 }
107
108 /**
109  * g_timer_destroy:
110  * @timer: a #GTimer to destroy.
111  *
112  * Destroys a timer, freeing associated resources.
113  **/
114 void
115 g_timer_destroy (GTimer *timer)
116 {
117   g_return_if_fail (timer != NULL);
118
119   g_free (timer);
120 }
121
122 /**
123  * g_timer_start:
124  * @timer: a #GTimer.
125  *
126  * Marks a start time, so that future calls to g_timer_elapsed() will
127  * report the time since g_timer_start() was called. g_timer_new()
128  * automatically marks the start time, so no need to call
129  * g_timer_start() immediately after creating the timer.
130  **/
131 void
132 g_timer_start (GTimer *timer)
133 {
134   g_return_if_fail (timer != NULL);
135
136   timer->active = TRUE;
137
138   GETTIME (timer->start);
139 }
140
141 /**
142  * g_timer_stop:
143  * @timer: a #GTimer.
144  *
145  * Marks an end time, so calls to g_timer_elapsed() will return the
146  * difference between this end time and the start time.
147  **/
148 void
149 g_timer_stop (GTimer *timer)
150 {
151   g_return_if_fail (timer != NULL);
152
153   timer->active = FALSE;
154
155   GETTIME (timer->end);
156 }
157
158 /**
159  * g_timer_reset:
160  * @timer: a #GTimer.
161  *
162  * This function is useless; it's fine to call g_timer_start() on an
163  * already-started timer to reset the start time, so g_timer_reset()
164  * serves no purpose.
165  **/
166 void
167 g_timer_reset (GTimer *timer)
168 {
169   g_return_if_fail (timer != NULL);
170
171   GETTIME (timer->start);
172 }
173
174 /**
175  * g_timer_continue:
176  * @timer: a #GTimer.
177  *
178  * Resumes a timer that has previously been stopped with
179  * g_timer_stop(). g_timer_stop() must be called before using this
180  * function.
181  *
182  * Since: 2.4
183  **/
184 void
185 g_timer_continue (GTimer *timer)
186 {
187   guint64 elapsed;
188
189   g_return_if_fail (timer != NULL);
190   g_return_if_fail (timer->active == FALSE);
191
192   /* Get elapsed time and reset timer start time
193    *  to the current time minus the previously
194    *  elapsed interval.
195    */
196
197   elapsed = timer->end - timer->start;
198
199   GETTIME (timer->start);
200
201   timer->start -= elapsed;
202
203   timer->active = TRUE;
204 }
205
206 /**
207  * g_timer_elapsed:
208  * @timer: a #GTimer.
209  * @microseconds: return location for the fractional part of seconds
210  *                elapsed, in microseconds (that is, the total number
211  *                of microseconds elapsed, modulo 1000000), or %NULL
212  * @Returns: seconds elapsed as a floating point value, including any
213  *           fractional part.
214  *
215  * If @timer has been started but not stopped, obtains the time since
216  * the timer was started. If @timer has been stopped, obtains the
217  * elapsed time between the time it was started and the time it was
218  * stopped. The return value is the number of seconds elapsed,
219  * including any fractional part. The @microseconds out parameter is
220  * essentially useless.
221  *
222  * <warning><para>
223  *  Calling initialization functions, in particular g_thread_init(), while a
224  *  timer is running will cause invalid return values from this function.
225  * </para></warning>
226  **/
227 gdouble
228 g_timer_elapsed (GTimer *timer,
229                  gulong *microseconds)
230 {
231   gdouble total;
232   gint64 elapsed;
233
234   g_return_val_if_fail (timer != NULL, 0);
235
236   if (timer->active)
237     GETTIME (timer->end);
238
239   elapsed = timer->end - timer->start;
240
241   total = elapsed / 1e9;
242
243   if (microseconds)
244     *microseconds = (elapsed / 1000) % 1000000;
245
246   return total;
247 }
248
249 void
250 g_usleep (gulong microseconds)
251 {
252 #ifdef G_OS_WIN32
253   Sleep (microseconds / 1000);
254 #else /* !G_OS_WIN32 */
255 # ifdef HAVE_NANOSLEEP
256   struct timespec request, remaining;
257   request.tv_sec = microseconds / G_USEC_PER_SEC;
258   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
259   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
260     request = remaining;
261 # else /* !HAVE_NANOSLEEP */
262 #  ifdef HAVE_NSLEEP
263   /* on AIX, nsleep is analogous to nanosleep */
264   struct timespec request, remaining;
265   request.tv_sec = microseconds / G_USEC_PER_SEC;
266   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
267   while (nsleep (&request, &remaining) == -1 && errno == EINTR)
268     request = remaining;
269 #  else /* !HAVE_NSLEEP */
270   if (g_thread_supported ())
271     {
272       static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
273       static GCond* cond = NULL;
274       GTimeVal end_time;
275       
276       g_get_current_time (&end_time);
277       if (microseconds > G_MAXLONG)
278         {
279           microseconds -= G_MAXLONG;
280           g_time_val_add (&end_time, G_MAXLONG);
281         }
282       g_time_val_add (&end_time, microseconds);
283
284       g_static_mutex_lock (&mutex);
285       
286       if (!cond)
287         cond = g_cond_new ();
288       
289       while (g_cond_timed_wait (cond, g_static_mutex_get_mutex (&mutex), 
290                                 &end_time))
291         /* do nothing */;
292       
293       g_static_mutex_unlock (&mutex);
294     }
295   else
296     {
297       struct timeval tv;
298       tv.tv_sec = microseconds / G_USEC_PER_SEC;
299       tv.tv_usec = microseconds % G_USEC_PER_SEC;
300       select(0, NULL, NULL, NULL, &tv);
301     }
302 #  endif /* !HAVE_NSLEEP */
303 # endif /* !HAVE_NANOSLEEP */
304 #endif /* !G_OS_WIN32 */
305 }
306
307 /**
308  * g_time_val_add:
309  * @time_: a #GTimeVal
310  * @microseconds: number of microseconds to add to @time
311  *
312  * Adds the given number of microseconds to @time_. @microseconds can
313  * also be negative to decrease the value of @time_.
314  **/
315 void 
316 g_time_val_add (GTimeVal *time_, glong microseconds)
317 {
318   g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
319
320   if (microseconds >= 0)
321     {
322       time_->tv_usec += microseconds % G_USEC_PER_SEC;
323       time_->tv_sec += microseconds / G_USEC_PER_SEC;
324       if (time_->tv_usec >= G_USEC_PER_SEC)
325        {
326          time_->tv_usec -= G_USEC_PER_SEC;
327          time_->tv_sec++;
328        }
329     }
330   else
331     {
332       microseconds *= -1;
333       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
334       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
335       if (time_->tv_usec < 0)
336        {
337          time_->tv_usec += G_USEC_PER_SEC;
338          time_->tv_sec--;
339        }      
340     }
341 }
342
343 /* converts a broken down date representation, relative to UTC, to
344  * a timestamp; it uses timegm() if it's available.
345  */
346 static time_t
347 mktime_utc (struct tm *tm)
348 {
349   time_t retval;
350   
351 #ifndef HAVE_TIMEGM
352   static const gint days_before[] =
353   {
354     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
355   };
356 #endif
357
358 #ifndef HAVE_TIMEGM
359   if (tm->tm_mon < 0 || tm->tm_mon > 11)
360     return (time_t) -1;
361
362   retval = (tm->tm_year - 70) * 365;
363   retval += (tm->tm_year - 68) / 4;
364   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
365   
366   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
367     retval -= 1;
368   
369   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
370 #else
371   retval = timegm (tm);
372 #endif /* !HAVE_TIMEGM */
373   
374   return retval;
375 }
376
377 /**
378  * g_time_val_from_iso8601:
379  * @iso_date: an ISO 8601 encoded date string
380  * @time_: a #GTimeVal
381  *
382  * Converts a string containing an ISO 8601 encoded date and time
383  * to a #GTimeVal and puts it into @time_.
384  *
385  * Return value: %TRUE if the conversion was successful.
386  *
387  * Since: 2.12
388  */
389 gboolean
390 g_time_val_from_iso8601 (const gchar *iso_date,
391                          GTimeVal    *time_)
392 {
393   struct tm tm = {0};
394   long val;
395
396   g_return_val_if_fail (iso_date != NULL, FALSE);
397   g_return_val_if_fail (time_ != NULL, FALSE);
398
399   /* Ensure that the first character is a digit,
400    * the first digit of the date, otherwise we don't
401    * have an ISO 8601 date */
402   while (g_ascii_isspace (*iso_date))
403     iso_date++;
404
405   if (*iso_date == '\0')
406     return FALSE;
407
408   if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
409     return FALSE;
410
411   val = strtoul (iso_date, (char **)&iso_date, 10);
412   if (*iso_date == '-')
413     {
414       /* YYYY-MM-DD */
415       tm.tm_year = val - 1900;
416       iso_date++;
417       tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
418       
419       if (*iso_date++ != '-')
420         return FALSE;
421       
422       tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
423     }
424   else
425     {
426       /* YYYYMMDD */
427       tm.tm_mday = val % 100;
428       tm.tm_mon = (val % 10000) / 100 - 1;
429       tm.tm_year = val / 10000 - 1900;
430     }
431
432   if (*iso_date != 'T')
433     {
434       /* Date only */
435       if (*iso_date == '\0')
436         return TRUE;
437       return FALSE;
438     }
439
440   *iso_date++;
441
442   /* If there is a 'T' then there has to be a time */
443   if (!g_ascii_isdigit (*iso_date))
444     return FALSE;
445
446   val = strtoul (iso_date, (char **)&iso_date, 10);
447   if (*iso_date == ':')
448     {
449       /* hh:mm:ss */
450       tm.tm_hour = val;
451       iso_date++;
452       tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
453       
454       if (*iso_date++ != ':')
455         return FALSE;
456       
457       tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
458     }
459   else
460     {
461       /* hhmmss */
462       tm.tm_sec = val % 100;
463       tm.tm_min = (val % 10000) / 100;
464       tm.tm_hour = val / 10000;
465     }
466
467   time_->tv_usec = 0;
468   
469   if (*iso_date == ',' || *iso_date == '.')
470     {
471       glong mul = 100000;
472
473       while (g_ascii_isdigit (*++iso_date))
474         {
475           time_->tv_usec += (*iso_date - '0') * mul;
476           mul /= 10;
477         }
478     }
479     
480   /* Now parse the offset and convert tm to a time_t */
481   if (*iso_date == 'Z')
482     {
483       iso_date++;
484       time_->tv_sec = mktime_utc (&tm);
485     }
486   else if (*iso_date == '+' || *iso_date == '-')
487     {
488       gint sign = (*iso_date == '+') ? -1 : 1;
489       
490       val = strtoul (iso_date + 1, (char **)&iso_date, 10);
491       
492       if (*iso_date == ':')
493         val = 60 * val + strtoul (iso_date + 1, (char **)&iso_date, 10);
494       else
495         val = 60 * (val / 100) + (val % 100);
496
497       time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * val * sign);
498     }
499   else
500     {
501       /* No "Z" or offset, so local time */
502       tm.tm_isdst = -1; /* locale selects DST */
503       time_->tv_sec = mktime (&tm);
504     }
505
506   while (g_ascii_isspace (*iso_date))
507     iso_date++;
508
509   return *iso_date == '\0';
510 }
511
512 /**
513  * g_time_val_to_iso8601:
514  * @time_: a #GTimeVal
515  * 
516  * Converts @time_ into an ISO 8601 encoded string, relative to the
517  * Coordinated Universal Time (UTC).
518  *
519  * Return value: a newly allocated string containing an ISO 8601 date
520  *
521  * Since: 2.12
522  */
523 gchar *
524 g_time_val_to_iso8601 (GTimeVal *time_)
525 {
526   gchar *retval;
527   struct tm *tm;
528 #ifdef HAVE_GMTIME_R
529   struct tm tm_;
530 #endif
531   time_t secs;
532   
533   g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
534
535  secs = time_->tv_sec;
536 #ifdef _WIN32
537  tm = gmtime (&secs);
538 #else
539 #ifdef HAVE_GMTIME_R
540   tm = gmtime_r (&secs, &tm_);
541 #else
542   tm = gmtime (&secs);
543 #endif
544 #endif
545
546   if (time_->tv_usec != 0)
547     {
548       /* ISO 8601 date and time format, with fractionary seconds:
549        *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
550        */
551       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
552                                 tm->tm_year + 1900,
553                                 tm->tm_mon + 1,
554                                 tm->tm_mday,
555                                 tm->tm_hour,
556                                 tm->tm_min,
557                                 tm->tm_sec,
558                                 time_->tv_usec);
559     }
560   else
561     {
562       /* ISO 8601 date and time format:
563        *   YYYY-MM-DDTHH:MM:SSZ
564        */
565       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
566                                 tm->tm_year + 1900,
567                                 tm->tm_mon + 1,
568                                 tm->tm_mday,
569                                 tm->tm_hour,
570                                 tm->tm_min,
571                                 tm->tm_sec);
572     }
573   
574   return retval;
575 }