g_time_val_from_iso8601: handle timezoneless dates
[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 #include "galias.h"
53
54 #define G_NSEC_PER_SEC 1000000000
55
56 #define GETTIME(v) (v = g_thread_gettime ())
57
58 struct _GTimer
59 {
60   guint64 start;
61   guint64 end;
62
63   guint active : 1;
64 };
65
66
67 GTimer*
68 g_timer_new (void)
69 {
70   GTimer *timer;
71
72   timer = g_new (GTimer, 1);
73   timer->active = TRUE;
74
75   GETTIME (timer->start);
76
77   return timer;
78 }
79
80 void
81 g_timer_destroy (GTimer *timer)
82 {
83   g_return_if_fail (timer != NULL);
84
85   g_free (timer);
86 }
87
88 void
89 g_timer_start (GTimer *timer)
90 {
91   g_return_if_fail (timer != NULL);
92
93   timer->active = TRUE;
94
95   GETTIME (timer->start);
96 }
97
98 void
99 g_timer_stop (GTimer *timer)
100 {
101   g_return_if_fail (timer != NULL);
102
103   timer->active = FALSE;
104
105   GETTIME (timer->end);
106 }
107
108 void
109 g_timer_reset (GTimer *timer)
110 {
111   g_return_if_fail (timer != NULL);
112
113   GETTIME (timer->start);
114 }
115
116 void
117 g_timer_continue (GTimer *timer)
118 {
119   guint64 elapsed;
120
121   g_return_if_fail (timer != NULL);
122   g_return_if_fail (timer->active == FALSE);
123
124   /* Get elapsed time and reset timer start time
125    *  to the current time minus the previously
126    *  elapsed interval.
127    */
128
129   elapsed = timer->end - timer->start;
130
131   GETTIME (timer->start);
132
133   timer->start -= elapsed;
134
135   timer->active = TRUE;
136 }
137
138 gdouble
139 g_timer_elapsed (GTimer *timer,
140                  gulong *microseconds)
141 {
142   gdouble total;
143   gint64 elapsed;
144
145   g_return_val_if_fail (timer != NULL, 0);
146
147   if (timer->active)
148     GETTIME (timer->end);
149
150   elapsed = timer->end - timer->start;
151
152   total = elapsed / 1e9;
153
154   if (microseconds)
155     *microseconds = (elapsed / 1000) % 1000000;
156
157   return total;
158 }
159
160 void
161 g_usleep (gulong microseconds)
162 {
163 #ifdef G_OS_WIN32
164   Sleep (microseconds / 1000);
165 #else /* !G_OS_WIN32 */
166 # ifdef HAVE_NANOSLEEP
167   struct timespec request, remaining;
168   request.tv_sec = microseconds / G_USEC_PER_SEC;
169   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
170   while (nanosleep (&request, &remaining) == -1 && errno == EINTR)
171     request = remaining;
172 # else /* !HAVE_NANOSLEEP */
173 #  ifdef HAVE_NSLEEP
174   /* on AIX, nsleep is analogous to nanosleep */
175   struct timespec request, remaining;
176   request.tv_sec = microseconds / G_USEC_PER_SEC;
177   request.tv_nsec = 1000 * (microseconds % G_USEC_PER_SEC);
178   while (nsleep (&request, &remaining) == -1 && errno == EINTR)
179     request = remaining;
180 #  else /* !HAVE_NSLEEP */
181   if (g_thread_supported ())
182     {
183       static GStaticMutex mutex = G_STATIC_MUTEX_INIT;
184       static GCond* cond = NULL;
185       GTimeVal end_time;
186       
187       g_get_current_time (&end_time);
188       if (microseconds > G_MAXLONG)
189         {
190           microseconds -= G_MAXLONG;
191           g_time_val_add (&end_time, G_MAXLONG);
192         }
193       g_time_val_add (&end_time, microseconds);
194
195       g_static_mutex_lock (&mutex);
196       
197       if (!cond)
198         cond = g_cond_new ();
199       
200       while (g_cond_timed_wait (cond, g_static_mutex_get_mutex (&mutex), 
201                                 &end_time))
202         /* do nothing */;
203       
204       g_static_mutex_unlock (&mutex);
205     }
206   else
207     {
208       struct timeval tv;
209       tv.tv_sec = microseconds / G_USEC_PER_SEC;
210       tv.tv_usec = microseconds % G_USEC_PER_SEC;
211       select(0, NULL, NULL, NULL, &tv);
212     }
213 #  endif /* !HAVE_NSLEEP */
214 # endif /* !HAVE_NANOSLEEP */
215 #endif /* !G_OS_WIN32 */
216 }
217
218 /**
219  * g_time_val_add:
220  * @time_: a #GTimeVal
221  * @microseconds: number of microseconds to add to @time
222  *
223  * Adds the given number of microseconds to @time_. @microseconds can
224  * also be negative to decrease the value of @time_.
225  **/
226 void 
227 g_time_val_add (GTimeVal *time_, glong microseconds)
228 {
229   g_return_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC);
230
231   if (microseconds >= 0)
232     {
233       time_->tv_usec += microseconds % G_USEC_PER_SEC;
234       time_->tv_sec += microseconds / G_USEC_PER_SEC;
235       if (time_->tv_usec >= G_USEC_PER_SEC)
236        {
237          time_->tv_usec -= G_USEC_PER_SEC;
238          time_->tv_sec++;
239        }
240     }
241   else
242     {
243       microseconds *= -1;
244       time_->tv_usec -= microseconds % G_USEC_PER_SEC;
245       time_->tv_sec -= microseconds / G_USEC_PER_SEC;
246       if (time_->tv_usec < 0)
247        {
248          time_->tv_usec += G_USEC_PER_SEC;
249          time_->tv_sec--;
250        }      
251     }
252 }
253
254 /* converts a broken down date representation, relative to UTC, to
255  * a timestamp; it uses timegm() if it's available.
256  */
257 static time_t
258 mktime_utc (struct tm *tm)
259 {
260   time_t retval;
261   
262 #ifndef HAVE_TIMEGM
263   static const gint days_before[] =
264   {
265     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
266   };
267 #endif
268
269 #ifndef HAVE_TIMEGM
270   if (tm->tm_mon < 0 || tm->tm_mon > 11)
271     return (time_t) -1;
272
273   retval = (tm->tm_year - 70) * 365;
274   retval += (tm->tm_year - 68) / 4;
275   retval += days_before[tm->tm_mon] + tm->tm_mday - 1;
276   
277   if (tm->tm_year % 4 == 0 && tm->tm_mon < 2)
278     retval -= 1;
279   
280   retval = ((((retval * 24) + tm->tm_hour) * 60) + tm->tm_min) * 60 + tm->tm_sec;
281 #else
282   retval = timegm (tm);
283 #endif /* !HAVE_TIMEGM */
284   
285   return retval;
286 }
287
288 /**
289  * g_time_val_from_iso8601:
290  * @iso_date: an ISO 8601 encoded date string
291  * @time_: a #GTimeVal
292  *
293  * Converts a string containing an ISO 8601 encoded date and time
294  * to a #GTimeVal and puts it into @time_.
295  *
296  * Return value: %TRUE if the conversion was successful.
297  *
298  * Since: 2.12
299  */
300 gboolean
301 g_time_val_from_iso8601 (const gchar *iso_date,
302                          GTimeVal    *time_)
303 {
304   struct tm tm;
305   long val;
306
307   g_return_val_if_fail (iso_date != NULL, FALSE);
308   g_return_val_if_fail (time_ != NULL, FALSE);
309
310   /* Ensure that the first character is a digit,
311    * the first digit of the date, otherwise we don't
312    * have an ISO 8601 date */
313   while (g_ascii_isspace (*iso_date))
314     iso_date++;
315
316   if (*iso_date == '\0')
317     return FALSE;
318
319   if (!g_ascii_isdigit (*iso_date) && *iso_date != '-' && *iso_date != '+')
320     return FALSE;
321
322   val = strtoul (iso_date, (char **)&iso_date, 10);
323   if (*iso_date == '-')
324     {
325       /* YYYY-MM-DD */
326       tm.tm_year = val - 1900;
327       iso_date++;
328       tm.tm_mon = strtoul (iso_date, (char **)&iso_date, 10) - 1;
329       
330       if (*iso_date++ != '-')
331         return FALSE;
332       
333       tm.tm_mday = strtoul (iso_date, (char **)&iso_date, 10);
334     }
335   else
336     {
337       /* YYYYMMDD */
338       tm.tm_mday = val % 100;
339       tm.tm_mon = (val % 10000) / 100 - 1;
340       tm.tm_year = val / 10000 - 1900;
341     }
342
343   if (*iso_date++ != 'T')
344     return FALSE;
345   
346   val = strtoul (iso_date, (char **)&iso_date, 10);
347   if (*iso_date == ':')
348     {
349       /* hh:mm:ss */
350       tm.tm_hour = val;
351       iso_date++;
352       tm.tm_min = strtoul (iso_date, (char **)&iso_date, 10);
353       
354       if (*iso_date++ != ':')
355         return FALSE;
356       
357       tm.tm_sec = strtoul (iso_date, (char **)&iso_date, 10);
358     }
359   else
360     {
361       /* hhmmss */
362       tm.tm_sec = val % 100;
363       tm.tm_min = (val % 10000) / 100;
364       tm.tm_hour = val / 10000;
365     }
366
367   time_->tv_usec = 0;
368   
369   if (*iso_date == ',' || *iso_date == '.')
370     {
371       glong mul = 100000;
372
373       while (g_ascii_isdigit (*++iso_date))
374         {
375           time_->tv_usec += (*iso_date - '0') * mul;
376           mul /= 10;
377         }
378     }
379     
380   /* Now parse the offset and convert tm to a time_t */
381   if (*iso_date == 'Z')
382     {
383       iso_date++;
384       time_->tv_sec = mktime_utc (&tm);
385     }
386   else if (*iso_date == '+' || *iso_date == '-')
387     {
388       gint sign = (*iso_date == '+') ? -1 : 1;
389       
390       val = strtoul (iso_date + 1, (char **)&iso_date, 10);
391       
392       if (*iso_date == ':')
393         val = 60 * val + strtoul (iso_date + 1, (char **)&iso_date, 10);
394       else
395         val = 60 * (val / 100) + (val % 100);
396
397       time_->tv_sec = mktime_utc (&tm) + (time_t) (60 * val * sign);
398     }
399   else
400     {
401       /* No "Z" or offset, so local time */
402       time_->tv_sec = mktime (&tm);
403     }
404
405   while (g_ascii_isspace (*iso_date))
406     iso_date++;
407
408   return *iso_date == '\0';
409 }
410
411 /**
412  * g_time_val_to_iso8601:
413  * @time_: a #GTimeVal
414  * 
415  * Converts @time_ into an ISO 8601 encoded string, relative to the
416  * Coordinated Universal Time (UTC).
417  *
418  * Return value: a newly allocated string containing an ISO 8601 date
419  *
420  * Since: 2.12
421  */
422 gchar *
423 g_time_val_to_iso8601 (GTimeVal *time_)
424 {
425   gchar *retval;
426   struct tm *tm;
427 #ifdef HAVE_GMTIME_R
428   struct tm tm_;
429 #endif
430   time_t secs;
431   
432   g_return_val_if_fail (time_->tv_usec >= 0 && time_->tv_usec < G_USEC_PER_SEC, NULL);
433
434  secs = time_->tv_sec;
435 #ifdef _WIN32
436  tm = gmtime (&secs);
437 #else
438 #ifdef HAVE_GMTIME_R
439   tm = gmtime_r (&secs, &tm_);
440 #else
441   tm = gmtime (&secs);
442 #endif
443 #endif
444
445   if (time_->tv_usec != 0)
446     {
447       /* ISO 8601 date and time format, with fractionary seconds:
448        *   YYYY-MM-DDTHH:MM:SS.MMMMMMZ
449        */
450       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02d.%06ldZ",
451                                 tm->tm_year + 1900,
452                                 tm->tm_mon + 1,
453                                 tm->tm_mday,
454                                 tm->tm_hour,
455                                 tm->tm_min,
456                                 tm->tm_sec,
457                                 time_->tv_usec);
458     }
459   else
460     {
461       /* ISO 8601 date and time format:
462        *   YYYY-MM-DDTHH:MM:SSZ
463        */
464       retval = g_strdup_printf ("%4d-%02d-%02dT%02d:%02d:%02dZ",
465                                 tm->tm_year + 1900,
466                                 tm->tm_mon + 1,
467                                 tm->tm_mday,
468                                 tm->tm_hour,
469                                 tm->tm_min,
470                                 tm->tm_sec);
471     }
472   
473   return retval;
474 }
475
476 #define __G_TIMER_C__
477 #include "galiasdef.c"