Fix a memory leak. (#94550, Sebastian Rittau)
[platform/upstream/glib.git] / glib / gdate.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 #define DEBUG_MSG(x)    /* */
32 #ifdef G_ENABLE_DEBUG
33 /* #define DEBUG_MSG(args)      g_message args ; */
34 #endif
35
36 #ifdef HAVE_CONFIG_H
37 #include <config.h>
38 #endif
39
40 #include "glib.h"
41
42 #include <time.h>
43 #include <string.h>
44 #include <stdlib.h>
45 #include <locale.h>
46
47 GDate*
48 g_date_new ()
49 {
50   GDate *d = g_new0 (GDate, 1); /* happily, 0 is the invalid flag for everything. */
51   
52   return d;
53 }
54
55 GDate*
56 g_date_new_dmy (GDateDay day, GDateMonth m, GDateYear y)
57 {
58   GDate *d;
59   g_return_val_if_fail (g_date_valid_dmy (day, m, y), NULL);
60   
61   d = g_new (GDate, 1);
62   
63   d->julian = FALSE;
64   d->dmy    = TRUE;
65   
66   d->month = m;
67   d->day   = day;
68   d->year  = y;
69   
70   g_assert (g_date_valid (d));
71   
72   return d;
73 }
74
75 GDate*
76 g_date_new_julian (guint32 j)
77 {
78   GDate *d;
79   g_return_val_if_fail (g_date_valid_julian (j), NULL);
80   
81   d = g_new (GDate, 1);
82   
83   d->julian = TRUE;
84   d->dmy    = FALSE;
85   
86   d->julian_days = j;
87   
88   g_assert (g_date_valid (d));
89   
90   return d;
91 }
92
93 void
94 g_date_free (GDate *d)
95 {
96   g_return_if_fail (d != NULL);
97   
98   g_free (d);
99 }
100
101 gboolean     
102 g_date_valid (const GDate *d)
103 {
104   g_return_val_if_fail (d != NULL, FALSE);
105   
106   return (d->julian || d->dmy);
107 }
108
109 static const guint8 days_in_months[2][13] = 
110 {  /* error, jan feb mar apr may jun jul aug sep oct nov dec */
111   {  0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, 
112   {  0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } /* leap year */
113 };
114
115 static const guint16 days_in_year[2][14] = 
116 {  /* 0, jan feb mar apr may  jun  jul  aug  sep  oct  nov  dec */
117   {  0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 }, 
118   {  0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
119 };
120
121 gboolean     
122 g_date_valid_month (GDateMonth   m)
123
124   return ( (m > G_DATE_BAD_MONTH) && (m < 13) );
125 }
126
127 gboolean     
128 g_date_valid_year (GDateYear    y)
129 {
130   return ( y > G_DATE_BAD_YEAR );
131 }
132
133 gboolean     
134 g_date_valid_day (GDateDay     d)
135 {
136   return ( (d > G_DATE_BAD_DAY) && (d < 32) );
137 }
138
139 gboolean     
140 g_date_valid_weekday (GDateWeekday w)
141 {
142   return ( (w > G_DATE_BAD_WEEKDAY) && (w < 8) );
143 }
144
145 gboolean     
146 g_date_valid_julian (guint32      j)
147 {
148   return (j > G_DATE_BAD_JULIAN);
149 }
150
151 gboolean     
152 g_date_valid_dmy (GDateDay     d, 
153                   GDateMonth   m, 
154                   GDateYear    y)
155 {
156   return ( (m > G_DATE_BAD_MONTH) &&
157            (m < 13)               && 
158            (d > G_DATE_BAD_DAY)   && 
159            (y > G_DATE_BAD_YEAR)  &&   /* must check before using g_date_is_leap_year */
160            (d <=  (g_date_is_leap_year (y) ? 
161                    days_in_months[1][m] : days_in_months[0][m])) );
162 }
163
164
165 /* "Julian days" just means an absolute number of days, where Day 1 ==
166  *   Jan 1, Year 1
167  */
168 static void
169 g_date_update_julian (const GDate *const_d)
170 {
171   GDate *d = (GDate *) const_d;
172   GDateYear year;
173   gint index;
174   
175   g_return_if_fail (d != NULL);
176   g_return_if_fail (d->dmy);
177   g_return_if_fail (!d->julian);
178   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
179   
180   /* What we actually do is: multiply years * 365 days in the year,
181    *  add the number of years divided by 4, subtract the number of
182    *  years divided by 100 and add the number of years divided by 400,
183    *  which accounts for leap year stuff. Code from Steffen Beyer's
184    *  DateCalc. 
185    */
186   
187   year = d->year - 1; /* we know d->year > 0 since it's valid */
188   
189   d->julian_days = year * 365U;
190   d->julian_days += (year >>= 2); /* divide by 4 and add */
191   d->julian_days -= (year /= 25); /* divides original # years by 100 */
192   d->julian_days += year >> 2;    /* divides by 4, which divides original by 400 */
193   
194   index = g_date_is_leap_year (d->year) ? 1 : 0;
195   
196   d->julian_days += days_in_year[index][d->month] + d->day;
197   
198   g_return_if_fail (g_date_valid_julian (d->julian_days));
199   
200   d->julian = TRUE;
201 }
202
203 static void 
204 g_date_update_dmy (const GDate *const_d)
205 {
206   GDate *d = (GDate *) const_d;
207   GDateYear y;
208   GDateMonth m;
209   GDateDay day;
210   
211   guint32 A, B, C, D, E, M;
212   
213   g_return_if_fail (d != NULL);
214   g_return_if_fail (d->julian);
215   g_return_if_fail (!d->dmy);
216   g_return_if_fail (g_date_valid_julian (d->julian_days));
217   
218   /* Formula taken from the Calendar FAQ; the formula was for the
219    *  Julian Period which starts on 1 January 4713 BC, so we add
220    *  1,721,425 to the number of days before doing the formula.
221    *
222    * I'm sure this can be simplified for our 1 January 1 AD period
223    * start, but I can't figure out how to unpack the formula.  
224    */
225   
226   A = d->julian_days + 1721425 + 32045;
227   B = ( 4 *(A + 36524) )/ 146097 - 1;
228   C = A - (146097 * B)/4;
229   D = ( 4 * (C + 365) ) / 1461 - 1;
230   E = C - ((1461*D) / 4);
231   M = (5 * (E - 1) + 2)/153;
232   
233   m = M + 3 - (12*(M/10));
234   day = E - (153*M + 2)/5;
235   y = 100 * B + D - 4800 + (M/10);
236   
237 #ifdef G_ENABLE_DEBUG
238   if (!g_date_valid_dmy (day, m, y)) 
239     {
240       g_warning ("\nOOPS julian: %u  computed dmy: %u %u %u\n", 
241                  d->julian_days, day, m, y);
242     }
243 #endif
244   
245   d->month = m;
246   d->day   = day;
247   d->year  = y;
248   
249   d->dmy = TRUE;
250 }
251
252 GDateWeekday 
253 g_date_get_weekday (const GDate *d)
254 {
255   g_return_val_if_fail (d != NULL, G_DATE_BAD_WEEKDAY);
256   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_WEEKDAY);
257   
258   if (!d->julian) 
259     {
260       g_date_update_julian (d);
261     }
262   g_return_val_if_fail (d->julian, G_DATE_BAD_WEEKDAY);
263   
264   return ((d->julian_days - 1) % 7) + 1;
265 }
266
267 GDateMonth   
268 g_date_get_month (const GDate *d)
269 {
270   g_return_val_if_fail (d != NULL, G_DATE_BAD_MONTH);
271   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_MONTH);
272   
273   if (!d->dmy) 
274     {
275       g_date_update_dmy (d);
276     }
277   g_return_val_if_fail (d->dmy, G_DATE_BAD_MONTH);
278   
279   return d->month;
280 }
281
282 GDateYear    
283 g_date_get_year (const GDate *d)
284 {
285   g_return_val_if_fail (d != NULL, G_DATE_BAD_YEAR);
286   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_YEAR);
287   
288   if (!d->dmy) 
289     {
290       g_date_update_dmy (d);
291     }
292   g_return_val_if_fail (d->dmy, G_DATE_BAD_YEAR);  
293   
294   return d->year;
295 }
296
297 GDateDay     
298 g_date_get_day (const GDate *d)
299 {
300   g_return_val_if_fail (d != NULL, G_DATE_BAD_DAY);
301   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_DAY);
302   
303   if (!d->dmy) 
304     {
305       g_date_update_dmy (d);
306     }
307   g_return_val_if_fail (d->dmy, G_DATE_BAD_DAY);  
308   
309   return d->day;
310 }
311
312 guint32      
313 g_date_get_julian (const GDate *d)
314 {
315   g_return_val_if_fail (d != NULL, G_DATE_BAD_JULIAN);
316   g_return_val_if_fail (g_date_valid (d), G_DATE_BAD_JULIAN);
317   
318   if (!d->julian) 
319     {
320       g_date_update_julian (d);
321     }
322   g_return_val_if_fail (d->julian, G_DATE_BAD_JULIAN);  
323   
324   return d->julian_days;
325 }
326
327 guint        
328 g_date_get_day_of_year (const GDate *d)
329 {
330   gint index;
331   
332   g_return_val_if_fail (d != NULL, 0);
333   g_return_val_if_fail (g_date_valid (d), 0);
334   
335   if (!d->dmy) 
336     {
337       g_date_update_dmy (d);
338     }
339   g_return_val_if_fail (d->dmy, 0);  
340   
341   index = g_date_is_leap_year (d->year) ? 1 : 0;
342   
343   return (days_in_year[index][d->month] + d->day);
344 }
345
346 guint        
347 g_date_get_monday_week_of_year (const GDate *d)
348 {
349   GDateWeekday wd;
350   guint day;
351   GDate first;
352   
353   g_return_val_if_fail (d != NULL, 0);
354   g_return_val_if_fail (g_date_valid (d), 0);
355   
356   if (!d->dmy) 
357     {
358       g_date_update_dmy (d);
359     }
360   g_return_val_if_fail (d->dmy, 0);  
361   
362   g_date_clear (&first, 1);
363   
364   g_date_set_dmy (&first, 1, 1, d->year);
365   
366   wd = g_date_get_weekday (&first) - 1; /* make Monday day 0 */
367   day = g_date_get_day_of_year (d) - 1;
368   
369   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
370 }
371
372 guint        
373 g_date_get_sunday_week_of_year (const GDate *d)
374 {
375   GDateWeekday wd;
376   guint day;
377   GDate first;
378   
379   g_return_val_if_fail (d != NULL, 0);
380   g_return_val_if_fail (g_date_valid (d), 0);
381   
382   if (!d->dmy) 
383     {
384       g_date_update_dmy (d);
385     }
386   g_return_val_if_fail (d->dmy, 0);  
387   
388   g_date_clear (&first, 1);
389   
390   g_date_set_dmy (&first, 1, 1, d->year);
391   
392   wd = g_date_get_weekday (&first);
393   if (wd == 7) wd = 0; /* make Sunday day 0 */
394   day = g_date_get_day_of_year (d) - 1;
395   
396   return ((day + wd)/7U + (wd == 0 ? 1 : 0));
397 }
398
399 gint
400 g_date_days_between (const GDate *d1,
401                      const GDate *d2)
402 {
403   g_return_val_if_fail (d1 != NULL, 0);
404   g_return_val_if_fail (d2 != NULL, 0);
405
406   g_return_val_if_fail (g_date_valid (d1), 0);
407   g_return_val_if_fail (g_date_valid (d2), 0);
408
409   return (gint)g_date_get_julian (d2) - (gint)g_date_get_julian (d1);
410 }
411
412 void         
413 g_date_clear (GDate       *d, guint ndates)
414 {
415   g_return_if_fail (d != NULL);
416   g_return_if_fail (ndates != 0);
417   
418   memset (d, 0x0, ndates*sizeof (GDate)); 
419 }
420
421 G_LOCK_DEFINE_STATIC (g_date_global);
422
423 /* These are for the parser, output to the user should use *
424  * g_date_strftime () - this creates more never-freed memory to annoy
425  * all those memory debugger users. :-) 
426  */
427
428 static gchar *long_month_names[13] = 
429
430   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
431 };
432
433 static gchar *short_month_names[13] = 
434 {
435   "Error", NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL 
436 };
437
438 /* This tells us if we need to update the parse info */
439 static gchar *current_locale = NULL;
440
441 /* order of these in the current locale */
442 static GDateDMY dmy_order[3] = 
443 {
444    G_DATE_DAY, G_DATE_MONTH, G_DATE_YEAR
445 };
446
447 /* Where to chop two-digit years: i.e., for the 1930 default, numbers
448  * 29 and below are counted as in the year 2000, numbers 30 and above
449  * are counted as in the year 1900.  
450  */
451
452 static GDateYear twodigit_start_year = 1930;
453
454 /* It is impossible to enter a year between 1 AD and 99 AD with this
455  * in effect.  
456  */
457 static gboolean using_twodigit_years = FALSE;
458
459 struct _GDateParseTokens {
460   gint num_ints;
461   gint n[3];
462   guint month;
463 };
464
465 typedef struct _GDateParseTokens GDateParseTokens;
466
467 #define NUM_LEN 10
468
469 /* HOLDS: g_date_global_lock */
470 static void
471 g_date_fill_parse_tokens (const gchar *str, GDateParseTokens *pt)
472 {
473   gchar num[4][NUM_LEN+1];
474   gint i;
475   const guchar *s;
476   
477   /* We count 4, but store 3; so we can give an error
478    * if there are 4.
479    */
480   num[0][0] = num[1][0] = num[2][0] = num[3][0] = '\0';
481   
482   s = (const guchar *) str;
483   pt->num_ints = 0;
484   while (*s && pt->num_ints < 4) 
485     {
486       
487       i = 0;
488       while (*s && g_ascii_isdigit (*s) && i <= NUM_LEN)
489         {
490           num[pt->num_ints][i] = *s;
491           ++s; 
492           ++i;
493         }
494       
495       if (i > 0) 
496         {
497           num[pt->num_ints][i] = '\0';
498           ++(pt->num_ints);
499         }
500       
501       if (*s == '\0') break;
502       
503       ++s;
504     }
505   
506   pt->n[0] = pt->num_ints > 0 ? atoi (num[0]) : 0;
507   pt->n[1] = pt->num_ints > 1 ? atoi (num[1]) : 0;
508   pt->n[2] = pt->num_ints > 2 ? atoi (num[2]) : 0;
509   
510   pt->month = G_DATE_BAD_MONTH;
511   
512   if (pt->num_ints < 3)
513     {
514       gchar *casefold;
515       gchar *normalized;
516       
517       casefold = g_utf8_casefold (str, -1);
518       normalized = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
519       g_free (casefold);
520
521       i = 1;
522       while (i < 13)
523         {
524           if (long_month_names[i] != NULL) 
525             {
526               const gchar *found = strstr (normalized, long_month_names[i]);
527               
528               if (found != NULL)
529                 {
530                   pt->month = i;
531                   break;
532                 }
533             }
534           
535           if (short_month_names[i] != NULL) 
536             {
537               const gchar *found = strstr (normalized, short_month_names[i]);
538               
539               if (found != NULL)
540                 {
541                   pt->month = i;
542                   break;
543                 }
544             }
545
546           ++i;
547         }
548
549       g_free (normalized);
550     }
551 }
552
553 /* HOLDS: g_date_global_lock */
554 static void
555 g_date_prepare_to_parse (const gchar *str, GDateParseTokens *pt)
556 {
557   const gchar *locale = setlocale (LC_TIME, NULL);
558   gboolean recompute_localeinfo = FALSE;
559   GDate d;
560   
561   g_return_if_fail (locale != NULL); /* should not happen */
562   
563   g_date_clear (&d, 1);              /* clear for scratch use */
564   
565   if ( (current_locale == NULL) || (strcmp (locale, current_locale) != 0) ) 
566     {
567       recompute_localeinfo = TRUE;  /* Uh, there used to be a reason for the temporary */
568     }
569   
570   if (recompute_localeinfo)
571     {
572       int i = 1;
573       GDateParseTokens testpt;
574       gchar buf[128];
575       
576       g_free (current_locale); /* still works if current_locale == NULL */
577       
578       current_locale = g_strdup (locale);
579       
580       while (i < 13) 
581         {
582           gchar *casefold;
583           
584           g_date_set_dmy (&d, 1, i, 1);
585           
586           g_return_if_fail (g_date_valid (&d));
587           
588           g_date_strftime (buf, 127, "%b", &d);
589
590           casefold = g_utf8_casefold (buf, -1);
591           g_free (short_month_names[i]);
592           short_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
593           g_free (casefold);
594           
595           g_date_strftime (buf, 127, "%B", &d);
596           casefold = g_utf8_casefold (buf, -1);
597           g_free (long_month_names[i]);
598           long_month_names[i] = g_utf8_normalize (casefold, -1, G_NORMALIZE_ALL);
599           g_free (casefold);
600           
601           ++i;
602         }
603       
604       /* Determine DMY order */
605       
606       /* had to pick a random day - don't change this, some strftimes
607        * are broken on some days, and this one is good so far. */
608       g_date_set_dmy (&d, 4, 7, 1976);
609       
610       g_date_strftime (buf, 127, "%x", &d);
611       
612       g_date_fill_parse_tokens (buf, &testpt);
613       
614       i = 0;
615       while (i < testpt.num_ints)
616         {
617           switch (testpt.n[i])
618             {
619             case 7:
620               dmy_order[i] = G_DATE_MONTH;
621               break;
622             case 4:
623               dmy_order[i] = G_DATE_DAY;
624               break;
625             case 76:
626               using_twodigit_years = TRUE; /* FALL THRU */
627             case 1976:
628               dmy_order[i] = G_DATE_YEAR;
629               break;
630             default:
631               /* leave it unchanged */
632               break;
633             }
634           ++i;
635         }
636       
637 #ifdef G_ENABLE_DEBUG
638       DEBUG_MSG (("**GDate prepared a new set of locale-specific parse rules."));
639       i = 1;
640       while (i < 13) 
641         {
642           DEBUG_MSG (("  %s   %s", long_month_names[i], short_month_names[i]));
643           ++i;
644         }
645       if (using_twodigit_years)
646         DEBUG_MSG (("**Using twodigit years with cutoff year: %u", twodigit_start_year));
647       { 
648         gchar *strings[3];
649         i = 0;
650         while (i < 3)
651           {
652             switch (dmy_order[i])
653               {
654               case G_DATE_MONTH:
655                 strings[i] = "Month";
656                 break;
657               case G_DATE_YEAR:
658                 strings[i] = "Year";
659                 break;
660               case G_DATE_DAY:
661                 strings[i] = "Day";
662                 break;
663               default:
664                 strings[i] = NULL;
665                 break;
666               }
667             ++i;
668           }
669         DEBUG_MSG (("**Order: %s, %s, %s", strings[0], strings[1], strings[2]));
670         DEBUG_MSG (("**Sample date in this locale: `%s'", buf));
671       }
672 #endif
673     }
674   
675   g_date_fill_parse_tokens (str, pt);
676 }
677
678 void         
679 g_date_set_parse (GDate       *d, 
680                   const gchar *str)
681 {
682   GDateParseTokens pt;
683   guint m = G_DATE_BAD_MONTH, day = G_DATE_BAD_DAY, y = G_DATE_BAD_YEAR;
684   
685   g_return_if_fail (d != NULL);
686   
687   /* set invalid */
688   g_date_clear (d, 1);
689   
690   G_LOCK (g_date_global);
691
692   g_date_prepare_to_parse (str, &pt);
693   
694   DEBUG_MSG (("Found %d ints, `%d' `%d' `%d' and written out month %d", 
695               pt.num_ints, pt.n[0], pt.n[1], pt.n[2], pt.month));
696   
697   
698   if (pt.num_ints == 4) 
699     {
700       G_UNLOCK (g_date_global);
701       return; /* presumably a typo; bail out. */
702     }
703   
704   if (pt.num_ints > 1)
705     {
706       int i = 0;
707       int j = 0;
708       
709       g_assert (pt.num_ints < 4); /* i.e., it is 2 or 3 */
710       
711       while (i < pt.num_ints && j < 3) 
712         {
713           switch (dmy_order[j])
714             {
715             case G_DATE_MONTH:
716             {
717               if (pt.num_ints == 2 && pt.month != G_DATE_BAD_MONTH)
718                 {
719                   m = pt.month;
720                   ++j;      /* skip months, but don't skip this number */
721                   continue;
722                 }
723               else 
724                 m = pt.n[i];
725             }
726             break;
727             case G_DATE_DAY:
728             {
729               if (pt.num_ints == 2 && pt.month == G_DATE_BAD_MONTH)
730                 {
731                   day = 1;
732                   ++j;      /* skip days, since we may have month/year */
733                   continue;
734                 }
735               day = pt.n[i];
736             }
737             break;
738             case G_DATE_YEAR:
739             {
740               y  = pt.n[i];
741               
742               if (using_twodigit_years && y < 100)
743                 {
744                   guint two     =  twodigit_start_year % 100;
745                   guint century = (twodigit_start_year / 100) * 100;
746                   
747                   if (y < two)
748                     century += 100;
749                   
750                   y += century;
751                 }
752             }
753             break;
754             default:
755               break;
756             }
757           
758           ++i;
759           ++j;
760         }
761       
762       
763       if (pt.num_ints == 3 && !g_date_valid_dmy (day, m, y))
764         {
765           /* Try YYYY MM DD */
766           y   = pt.n[0];
767           m   = pt.n[1];
768           day = pt.n[2];
769           
770           if (using_twodigit_years && y < 100) 
771             y = G_DATE_BAD_YEAR; /* avoids ambiguity */
772         }
773       else if (pt.num_ints == 2)
774         {
775           if (m == G_DATE_BAD_MONTH && pt.month != G_DATE_BAD_MONTH)
776             {
777               m = pt.month;
778             }
779         }
780     }
781   else if (pt.num_ints == 1) 
782     {
783       if (pt.month != G_DATE_BAD_MONTH)
784         {
785           /* Month name and year? */
786           m    = pt.month;
787           day  = 1;
788           y = pt.n[0];
789         }
790       else
791         {
792           /* Try yyyymmdd and yymmdd */
793           
794           m   = (pt.n[0]/100) % 100;
795           day = pt.n[0] % 100;
796           y   = pt.n[0]/10000;
797           
798           /* FIXME move this into a separate function */
799           if (using_twodigit_years && y < 100)
800             {
801               guint two     =  twodigit_start_year % 100;
802               guint century = (twodigit_start_year / 100) * 100;
803               
804               if (y < two)
805                 century += 100;
806               
807               y += century;
808             }
809         }
810     }
811   
812   /* See if we got anything valid out of all this. */
813   /* y < 8000 is to catch 19998 style typos; the library is OK up to 65535 or so */
814   if (y < 8000 && g_date_valid_dmy (day, m, y)) 
815     {
816       d->month = m;
817       d->day   = day;
818       d->year  = y;
819       d->dmy   = TRUE;
820     }
821 #ifdef G_ENABLE_DEBUG
822   else 
823     DEBUG_MSG (("Rejected DMY %u %u %u", day, m, y));
824 #endif
825   G_UNLOCK (g_date_global);
826 }
827
828 void         
829 g_date_set_time (GDate *d,
830                  GTime  time)
831 {
832   time_t t = time;
833   struct tm tm;
834   
835   g_return_if_fail (d != NULL);
836   
837 #ifdef HAVE_LOCALTIME_R
838   localtime_r (&t, &tm);
839 #else
840   {
841     struct tm *ptm = localtime (&t);
842     g_assert (ptm);
843     memcpy ((void *) &tm, (void *) ptm, sizeof(struct tm));
844   }
845 #endif
846   
847   d->julian = FALSE;
848   
849   d->month = tm.tm_mon + 1;
850   d->day   = tm.tm_mday;
851   d->year  = tm.tm_year + 1900;
852   
853   g_return_if_fail (g_date_valid_dmy (d->day, d->month, d->year));
854   
855   d->dmy    = TRUE;
856 }
857
858 void         
859 g_date_set_month (GDate     *d, 
860                   GDateMonth m)
861 {
862   g_return_if_fail (d != NULL);
863   g_return_if_fail (g_date_valid_month (m));
864
865   if (d->julian && !d->dmy) g_date_update_dmy(d);
866   d->julian = FALSE;
867   
868   d->month = m;
869   
870   if (g_date_valid_dmy (d->day, d->month, d->year))
871     d->dmy = TRUE;
872   else 
873     d->dmy = FALSE;
874 }
875
876 void         
877 g_date_set_day (GDate     *d, 
878                 GDateDay day)
879 {
880   g_return_if_fail (d != NULL);
881   g_return_if_fail (g_date_valid_day (day));
882   
883   if (d->julian && !d->dmy) g_date_update_dmy(d);
884   d->julian = FALSE;
885   
886   d->day = day;
887   
888   if (g_date_valid_dmy (d->day, d->month, d->year))
889     d->dmy = TRUE;
890   else 
891     d->dmy = FALSE;
892 }
893
894 void         
895 g_date_set_year (GDate     *d, 
896                  GDateYear  y)
897 {
898   g_return_if_fail (d != NULL);
899   g_return_if_fail (g_date_valid_year (y));
900   
901   if (d->julian && !d->dmy) g_date_update_dmy(d);
902   d->julian = FALSE;
903   
904   d->year = y;
905   
906   if (g_date_valid_dmy (d->day, d->month, d->year))
907     d->dmy = TRUE;
908   else 
909     d->dmy = FALSE;
910 }
911
912 void         
913 g_date_set_dmy (GDate     *d, 
914                 GDateDay   day, 
915                 GDateMonth m, 
916                 GDateYear  y)
917 {
918   g_return_if_fail (d != NULL);
919   g_return_if_fail (g_date_valid_dmy (day, m, y));
920   
921   d->julian = FALSE;
922   
923   d->month = m;
924   d->day   = day;
925   d->year  = y;
926   
927   d->dmy = TRUE;
928 }
929
930 void         
931 g_date_set_julian (GDate *d, guint32 j)
932 {
933   g_return_if_fail (d != NULL);
934   g_return_if_fail (g_date_valid_julian (j));
935   
936   d->julian_days = j;
937   d->julian = TRUE;
938   d->dmy = FALSE;
939 }
940
941
942 gboolean     
943 g_date_is_first_of_month (const GDate *d)
944 {
945   g_return_val_if_fail (d != NULL, FALSE);
946   g_return_val_if_fail (g_date_valid (d), FALSE);
947   
948   if (!d->dmy) 
949     {
950       g_date_update_dmy (d);
951     }
952   g_return_val_if_fail (d->dmy, FALSE);  
953   
954   if (d->day == 1) return TRUE;
955   else return FALSE;
956 }
957
958 gboolean     
959 g_date_is_last_of_month (const GDate *d)
960 {
961   gint index;
962   
963   g_return_val_if_fail (d != NULL, FALSE);
964   g_return_val_if_fail (g_date_valid (d), FALSE);
965   
966   if (!d->dmy) 
967     {
968       g_date_update_dmy (d);
969     }
970   g_return_val_if_fail (d->dmy, FALSE);  
971   
972   index = g_date_is_leap_year (d->year) ? 1 : 0;
973   
974   if (d->day == days_in_months[index][d->month]) return TRUE;
975   else return FALSE;
976 }
977
978 void         
979 g_date_add_days (GDate *d, guint ndays)
980 {
981   g_return_if_fail (d != NULL);
982   g_return_if_fail (g_date_valid (d));
983   
984   if (!d->julian)
985     {
986       g_date_update_julian (d);
987     }
988   g_return_if_fail (d->julian);
989   
990   d->julian_days += ndays;
991   d->dmy = FALSE;
992 }
993
994 void         
995 g_date_subtract_days (GDate *d, guint ndays)
996 {
997   g_return_if_fail (d != NULL);
998   g_return_if_fail (g_date_valid (d));
999   
1000   if (!d->julian)
1001     {
1002       g_date_update_julian (d);
1003     }
1004   g_return_if_fail (d->julian);
1005   g_return_if_fail (d->julian_days > ndays);
1006   
1007   d->julian_days -= ndays;
1008   d->dmy = FALSE;
1009 }
1010
1011 void         
1012 g_date_add_months (GDate       *d, 
1013                    guint        nmonths)
1014 {
1015   guint years, months;
1016   gint index;
1017   
1018   g_return_if_fail (d != NULL);
1019   g_return_if_fail (g_date_valid (d));
1020   
1021   if (!d->dmy) 
1022     {
1023       g_date_update_dmy (d);
1024     }
1025   g_return_if_fail (d->dmy);  
1026   
1027   nmonths += d->month - 1;
1028   
1029   years  = nmonths/12;
1030   months = nmonths%12;
1031   
1032   d->month = months + 1;
1033   d->year  += years;
1034   
1035   index = g_date_is_leap_year (d->year) ? 1 : 0;
1036   
1037   if (d->day > days_in_months[index][d->month])
1038     d->day = days_in_months[index][d->month];
1039   
1040   d->julian = FALSE;
1041   
1042   g_return_if_fail (g_date_valid (d));
1043 }
1044
1045 void         
1046 g_date_subtract_months (GDate       *d, 
1047                         guint        nmonths)
1048 {
1049   guint years, months;
1050   gint index;
1051   
1052   g_return_if_fail (d != NULL);
1053   g_return_if_fail (g_date_valid (d));
1054   
1055   if (!d->dmy) 
1056     {
1057       g_date_update_dmy (d);
1058     }
1059   g_return_if_fail (d->dmy);  
1060   
1061   years  = nmonths/12;
1062   months = nmonths%12;
1063   
1064   g_return_if_fail (d->year > years);
1065   
1066   d->year  -= years;
1067   
1068   if (d->month > months) d->month -= months;
1069   else 
1070     {
1071       months -= d->month;
1072       d->month = 12 - months;
1073       d->year -= 1;
1074     }
1075   
1076   index = g_date_is_leap_year (d->year) ? 1 : 0;
1077   
1078   if (d->day > days_in_months[index][d->month])
1079     d->day = days_in_months[index][d->month];
1080   
1081   d->julian = FALSE;
1082   
1083   g_return_if_fail (g_date_valid (d));
1084 }
1085
1086 void         
1087 g_date_add_years (GDate       *d, 
1088                   guint        nyears)
1089 {
1090   g_return_if_fail (d != NULL);
1091   g_return_if_fail (g_date_valid (d));
1092   
1093   if (!d->dmy) 
1094     {
1095       g_date_update_dmy (d);
1096     }
1097   g_return_if_fail (d->dmy);  
1098   
1099   d->year += nyears;
1100   
1101   if (d->month == 2 && d->day == 29)
1102     {
1103       if (!g_date_is_leap_year (d->year))
1104         {
1105           d->day = 28;
1106         }
1107     }
1108   
1109   d->julian = FALSE;
1110 }
1111
1112 void         
1113 g_date_subtract_years (GDate       *d, 
1114                        guint        nyears)
1115 {
1116   g_return_if_fail (d != NULL);
1117   g_return_if_fail (g_date_valid (d));
1118   
1119   if (!d->dmy) 
1120     {
1121       g_date_update_dmy (d);
1122     }
1123   g_return_if_fail (d->dmy);  
1124   g_return_if_fail (d->year > nyears);
1125   
1126   d->year -= nyears;
1127   
1128   if (d->month == 2 && d->day == 29)
1129     {
1130       if (!g_date_is_leap_year (d->year))
1131         {
1132           d->day = 28;
1133         }
1134     }
1135   
1136   d->julian = FALSE;
1137 }
1138
1139
1140 gboolean     
1141 g_date_is_leap_year (GDateYear  year)
1142 {
1143   g_return_val_if_fail (g_date_valid_year (year), FALSE);
1144   
1145   return ( (((year % 4) == 0) && ((year % 100) != 0)) ||
1146            (year % 400) == 0 );
1147 }
1148
1149 guint8         
1150 g_date_get_days_in_month (GDateMonth month, 
1151                           GDateYear  year)
1152 {
1153   gint index;
1154   
1155   g_return_val_if_fail (g_date_valid_year (year), 0);
1156   g_return_val_if_fail (g_date_valid_month (month), 0);
1157   
1158   index = g_date_is_leap_year (year) ? 1 : 0;
1159   
1160   return days_in_months[index][month];
1161 }
1162
1163 guint8       
1164 g_date_get_monday_weeks_in_year (GDateYear  year)
1165 {
1166   GDate d;
1167   
1168   g_return_val_if_fail (g_date_valid_year (year), 0);
1169   
1170   g_date_clear (&d, 1);
1171   g_date_set_dmy (&d, 1, 1, year);
1172   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1173   g_date_set_dmy (&d, 31, 12, year);
1174   if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1175   if (g_date_is_leap_year (year)) 
1176     {
1177       g_date_set_dmy (&d, 2, 1, year);
1178       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1179       g_date_set_dmy (&d, 30, 12, year);
1180       if (g_date_get_weekday (&d) == G_DATE_MONDAY) return 53;
1181     }
1182   return 52;
1183 }
1184
1185 guint8       
1186 g_date_get_sunday_weeks_in_year (GDateYear  year)
1187 {
1188   GDate d;
1189   
1190   g_return_val_if_fail (g_date_valid_year (year), 0);
1191   
1192   g_date_clear (&d, 1);
1193   g_date_set_dmy (&d, 1, 1, year);
1194   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1195   g_date_set_dmy (&d, 31, 12, year);
1196   if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1197   if (g_date_is_leap_year (year)) 
1198     {
1199       g_date_set_dmy (&d, 2, 1, year);
1200       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1201       g_date_set_dmy (&d, 30, 12, year);
1202       if (g_date_get_weekday (&d) == G_DATE_SUNDAY) return 53;
1203     }
1204   return 52;
1205 }
1206
1207 gint         
1208 g_date_compare (const GDate *lhs, 
1209                 const GDate *rhs)
1210 {
1211   g_return_val_if_fail (lhs != NULL, 0);
1212   g_return_val_if_fail (rhs != NULL, 0);
1213   g_return_val_if_fail (g_date_valid (lhs), 0);
1214   g_return_val_if_fail (g_date_valid (rhs), 0);
1215   
1216   /* Remember the self-comparison case! I think it works right now. */
1217   
1218   while (TRUE)
1219     {
1220       
1221       if (lhs->julian && rhs->julian) 
1222         {
1223           if (lhs->julian_days < rhs->julian_days) return -1;
1224           else if (lhs->julian_days > rhs->julian_days) return 1;
1225           else                                          return 0;
1226         }
1227       else if (lhs->dmy && rhs->dmy) 
1228         {
1229           if (lhs->year < rhs->year)               return -1;
1230           else if (lhs->year > rhs->year)               return 1;
1231           else 
1232             {
1233               if (lhs->month < rhs->month)         return -1;
1234               else if (lhs->month > rhs->month)         return 1;
1235               else 
1236                 {
1237                   if (lhs->day < rhs->day)              return -1;
1238                   else if (lhs->day > rhs->day)              return 1;
1239                   else                                       return 0;
1240                 }
1241               
1242             }
1243           
1244         }
1245       else
1246         {
1247           if (!lhs->julian) g_date_update_julian (lhs);
1248           if (!rhs->julian) g_date_update_julian (rhs);
1249           g_return_val_if_fail (lhs->julian, 0);
1250           g_return_val_if_fail (rhs->julian, 0);
1251         }
1252       
1253     }
1254   return 0; /* warnings */
1255 }
1256
1257
1258 void        
1259 g_date_to_struct_tm (const GDate *d, 
1260                      struct tm   *tm)
1261 {
1262   GDateWeekday day;
1263      
1264   g_return_if_fail (d != NULL);
1265   g_return_if_fail (g_date_valid (d));
1266   g_return_if_fail (tm != NULL);
1267   
1268   if (!d->dmy) 
1269     {
1270       g_date_update_dmy (d);
1271     }
1272   g_return_if_fail (d->dmy);
1273   
1274   /* zero all the irrelevant fields to be sure they're valid */
1275   
1276   /* On Linux and maybe other systems, there are weird non-POSIX
1277    * fields on the end of struct tm that choke strftime if they
1278    * contain garbage.  So we need to 0 the entire struct, not just the
1279    * fields we know to exist. 
1280    */
1281   
1282   memset (tm, 0x0, sizeof (struct tm));
1283   
1284   tm->tm_mday = d->day;
1285   tm->tm_mon  = d->month - 1; /* 0-11 goes in tm */
1286   tm->tm_year = ((int)d->year) - 1900; /* X/Open says tm_year can be negative */
1287   
1288   day = g_date_get_weekday (d);
1289   if (day == 7) day = 0; /* struct tm wants days since Sunday, so Sunday is 0 */
1290   
1291   tm->tm_wday = (int)day;
1292   
1293   tm->tm_yday = g_date_get_day_of_year (d) - 1; /* 0 to 365 */
1294   tm->tm_isdst = -1; /* -1 means "information not available" */
1295 }
1296
1297 void
1298 g_date_clamp (GDate *date,
1299               const GDate *min_date,
1300               const GDate *max_date)
1301 {
1302   g_return_if_fail (date);
1303   g_return_if_fail (g_date_valid (date));
1304   if (min_date != NULL)
1305     g_return_if_fail (g_date_valid (min_date));
1306   if (max_date != NULL)
1307     g_return_if_fail (g_date_valid (max_date));
1308   if (min_date != NULL && max_date != NULL)
1309     g_return_if_fail (g_date_compare (min_date, max_date) <= 0);
1310
1311   if (min_date && g_date_compare (date, min_date) < 0)
1312     *date = *min_date;
1313
1314   if (max_date && g_date_compare (max_date, date) < 0)
1315     *date = *max_date;
1316 }
1317
1318 void
1319 g_date_order (GDate *date1,
1320               GDate *date2)
1321 {
1322   g_return_if_fail (date1 != NULL);
1323   g_return_if_fail (date2 != NULL);
1324   g_return_if_fail (g_date_valid (date1));
1325   g_return_if_fail (g_date_valid (date2));
1326
1327   if (g_date_compare (date1, date2) > 0)
1328     {
1329       GDate tmp = *date1;
1330       *date1 = *date2;
1331       *date2 = tmp;
1332     }
1333 }
1334
1335 gsize     
1336 g_date_strftime (gchar       *s, 
1337                  gsize        slen, 
1338                  const gchar *format, 
1339                  const GDate *d)
1340 {
1341   struct tm tm;
1342   gsize locale_format_len = 0;
1343   gchar *locale_format;
1344   gsize tmplen;
1345   gchar *tmpbuf;
1346   gsize tmpbufsize;
1347   gsize convlen = 0;
1348   gchar *convbuf;
1349   GError *error = NULL;
1350   gsize retval;
1351
1352   g_return_val_if_fail (d != NULL, 0);
1353   g_return_val_if_fail (g_date_valid (d), 0);
1354   g_return_val_if_fail (slen > 0, 0); 
1355   g_return_val_if_fail (format != 0, 0);
1356   g_return_val_if_fail (s != 0, 0);
1357
1358   g_date_to_struct_tm (d, &tm);
1359
1360   locale_format = g_locale_from_utf8 (format, -1, NULL, &locale_format_len, &error);
1361
1362   if (error)
1363     {
1364       g_warning (G_STRLOC "Error converting format to locale encoding: %s\n", error->message);
1365       g_error_free (error);
1366
1367       s[0] = '\0';
1368       return 0;
1369     }
1370
1371   tmpbufsize = MAX (128, locale_format_len * 2);
1372   while (TRUE)
1373     {
1374       tmpbuf = g_malloc (tmpbufsize);
1375
1376       /* Set the first byte to something other than '\0', to be able to
1377        * recognize whether strftime actually failed or just returned "".
1378        */
1379       tmpbuf[0] = '\1';
1380       tmplen = strftime (tmpbuf, tmpbufsize, locale_format, &tm);
1381
1382       if (tmplen == 0 && tmpbuf[0] != '\0')
1383         {
1384           g_free (tmpbuf);
1385           tmpbufsize *= 2;
1386
1387           if (tmpbufsize > 65536)
1388             {
1389               g_warning (G_STRLOC "Maximum buffer size for g_date_strftime exceeded: giving up\n");
1390               g_free (locale_format);
1391
1392               s[0] = '\0';
1393               return 0;
1394             }
1395         }
1396       else
1397         break;
1398     }
1399   g_free (locale_format);
1400
1401   convbuf = g_locale_to_utf8 (tmpbuf, tmplen, NULL, &convlen, &error);
1402   g_free (tmpbuf);
1403
1404   if (error)
1405     {
1406       g_warning (G_STRLOC "Error converting results of strftime to UTF-8: %s\n", error->message);
1407       g_error_free (error);
1408
1409       s[0] = '\0';
1410       return 0;
1411     }
1412
1413   if (slen <= convlen)
1414     {
1415       /* Ensure only whole characters are copied into the buffer.
1416        */
1417       gchar *end = g_utf8_find_prev_char (convbuf, convbuf + slen);
1418       g_assert (end != NULL);
1419       convlen = end - convbuf;
1420
1421       /* Return 0 because the buffer isn't large enough.
1422        */
1423       retval = 0;
1424     }
1425   else
1426     retval = convlen;
1427
1428   memcpy (s, convbuf, convlen);
1429   s[convlen] = '\0';
1430   g_free (convbuf);
1431
1432   return retval;
1433 }
1434