2 * Copyright © 2010 Codethink Limited
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 licence, or (at your option) any later version.
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.
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.
19 * Author: Ryan Lortie <desrt@desrt.ca>
26 #include "gtimezone.h"
32 #include "gmappedfile.h"
33 #include "gtestutils.h"
34 #include "gfileutils.h"
35 #include "gstrfuncs.h"
44 * @short_description: a structure representing a time zone
45 * @see_also: #GDateTime
47 * #GTimeZone is a structure that represents a time zone, at no
48 * particular point in time. It is refcounted and immutable.
50 * A time zone contains a number of intervals. Each interval has
51 * an abbreviation to describe it, an offet to UTC and a flag indicating
52 * if the daylight savings time is in effect during that interval. A
53 * time zone always has at least one interval -- interval 0.
55 * Every UTC time is contained within exactly one interval, but a given
56 * local time may be contained within zero, one or two intervals (due to
57 * incontinuities associated with daylight savings time).
59 * An interval may refer to a specific period of time (eg: the duration
60 * of daylight savings time during 2010) or it may refer to many periods
61 * of time that share the same properties (eg: all periods of daylight
62 * savings time). It is also possible (usually for political reasons)
63 * that some properties (like the abbreviation) change between intervals
64 * without other properties changing.
66 * #GTimeZone is available since GLib 2.26.
72 * #GDateTime is an opaque structure whose members cannot be accessed
78 /* zoneinfo file format {{{1 */
81 typedef struct { gchar bytes[8]; } gint64_be;
82 typedef struct { gchar bytes[4]; } gint32_be;
83 typedef struct { gchar bytes[4]; } guint32_be;
85 static inline gint64 gint64_from_be (const gint64_be be) {
86 gint64 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT64_FROM_BE (tmp);
89 static inline gint32 gint32_from_be (const gint32_be be) {
90 gint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GINT32_FROM_BE (tmp);
93 static inline guint32 guint32_from_be (const guint32_be be) {
94 guint32 tmp; memcpy (&tmp, &be, sizeof tmp); return GUINT32_FROM_BE (tmp);
101 guchar tzh_reserved[15];
103 guint32_be tzh_ttisgmtcnt;
104 guint32_be tzh_ttisstdcnt;
105 guint32_be tzh_leapcnt;
106 guint32_be tzh_timecnt;
107 guint32_be tzh_typecnt;
108 guint32_be tzh_charcnt;
118 /* GTimeZone structure and lifecycle {{{1 */
125 const struct tzhead *header;
126 const struct ttinfo *infos;
129 const gint32_be *one;
130 const gint64_be *two;
132 const guint8 *indices;
139 G_LOCK_DEFINE_STATIC (time_zones);
140 static GHashTable/*<string?, GTimeZone>*/ *time_zones;
146 * Decreases the reference count on @tz.
151 g_time_zone_unref (GTimeZone *tz)
156 ref_count = g_atomic_int_get (&tz->ref_count);
158 g_assert (ref_count > 0);
162 if (tz->name != NULL)
166 /* someone else might have grabbed a ref in the meantime */
167 if G_UNLIKELY (g_atomic_int_get (&tz->ref_count) != 1)
169 G_UNLOCK(time_zones);
173 g_hash_table_remove (time_zones, tz->name);
174 G_UNLOCK(time_zones);
178 g_bytes_unref (tz->zoneinfo);
182 g_slice_free (GTimeZone, tz);
185 else if G_UNLIKELY (!g_atomic_int_compare_and_exchange (&tz->ref_count,
195 * Increases the reference count on @tz.
197 * Returns: a new reference to @tz.
202 g_time_zone_ref (GTimeZone *tz)
204 g_assert (tz->ref_count > 0);
206 g_atomic_int_inc (&tz->ref_count);
211 /* fake zoneinfo creation (for RFC3339/ISO 8601 timezones) {{{1 */
213 * parses strings of the form 'hh' 'hhmm' or 'hh:mm' where:
218 parse_time (const gchar *time_,
221 if (*time_ < '0' || '2' < *time_)
224 *offset = 10 * 60 * 60 * (*time_++ - '0');
226 if (*time_ < '0' || '9' < *time_)
229 *offset += 60 * 60 * (*time_++ - '0');
231 if (*offset > 23 * 60 * 60)
240 if (*time_ < '0' || '5' < *time_)
243 *offset += 10 * 60 * (*time_++ - '0');
245 if (*time_ < '0' || '9' < *time_)
248 *offset += 60 * (*time_++ - '0');
250 return *time_ == '\0';
254 parse_constant_offset (const gchar *name,
264 return parse_time (name, offset);
267 if (parse_time (name, offset))
279 zone_for_constant_offset (const gchar *name)
281 const gchar fake_zoneinfo_headers[] =
282 "TZif" "2..." "...." "...." "...."
283 "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0"
284 "TZif" "2..." "...." "...." "...."
285 "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\0" "\0\0\0\1" "\0\0\0\7";
287 struct tzhead headers[2];
293 if (name == NULL || !parse_constant_offset (name, &offset))
296 offset = GINT32_TO_BE (offset);
298 fake = g_malloc (sizeof *fake);
299 memcpy (fake, fake_zoneinfo_headers, sizeof fake_zoneinfo_headers);
300 memcpy (&fake->info.tt_gmtoff, &offset, sizeof offset);
301 fake->info.tt_isdst = FALSE;
302 fake->info.tt_abbrind = 0;
303 strcpy (fake->abbr, name);
305 return g_bytes_new_take (fake, sizeof *fake);
309 zone_info_unix (const gchar *identifier)
312 GMappedFile *file = NULL;
313 GBytes *zoneinfo = NULL;
315 /* identifier can be a relative or absolute path name;
316 if relative, it is interpreted starting from /usr/share/zoneinfo
317 while the POSIX standard says it should start with :,
318 glibc allows both syntaxes, so we should too */
319 if (identifier != NULL)
323 tzdir = getenv ("TZDIR");
325 tzdir = "/usr/share/zoneinfo";
327 if (*identifier == ':')
330 if (g_path_is_absolute (identifier))
331 filename = g_strdup (identifier);
333 filename = g_build_filename (tzdir, identifier, NULL);
336 filename = g_strdup ("/etc/localtime");
338 file = g_mapped_file_new (filename, FALSE, NULL);
341 zoneinfo = g_bytes_new_with_free_func (g_mapped_file_get_contents (file),
342 g_mapped_file_get_length (file),
343 (GDestroyNotify)g_mapped_file_unref,
344 g_mapped_file_ref (file));
345 g_mapped_file_unref (file);
352 /* Construction {{{1 */
355 * @identifier: (allow-none): a timezone identifier
357 * Creates a #GTimeZone corresponding to @identifier.
359 * @identifier can either be an RFC3339/ISO 8601 time offset or
360 * something that would pass as a valid value for the
361 * <varname>TZ</varname> environment variable (including %NULL).
363 * Valid RFC3339 time offsets are <literal>"Z"</literal> (for UTC) or
364 * <literal>"±hh:mm"</literal>. ISO 8601 additionally specifies
365 * <literal>"±hhmm"</literal> and <literal>"±hh"</literal>.
367 * The <varname>TZ</varname> environment variable typically corresponds
368 * to the name of a file in the zoneinfo database, but there are many
369 * other possibilities. Note that those other possibilities are not
370 * currently implemented, but are planned.
372 * g_time_zone_new_local() calls this function with the value of the
373 * <varname>TZ</varname> environment variable. This function itself is
374 * independent of the value of <varname>TZ</varname>, but if @identifier
375 * is %NULL then <filename>/etc/localtime</filename> will be consulted
376 * to discover the correct timezone.
379 * url='http://tools.ietf.org/html/rfc3339#section-5.6'>RFC3339
380 * §5.6</ulink> for a precise definition of valid RFC3339 time offsets
381 * (the <varname>time-offset</varname> expansion) and ISO 8601 for the
382 * full list of valid time offsets. See <ulink
383 * url='http://www.gnu.org/s/libc/manual/html_node/TZ-Variable.html'>The
384 * GNU C Library manual</ulink> for an explanation of the possible
385 * values of the <varname>TZ</varname> environment variable.
387 * You should release the return value by calling g_time_zone_unref()
388 * when you are done with it.
390 * Returns: the requested timezone
395 g_time_zone_new (const gchar *identifier)
401 if (time_zones == NULL)
402 time_zones = g_hash_table_new (g_str_hash, g_str_equal);
405 tz = g_hash_table_lookup (time_zones, identifier);
411 tz = g_slice_new0 (GTimeZone);
412 tz->name = g_strdup (identifier);
415 tz->zoneinfo = zone_for_constant_offset (identifier);
417 if (tz->zoneinfo == NULL)
418 tz->zoneinfo = zone_info_unix (identifier);
420 if (tz->zoneinfo != NULL)
423 const struct tzhead *header = g_bytes_get_data (tz->zoneinfo, &size);
425 if (size < sizeof (struct tzhead) || memcmp (header, "TZif", 4))
427 g_bytes_unref (tz->zoneinfo);
433 tz->version = header->tzh_version;
434 /* we trust the file completely. */
435 if (tz->version == '2')
436 tz->header = (const struct tzhead *)
437 (((const gchar *) (header + 1)) +
438 guint32_from_be(header->tzh_ttisgmtcnt) +
439 guint32_from_be(header->tzh_ttisstdcnt) +
440 8 * guint32_from_be(header->tzh_leapcnt) +
441 5 * guint32_from_be(header->tzh_timecnt) +
442 6 * guint32_from_be(header->tzh_typecnt) +
443 guint32_from_be(header->tzh_charcnt));
447 typecnt = guint32_from_be (tz->header->tzh_typecnt);
448 tz->timecnt = guint32_from_be (tz->header->tzh_timecnt);
449 if (tz->version == '2')
451 tz->trans.two = (gconstpointer) (tz->header + 1);
452 tz->indices = (gconstpointer) (tz->trans.two + tz->timecnt);
456 tz->trans.one = (gconstpointer) (tz->header + 1);
457 tz->indices = (gconstpointer) (tz->trans.one + tz->timecnt);
459 tz->infos = (gconstpointer) (tz->indices + tz->timecnt);
460 tz->abbrs = (gconstpointer) (tz->infos + typecnt);
465 g_hash_table_insert (time_zones, tz->name, tz);
467 g_atomic_int_inc (&tz->ref_count);
468 G_UNLOCK (time_zones);
474 * g_time_zone_new_utc:
476 * Creates a #GTimeZone corresponding to UTC.
478 * This is equivalent to calling g_time_zone_new() with a value like
479 * "Z", "UTC", "+00", etc.
481 * You should release the return value by calling g_time_zone_unref()
482 * when you are done with it.
484 * Returns: the universal timezone
489 g_time_zone_new_utc (void)
491 return g_time_zone_new ("UTC");
495 * g_time_zone_new_local:
497 * Creates a #GTimeZone corresponding to local time. The local time
498 * zone may change between invocations to this function; for example,
499 * if the system administrator changes it.
501 * This is equivalent to calling g_time_zone_new() with the value of the
502 * <varname>TZ</varname> environment variable (including the possibility
505 * You should release the return value by calling g_time_zone_unref()
506 * when you are done with it.
508 * Returns: the local timezone
513 g_time_zone_new_local (void)
515 return g_time_zone_new (getenv ("TZ"));
518 /* Internal helpers {{{1 */
519 inline static const struct ttinfo *
520 interval_info (GTimeZone *tz,
524 return tz->infos + tz->indices[interval - 1];
530 interval_start (GTimeZone *tz,
535 if (tz->version == '2')
536 return gint64_from_be (tz->trans.two[interval - 1]);
538 return gint32_from_be (tz->trans.one[interval - 1]);
544 interval_end (GTimeZone *tz,
547 if (interval < tz->timecnt)
549 if (tz->version == '2')
550 return gint64_from_be (tz->trans.two[interval]) - 1;
552 return gint32_from_be (tz->trans.one[interval]) - 1;
558 interval_offset (GTimeZone *tz,
561 return gint32_from_be (interval_info (tz, interval)->tt_gmtoff);
564 inline static gboolean
565 interval_isdst (GTimeZone *tz,
568 return interval_info (tz, interval)->tt_isdst;
572 interval_abbrind (GTimeZone *tz,
575 return interval_info (tz, interval)->tt_abbrind;
579 interval_local_start (GTimeZone *tz,
583 return interval_start (tz, interval) + interval_offset (tz, interval);
589 interval_local_end (GTimeZone *tz,
592 if (interval < tz->timecnt)
593 return interval_end (tz, interval) + interval_offset (tz, interval);
599 interval_valid (GTimeZone *tz,
602 return interval <= tz->timecnt;
605 /* g_time_zone_find_interval() {{{1 */
608 * g_time_zone_adjust_time:
610 * @type: the #GTimeType of @time_
611 * @time_: a pointer to a number of seconds since January 1, 1970
613 * Finds an interval within @tz that corresponds to the given @time_,
614 * possibly adjusting @time_ if required to fit into an interval.
615 * The meaning of @time_ depends on @type.
617 * This function is similar to g_time_zone_find_interval(), with the
618 * difference that it always succeeds (by making the adjustments
621 * In any of the cases where g_time_zone_find_interval() succeeds then
622 * this function returns the same value, without modifying @time_.
624 * This function may, however, modify @time_ in order to deal with
625 * non-existent times. If the non-existent local @time_ of 02:30 were
626 * requested on March 14th 2010 in Toronto then this function would
627 * adjust @time_ to be 03:00 and return the interval containing the
630 * Returns: the interval containing @time_, never -1
635 g_time_zone_adjust_time (GTimeZone *tz,
641 if (tz->zoneinfo == NULL)
644 /* find the interval containing *time UTC
645 * TODO: this could be binary searched (or better) */
646 for (i = 0; i < tz->timecnt; i++)
647 if (*time_ <= interval_end (tz, i))
650 g_assert (interval_start (tz, i) <= *time_ && *time_ <= interval_end (tz, i));
652 if (type != G_TIME_TYPE_UNIVERSAL)
654 if (*time_ < interval_local_start (tz, i))
655 /* if time came before the start of this interval... */
659 /* if it's not in the previous interval... */
660 if (*time_ > interval_local_end (tz, i))
662 /* it doesn't exist. fast-forward it. */
664 *time_ = interval_local_start (tz, i);
668 else if (*time_ > interval_local_end (tz, i))
669 /* if time came after the end of this interval... */
673 /* if it's not in the next interval... */
674 if (*time_ < interval_local_start (tz, i))
675 /* it doesn't exist. fast-forward it. */
676 *time_ = interval_local_start (tz, i);
679 else if (interval_isdst (tz, i) != type)
680 /* it's in this interval, but dst flag doesn't match.
681 * check neighbours for a better fit. */
683 if (i && *time_ <= interval_local_end (tz, i - 1))
686 else if (i < tz->timecnt &&
687 *time_ >= interval_local_start (tz, i + 1))
696 * g_time_zone_find_interval:
698 * @type: the #GTimeType of @time_
699 * @time_: a number of seconds since January 1, 1970
701 * Finds an the interval within @tz that corresponds to the given @time_.
702 * The meaning of @time_ depends on @type.
704 * If @type is %G_TIME_TYPE_UNIVERSAL then this function will always
705 * succeed (since universal time is monotonic and continuous).
707 * Otherwise @time_ is treated is local time. The distinction between
708 * %G_TIME_TYPE_STANDARD and %G_TIME_TYPE_DAYLIGHT is ignored except in
709 * the case that the given @time_ is ambiguous. In Toronto, for example,
710 * 01:30 on November 7th 2010 occurred twice (once inside of daylight
711 * savings time and the next, an hour later, outside of daylight savings
712 * time). In this case, the different value of @type would result in a
713 * different interval being returned.
715 * It is still possible for this function to fail. In Toronto, for
716 * example, 02:00 on March 14th 2010 does not exist (due to the leap
717 * forward to begin daylight savings time). -1 is returned in that
720 * Returns: the interval containing @time_, or -1 in case of failure
725 g_time_zone_find_interval (GTimeZone *tz,
731 if (tz->zoneinfo == NULL)
734 for (i = 0; i < tz->timecnt; i++)
735 if (time_ <= interval_end (tz, i))
738 if (type == G_TIME_TYPE_UNIVERSAL)
741 if (time_ < interval_local_start (tz, i))
743 if (time_ > interval_local_end (tz, --i))
747 else if (time_ > interval_local_end (tz, i))
749 if (time_ < interval_local_start (tz, ++i))
753 else if (interval_isdst (tz, i) != type)
755 if (i && time_ <= interval_local_end (tz, i - 1))
758 else if (i < tz->timecnt && time_ >= interval_local_start (tz, i + 1))
765 /* Public API accessors {{{1 */
768 * g_time_zone_get_abbreviation:
770 * @interval: an interval within the timezone
772 * Determines the time zone abbreviation to be used during a particular
773 * @interval of time in the time zone @tz.
775 * For example, in Toronto this is currently "EST" during the winter
776 * months and "EDT" during the summer months when daylight savings time
779 * Returns: the time zone abbreviation, which belongs to @tz
784 g_time_zone_get_abbreviation (GTimeZone *tz,
787 g_return_val_if_fail (interval_valid (tz, interval), NULL);
789 if (tz->header == NULL)
792 return tz->abbrs + interval_abbrind (tz, interval);
796 * g_time_zone_get_offset:
798 * @interval: an interval within the timezone
800 * Determines the offset to UTC in effect during a particular @interval
801 * of time in the time zone @tz.
803 * The offset is the number of seconds that you add to UTC time to
804 * arrive at local time for @tz (ie: negative numbers for time zones
805 * west of GMT, positive numbers for east).
807 * Returns: the number of seconds that should be added to UTC to get the
813 g_time_zone_get_offset (GTimeZone *tz,
816 g_return_val_if_fail (interval_valid (tz, interval), 0);
818 if (tz->header == NULL)
821 return interval_offset (tz, interval);
825 * g_time_zone_is_dst:
827 * @interval: an interval within the timezone
829 * Determines if daylight savings time is in effect during a particular
830 * @interval of time in the time zone @tz.
832 * Returns: %TRUE if daylight savings time is in effect
837 g_time_zone_is_dst (GTimeZone *tz,
840 g_return_val_if_fail (interval_valid (tz, interval), FALSE);
842 if (tz->header == NULL)
845 return interval_isdst (tz, interval);
849 /* vim:set foldmethod=marker: */