Merge pull request #980 from StephenMcConnel/bug-18638
[mono.git] / mcs / class / System.Core / System / TimeZoneInfo.cs
1
2 /*
3  * System.TimeZoneInfo
4  *
5  * Author(s)
6  *      Stephane Delcroix <stephane@delcroix.org>
7  *
8  * Copyright 2011 Xamarin Inc.
9  *
10  * Permission is hereby granted, free of charge, to any person obtaining
11  * a copy of this software and associated documentation files (the
12  * "Software"), to deal in the Software without restriction, including
13  * without limitation the rights to use, copy, modify, merge, publish,
14  * distribute, sublicense, and/or sell copies of the Software, and to
15  * permit persons to whom the Software is furnished to do so, subject to
16  * the following conditions:
17  * 
18  * The above copyright notice and this permission notice shall be
19  * included in all copies or substantial portions of the Software.
20  * 
21  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24  * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25  * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26  * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27  * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28  */
29
30 using System;
31 using System.Runtime.CompilerServices;
32 using System.Threading;
33
34 #if !INSIDE_CORLIB && NET_4_0
35
36 [assembly:TypeForwardedTo (typeof(TimeZoneInfo))]
37
38 #elif INSIDE_CORLIB || (NET_3_5 && !NET_4_0 && !MOBILE)
39
40 using System.Collections.Generic;
41 using System.Collections.ObjectModel;
42 using System.Runtime.Serialization;
43 using System.Text;
44
45 #if LIBC || MONODROID
46 using System.IO;
47 using Mono;
48 #endif
49
50 using Microsoft.Win32;
51
52 namespace System
53 {
54 #if MOBILE
55         [TypeForwardedFrom (Consts.AssemblySystem_Core)]
56 #elif NET_4_0
57         [TypeForwardedFrom (Consts.AssemblySystemCore_3_5)]
58 #endif
59         [SerializableAttribute]
60 #if NET_4_0 || !INSIDE_CORLIB
61         public
62 #endif
63         sealed partial class TimeZoneInfo : IEquatable<TimeZoneInfo>, ISerializable, IDeserializationCallback
64         {
65                 TimeSpan baseUtcOffset;
66                 public TimeSpan BaseUtcOffset {
67                         get { return baseUtcOffset; }
68                 }
69
70                 string daylightDisplayName;
71                 public string DaylightName {
72                         get { 
73                                 return supportsDaylightSavingTime
74                                         ? daylightDisplayName
75                                         : string.Empty;
76                         }
77                 }
78
79                 string displayName;
80                 public string DisplayName {
81                         get { return displayName; }
82                 }
83
84                 string id;
85                 public string Id {
86                         get { return id; }
87                 }
88
89                 static TimeZoneInfo local;
90                 public static TimeZoneInfo Local {
91                         get { 
92                                 var l = local;
93                                 if (l == null) {
94                                         l = CreateLocal ();
95                                         if (l == null)
96                                                 throw new TimeZoneNotFoundException ();
97
98                                         if (Interlocked.CompareExchange (ref local, l, null) != null)
99                                                 l = local;
100                                 }
101
102                                 return l;
103                         }
104                 }
105
106                 /*
107                         TimeZone transitions are stored when there is a change on the base offset.
108                 */
109                 private List<KeyValuePair<DateTime, TimeType>> transitions;
110
111                 static TimeZoneInfo CreateLocal ()
112                 {
113 #if MONODROID
114                         return AndroidTimeZones.Local;
115 #elif MONOTOUCH
116                         using (Stream stream = GetMonoTouchData (null)) {
117                                 return BuildFromStream ("Local", stream);
118                         }
119 #else
120                         if (IsWindows && LocalZoneKey != null) {
121                                 string name = (string)LocalZoneKey.GetValue ("TimeZoneKeyName");
122                                 name = TrimSpecial (name);
123                                 if (name != null)
124                                         return TimeZoneInfo.FindSystemTimeZoneById (name);
125                         }
126
127                         var tz = Environment.GetEnvironmentVariable ("TZ");
128                         if (tz != null) {
129                                 if (tz == String.Empty)
130                                         return Utc;
131                                 try {
132                                         return FindSystemTimeZoneByFileName (tz, Path.Combine (TimeZoneDirectory, tz));
133                                 } catch {
134                                         return Utc;
135                                 }
136                         }
137
138                         try {
139                                 return FindSystemTimeZoneByFileName ("Local", "/etc/localtime");        
140                         } catch {
141                                 try {
142                                         return FindSystemTimeZoneByFileName ("Local", Path.Combine (TimeZoneDirectory, "localtime"));   
143                                 } catch {
144                                         return null;
145                                 }
146                         }
147 #endif
148                 }
149
150                 string standardDisplayName;
151                 public string StandardName {
152                         get { return standardDisplayName; }
153                 }
154
155                 bool supportsDaylightSavingTime;
156                 public bool SupportsDaylightSavingTime {
157                         get  { return supportsDaylightSavingTime; }
158                 }
159
160                 static TimeZoneInfo utc;
161                 public static TimeZoneInfo Utc {
162                         get {
163                                 if (utc == null)
164                                         utc = CreateCustomTimeZone ("UTC", new TimeSpan (0), "UTC", "UTC");
165                                 return utc;
166                         }
167                 }
168 #if LIBC
169                 static string timeZoneDirectory;
170                 static string TimeZoneDirectory {
171                         get {
172                                 if (timeZoneDirectory == null)
173                                         timeZoneDirectory = "/usr/share/zoneinfo";
174                                 return timeZoneDirectory;
175                         }
176                         set {
177                                 ClearCachedData ();
178                                 timeZoneDirectory = value;
179                         }
180                 }
181 #endif
182                 private AdjustmentRule [] adjustmentRules;
183
184 #if !NET_2_1
185                 /// <summary>
186                 /// Determine whether windows of not (taken Stephane Delcroix's code)
187                 /// </summary>
188                 private static bool IsWindows
189                 {
190                         get {
191                                 int platform = (int) Environment.OSVersion.Platform;
192                                 return ((platform != 4) && (platform != 6) && (platform != 128));
193                         }
194                 }
195                 
196                 /// <summary>
197                 /// Needed to trim misc garbage in MS registry keys
198                 /// </summary>
199                 private static string TrimSpecial (string str)
200                 {
201                         var Istart = 0;
202                         while (Istart < str.Length && !char.IsLetterOrDigit(str[Istart])) Istart++;
203                         var Iend = str.Length - 1;
204                         while (Iend > Istart && !char.IsLetterOrDigit(str[Iend])) Iend--;
205                         
206                         return str.Substring (Istart, Iend-Istart+1);
207                 }
208                 
209                 static RegistryKey timeZoneKey;
210                 static RegistryKey TimeZoneKey {
211                         get {
212                                 if (timeZoneKey != null)
213                                         return timeZoneKey;
214                                 if (!IsWindows)
215                                         return null;
216                                 
217                                 return timeZoneKey = Registry.LocalMachine.OpenSubKey (
218                                         "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones",
219                                         false);
220                         }
221                 }
222                 
223                 static RegistryKey localZoneKey;
224                 static RegistryKey LocalZoneKey {
225                         get {
226                                 if (localZoneKey != null)
227                                         return localZoneKey;
228                                 
229                                 if (!IsWindows)
230                                         return null;
231                                 
232                                 return localZoneKey = Registry.LocalMachine.OpenSubKey (
233                                         "SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation", false);
234                         }
235                 }
236 #endif
237
238                 public static void ClearCachedData ()
239                 {
240                         local = null;
241                         utc = null;
242                         systemTimeZones = null;
243                 }
244
245                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo destinationTimeZone)
246                 {
247                         return ConvertTime (dateTime, dateTime.Kind == DateTimeKind.Utc ? TimeZoneInfo.Utc : TimeZoneInfo.Local, destinationTimeZone);
248                 }
249
250                 public static DateTime ConvertTime (DateTime dateTime, TimeZoneInfo sourceTimeZone, TimeZoneInfo destinationTimeZone)
251                 {
252                         if (sourceTimeZone == null)
253                                 throw new ArgumentNullException ("sourceTimeZone");
254
255                         if (destinationTimeZone == null)
256                                 throw new ArgumentNullException ("destinationTimeZone");
257                         
258                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
259                                 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
260
261                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
262                                 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
263                         
264                         if (sourceTimeZone.IsInvalidTime (dateTime))
265                                 throw new ArgumentException ("dateTime parameter is an invalid time");
266
267                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone == TimeZoneInfo.Local && destinationTimeZone == TimeZoneInfo.Local)
268                                 return dateTime;
269
270                         DateTime utc = ConvertTimeToUtc (dateTime);
271
272                         if (destinationTimeZone != TimeZoneInfo.Utc) {
273                                 utc = ConvertTimeFromUtc (utc, destinationTimeZone);
274                                 if (dateTime.Kind == DateTimeKind.Unspecified)
275                                         return DateTime.SpecifyKind (utc, DateTimeKind.Unspecified);
276                         }
277                         
278                         return utc;
279                 }
280
281                 public static DateTimeOffset ConvertTime(DateTimeOffset dateTimeOffset, TimeZoneInfo destinationTimeZone) 
282                 {
283                         if (destinationTimeZone == null) 
284                                 throw new ArgumentNullException("destinationTimeZone");
285                 
286                         var utcDateTime = dateTimeOffset.UtcDateTime;
287                         AdjustmentRule rule = destinationTimeZone.GetApplicableRule (utcDateTime);
288                 
289                         if (rule != null && destinationTimeZone.IsDaylightSavingTime(utcDateTime)) {
290                                 var offset = destinationTimeZone.BaseUtcOffset + rule.DaylightDelta;
291                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + offset, offset);
292                         }
293                         else {
294                                 return new DateTimeOffset(DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified) + destinationTimeZone.BaseUtcOffset, destinationTimeZone.BaseUtcOffset);
295                         }
296                 }
297
298                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string destinationTimeZoneId)
299                 {
300                         return ConvertTime (dateTime, FindSystemTimeZoneById (destinationTimeZoneId));
301                 }
302
303                 public static DateTime ConvertTimeBySystemTimeZoneId (DateTime dateTime, string sourceTimeZoneId, string destinationTimeZoneId)
304                 {
305                         return ConvertTime (dateTime, FindSystemTimeZoneById (sourceTimeZoneId), FindSystemTimeZoneById (destinationTimeZoneId));
306                 }
307
308                 public static DateTimeOffset ConvertTimeBySystemTimeZoneId (DateTimeOffset dateTimeOffset, string destinationTimeZoneId)
309                 {
310                         return ConvertTime (dateTimeOffset, FindSystemTimeZoneById (destinationTimeZoneId));
311                 }
312
313                 private DateTime ConvertTimeFromUtc (DateTime dateTime)
314                 {
315                         if (dateTime.Kind == DateTimeKind.Local)
316                                 throw new ArgumentException ("Kind property of dateTime is Local");
317
318                         if (this == TimeZoneInfo.Utc)
319                                 return DateTime.SpecifyKind (dateTime, DateTimeKind.Utc);
320                         
321                         //FIXME: do not rely on DateTime implementation !
322                         if (this == TimeZoneInfo.Local) 
323                         {
324 #if NET_4_0
325                                 return dateTime.ToLocalTime ();
326 #else
327                                 return DateTime.SpecifyKind (dateTime.ToLocalTime (), DateTimeKind.Unspecified);
328 #endif
329                         }
330
331
332                         AdjustmentRule rule = GetApplicableRule (dateTime);
333                         if (rule != null && IsDaylightSavingTime (DateTime.SpecifyKind (dateTime, DateTimeKind.Utc)))
334                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset + rule.DaylightDelta , DateTimeKind.Unspecified);
335                         else
336                                 return DateTime.SpecifyKind (dateTime + BaseUtcOffset, DateTimeKind.Unspecified);
337                 }
338
339                 public static DateTime ConvertTimeFromUtc (DateTime dateTime, TimeZoneInfo destinationTimeZone)
340                 {
341                         if (destinationTimeZone == null)
342                                 throw new ArgumentNullException ("destinationTimeZone");
343
344                         return destinationTimeZone.ConvertTimeFromUtc (dateTime);
345                 }
346
347                 public static DateTime ConvertTimeToUtc (DateTime dateTime)
348                 {
349                         if (dateTime.Kind == DateTimeKind.Utc)
350                                 return dateTime;
351
352                         return ConvertTimeToUtc (dateTime, TimeZoneInfo.Local);
353                 }
354
355                 public static DateTime ConvertTimeToUtc (DateTime dateTime, TimeZoneInfo sourceTimeZone)
356                 {
357                         if (sourceTimeZone == null)
358                                 throw new ArgumentNullException ("sourceTimeZone");
359
360                         if (dateTime.Kind == DateTimeKind.Utc && sourceTimeZone != TimeZoneInfo.Utc)
361                                 throw new ArgumentException ("Kind property of dateTime is Utc but the sourceTimeZone does not equal TimeZoneInfo.Utc");
362
363                         if (dateTime.Kind == DateTimeKind.Local && sourceTimeZone != TimeZoneInfo.Local)
364                                 throw new ArgumentException ("Kind property of dateTime is Local but the sourceTimeZone does not equal TimeZoneInfo.Local");
365
366                         if (sourceTimeZone.IsInvalidTime (dateTime))
367                                 throw new ArgumentException ("dateTime parameter is an invalid time");
368
369                         if (dateTime.Kind == DateTimeKind.Utc)
370                                 return dateTime;
371
372                         if (sourceTimeZone.IsAmbiguousTime (dateTime) || !sourceTimeZone.IsDaylightSavingTime (dateTime))
373                                 return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
374                         else {
375                                 AdjustmentRule rule = sourceTimeZone.GetApplicableRule (dateTime);
376                                 if (rule != null)
377                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset - rule.DaylightDelta, DateTimeKind.Utc);
378                                 else
379                                         return DateTime.SpecifyKind (dateTime - sourceTimeZone.BaseUtcOffset, DateTimeKind.Utc);
380                         }
381                 }
382
383                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName) 
384                 {
385                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, null, null, true);
386                 }
387
388                 public static TimeZoneInfo CreateCustomTimeZone (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules)
389                 {
390                         return CreateCustomTimeZone (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, false);
391                 }
392
393                 public static TimeZoneInfo CreateCustomTimeZone ( string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
394                 {
395                         return new TimeZoneInfo (id, baseUtcOffset, displayName, standardDisplayName, daylightDisplayName, adjustmentRules, disableDaylightSavingTime);
396                 }
397
398 #if NET_4_5
399                 public override bool Equals (object obj)
400                 {
401                         return Equals (obj as TimeZoneInfo);
402                 }
403 #endif
404
405                 public bool Equals (TimeZoneInfo other)
406                 {
407                         if (other == null)
408                                 return false;
409
410                         return other.Id == this.Id && HasSameRules (other);
411                 }
412
413                 public static TimeZoneInfo FindSystemTimeZoneById (string id)
414                 {
415                         //FIXME: this method should check for cached values in systemTimeZones
416                         if (id == null)
417                                 throw new ArgumentNullException ("id");
418 #if !NET_2_1
419                         if (TimeZoneKey != null)
420                         {
421                                 RegistryKey key = TimeZoneKey.OpenSubKey (id, false);
422                                 if (key == null)
423                                         throw new TimeZoneNotFoundException ();
424                                 return FromRegistryKey(id, key);
425                         }
426 #endif
427                         // Local requires special logic that already exists in the Local property (bug #326)
428                         if (id == "Local")
429                                 return Local;
430 #if MONOTOUCH
431                         using (Stream stream = GetMonoTouchData (id)) {
432                                 return BuildFromStream (id, stream);
433                         }
434 #elif MONODROID
435                         var timeZoneInfo = AndroidTimeZones.GetTimeZone (id, id);
436                         if (timeZoneInfo == null)
437                                 throw new TimeZoneNotFoundException ();
438                         return timeZoneInfo;
439 #elif LIBC
440                         string filepath = Path.Combine (TimeZoneDirectory, id);
441                         return FindSystemTimeZoneByFileName (id, filepath);
442 #else
443                         throw new NotImplementedException ();
444 #endif
445                 }
446
447 #if LIBC
448                 private static TimeZoneInfo FindSystemTimeZoneByFileName (string id, string filepath)
449                 {
450                         if (!File.Exists (filepath))
451                                 throw new TimeZoneNotFoundException ();
452
453                         using (FileStream stream = File.OpenRead (filepath)) {
454                                 return BuildFromStream (id, stream);
455                         }
456                 }
457 #endif
458 #if LIBC || MONOTOUCH
459                 const int BUFFER_SIZE = 16384; //Big enough for any tz file (on Oct 2008, all tz files are under 10k)
460                 
461                 private static TimeZoneInfo BuildFromStream (string id, Stream stream) 
462                 {
463                         byte [] buffer = new byte [BUFFER_SIZE];
464                         int length = stream.Read (buffer, 0, BUFFER_SIZE);
465                         
466                         if (!ValidTZFile (buffer, length))
467                                 throw new InvalidTimeZoneException ("TZ file too big for the buffer");
468
469                         try {
470                                 return ParseTZBuffer (id, buffer, length);
471                         } catch (Exception e) {
472                                 throw new InvalidTimeZoneException (e.Message);
473                         }
474                 }
475 #endif
476
477 #if !NET_2_1
478                 private static TimeZoneInfo FromRegistryKey (string id, RegistryKey key)
479                 {
480                         byte [] reg_tzi = (byte []) key.GetValue ("TZI");
481
482                         if (reg_tzi == null)
483                                 throw new InvalidTimeZoneException ();
484
485                         int bias = BitConverter.ToInt32 (reg_tzi, 0);
486                         TimeSpan baseUtcOffset = new TimeSpan (0, -bias, 0);
487
488                         string display_name = (string) key.GetValue ("Display");
489                         string standard_name = (string) key.GetValue ("Std");
490                         string daylight_name = (string) key.GetValue ("Dlt");
491
492                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
493
494                         RegistryKey dst_key = key.OpenSubKey ("Dynamic DST", false);
495                         if (dst_key != null) {
496                                 int first_year = (int) dst_key.GetValue ("FirstEntry");
497                                 int last_year = (int) dst_key.GetValue ("LastEntry");
498                                 int year;
499
500                                 for (year=first_year; year<=last_year; year++) {
501                                         byte [] dst_tzi = (byte []) dst_key.GetValue (year.ToString ());
502                                         if (dst_tzi != null) {
503                                                 int start_year = year == first_year ? 1 : year;
504                                                 int end_year = year == last_year ? 9999 : year;
505                                                 ParseRegTzi(adjustmentRules, start_year, end_year, dst_tzi);
506                                         }
507                                 }
508                         }
509                         else
510                                 ParseRegTzi(adjustmentRules, 1, 9999, reg_tzi);
511
512                         return CreateCustomTimeZone (id, baseUtcOffset, display_name, standard_name, daylight_name, ValidateRules (adjustmentRules).ToArray ());
513                 }
514
515                 private static void ParseRegTzi (List<AdjustmentRule> adjustmentRules, int start_year, int end_year, byte [] buffer)
516                 {
517                         //int standard_bias = BitConverter.ToInt32 (buffer, 4); /* not sure how to handle this */
518                         int daylight_bias = BitConverter.ToInt32 (buffer, 8);
519
520                         int standard_year = BitConverter.ToInt16 (buffer, 12);
521                         int standard_month = BitConverter.ToInt16 (buffer, 14);
522                         int standard_dayofweek = BitConverter.ToInt16 (buffer, 16);
523                         int standard_day = BitConverter.ToInt16 (buffer, 18);
524                         int standard_hour = BitConverter.ToInt16 (buffer, 20);
525                         int standard_minute = BitConverter.ToInt16 (buffer, 22);
526                         int standard_second = BitConverter.ToInt16 (buffer, 24);
527                         int standard_millisecond = BitConverter.ToInt16 (buffer, 26);
528
529                         int daylight_year = BitConverter.ToInt16 (buffer, 28);
530                         int daylight_month = BitConverter.ToInt16 (buffer, 30);
531                         int daylight_dayofweek = BitConverter.ToInt16 (buffer, 32);
532                         int daylight_day = BitConverter.ToInt16 (buffer, 34);
533                         int daylight_hour = BitConverter.ToInt16 (buffer, 36);
534                         int daylight_minute = BitConverter.ToInt16 (buffer, 38);
535                         int daylight_second = BitConverter.ToInt16 (buffer, 40);
536                         int daylight_millisecond = BitConverter.ToInt16 (buffer, 42);
537
538                         if (standard_month == 0 || daylight_month == 0)
539                                 return;
540
541                         DateTime start_date;
542                         DateTime start_timeofday = new DateTime (1, 1, 1, daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
543                         TransitionTime start_transition_time;
544
545                         if (daylight_year == 0) {
546                                 start_date = new DateTime (start_year, 1, 1);
547                                 start_transition_time = TransitionTime.CreateFloatingDateRule (
548                                         start_timeofday, daylight_month, daylight_day,
549                                         (DayOfWeek) daylight_dayofweek);
550                         }
551                         else {
552                                 start_date = new DateTime (daylight_year, daylight_month, daylight_day,
553                                         daylight_hour, daylight_minute, daylight_second, daylight_millisecond);
554                                 start_transition_time = TransitionTime.CreateFixedDateRule (
555                                         start_timeofday, daylight_month, daylight_day);
556                         }
557
558                         DateTime end_date;
559                         DateTime end_timeofday = new DateTime (1, 1, 1, standard_hour, standard_minute, standard_second, standard_millisecond);
560                         TransitionTime end_transition_time;
561
562                         if (standard_year == 0) {
563                                 end_date = new DateTime (end_year, 12, 31);
564                                 end_transition_time = TransitionTime.CreateFloatingDateRule (
565                                         end_timeofday, standard_month, standard_day,
566                                         (DayOfWeek) standard_dayofweek);
567                         }
568                         else {
569                                 end_date = new DateTime (standard_year, standard_month, standard_day,
570                                         standard_hour, standard_minute, standard_second, standard_millisecond);
571                                 end_transition_time = TransitionTime.CreateFixedDateRule (
572                                         end_timeofday, standard_month, standard_day);
573                         }
574
575                         TimeSpan daylight_delta = new TimeSpan(0, -daylight_bias, 0);
576
577                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (
578                                 start_date, end_date, daylight_delta,
579                                 start_transition_time, end_transition_time));
580                 }
581 #endif
582
583                 public AdjustmentRule [] GetAdjustmentRules ()
584                 {
585                         if (!supportsDaylightSavingTime)
586                                 return new AdjustmentRule [0];
587                         else
588                                 return (AdjustmentRule []) adjustmentRules.Clone ();
589                 }
590
591                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTime dateTime)
592                 {
593                         if (!IsAmbiguousTime (dateTime))
594                                 throw new ArgumentException ("dateTime is not an ambiguous time");
595
596                         AdjustmentRule rule = GetApplicableRule (dateTime);
597                         if (rule != null)
598                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset + rule.DaylightDelta};
599                         else
600                                 return new TimeSpan[] {baseUtcOffset, baseUtcOffset};
601                 }
602
603                 public TimeSpan [] GetAmbiguousTimeOffsets (DateTimeOffset dateTimeOffset)
604                 {
605                         if (!IsAmbiguousTime (dateTimeOffset))
606                                 throw new ArgumentException ("dateTimeOffset is not an ambiguous time");
607
608                         throw new NotImplementedException ();
609                 }
610
611                 public override int GetHashCode ()
612                 {
613                         int hash_code = Id.GetHashCode ();
614                         foreach (AdjustmentRule rule in GetAdjustmentRules ())
615                                 hash_code ^= rule.GetHashCode ();
616                         return hash_code;
617                 }
618
619 #if NET_4_0
620                 void ISerializable.GetObjectData (SerializationInfo info, StreamingContext context)
621 #else
622                 public void GetObjectData (SerializationInfo info, StreamingContext context)
623 #endif
624                 {
625                         if (info == null)
626                                 throw new ArgumentNullException ("info");
627                         info.AddValue ("Id", id);
628                         info.AddValue ("DisplayName", displayName);
629                         info.AddValue ("StandardName", standardDisplayName);
630                         info.AddValue ("DaylightName", daylightDisplayName);
631                         info.AddValue ("BaseUtcOffset", baseUtcOffset);
632                         info.AddValue ("AdjustmentRules", adjustmentRules);
633                         info.AddValue ("SupportsDaylightSavingTime", SupportsDaylightSavingTime);
634                 }
635
636                 //FIXME: change this to a generic Dictionary and allow caching for FindSystemTimeZoneById
637                 private static List<TimeZoneInfo> systemTimeZones;
638                 public static ReadOnlyCollection<TimeZoneInfo> GetSystemTimeZones ()
639                 {
640                         if (systemTimeZones == null) {
641                                 systemTimeZones = new List<TimeZoneInfo> ();
642 #if !NET_2_1
643                                 if (TimeZoneKey != null) {
644                                         foreach (string id in TimeZoneKey.GetSubKeyNames ()) {
645                                                 try {
646                                                         systemTimeZones.Add (FindSystemTimeZoneById (id));
647                                                 } catch {}
648                                         }
649
650                                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
651                                 }
652 #endif
653 #if MONODROID
654                         foreach (string id in AndroidTimeZones.GetAvailableIds ()) {
655                                 var tz = AndroidTimeZones.GetTimeZone (id, id);
656                                 if (tz != null)
657                                         systemTimeZones.Add (tz);
658                         }
659 #elif MONOTOUCH
660                                 if (systemTimeZones.Count == 0) {
661                                         foreach (string name in GetMonoTouchNames ()) {
662                                                 using (Stream stream = GetMonoTouchData (name, false)) {
663                                                         if (stream == null)
664                                                                 continue;
665                                                         systemTimeZones.Add (BuildFromStream (name, stream));
666                                                 }
667                                         }
668                                 }
669 #elif LIBC
670                                 string[] continents = new string [] {"Africa", "America", "Antarctica", "Arctic", "Asia", "Atlantic", "Brazil", "Canada", "Chile", "Europe", "Indian", "Mexico", "Mideast", "Pacific", "US"};
671                                 foreach (string continent in continents) {
672                                         try {
673                                                 foreach (string zonepath in Directory.GetFiles (Path.Combine (TimeZoneDirectory, continent))) {
674                                                         try {
675                                                                 string id = String.Format ("{0}/{1}", continent, Path.GetFileName (zonepath));
676                                                                 systemTimeZones.Add (FindSystemTimeZoneById (id));
677                                                         } catch (ArgumentNullException) {
678                                                         } catch (TimeZoneNotFoundException) {
679                                                         } catch (InvalidTimeZoneException) {
680                                                         } catch (Exception) {
681                                                                 throw;
682                                                         }
683                                                 }
684                                         } catch {}
685                                 }
686 #else
687                                 throw new NotImplementedException ("This method is not implemented for this platform");
688 #endif
689                         }
690                         return new ReadOnlyCollection<TimeZoneInfo> (systemTimeZones);
691                 }
692
693                 public TimeSpan GetUtcOffset (DateTime dateTime)
694                 {
695                         bool isDST;
696                         return GetUtcOffset (dateTime, out isDST);
697                 }
698
699                 public TimeSpan GetUtcOffset (DateTimeOffset dateTimeOffset)
700                 {
701                         throw new NotImplementedException ();
702                 }
703
704                 private TimeSpan GetUtcOffset (DateTime dateTime, out bool isDST)
705                 {
706                         isDST = false;
707
708                         TimeZoneInfo tz = this;
709                         if (dateTime.Kind == DateTimeKind.Utc)
710                                 tz = TimeZoneInfo.Utc;
711
712                         if (dateTime.Kind == DateTimeKind.Local)
713                                 tz = TimeZoneInfo.Local;
714
715                         bool isTzDst;
716                         var tzOffset = GetUtcOffset (dateTime, tz, out isTzDst);
717
718                         if (tz == this) {
719                                 isDST = isTzDst;
720                                 return tzOffset;
721                         }
722
723                         var utcTicks = dateTime.Ticks - tzOffset.Ticks;
724                         if (utcTicks < 0 || utcTicks > DateTime.MaxValue.Ticks)
725                                 return BaseUtcOffset;
726
727                         var utcDateTime = new DateTime (utcTicks, DateTimeKind.Utc);
728
729                         return GetUtcOffset (utcDateTime, this, out isDST);
730                 }
731
732                 private static TimeSpan GetUtcOffset (DateTime dateTime, TimeZoneInfo tz, out bool isDST)
733                 {
734                         if (dateTime.Kind == DateTimeKind.Local && tz != TimeZoneInfo.Local)
735                                 throw new Exception ();
736
737                         isDST = false;
738
739                         if (tz == TimeZoneInfo.Utc)
740                                 return TimeSpan.Zero;
741
742                         TimeSpan offset;
743                         if (tz.TryGetTransitionOffset(dateTime, out offset, out isDST))
744                                 return offset;
745
746                         if (dateTime.Kind == DateTimeKind.Utc) {
747                                 var utcRule = tz.GetApplicableRule (dateTime);
748                                 if (utcRule != null && tz.IsInDST (utcRule, dateTime)) {
749                                         isDST = true;
750                                         return tz.BaseUtcOffset + utcRule.DaylightDelta;
751                                 }
752
753                                 return tz.BaseUtcOffset;
754                         }
755
756                         var stdTicks = dateTime.Ticks - tz.BaseUtcOffset.Ticks;
757                         if (stdTicks < 0 || stdTicks > DateTime.MaxValue.Ticks)
758                                 return tz.BaseUtcOffset;
759
760                         var stdUtcDateTime = new DateTime (stdTicks, DateTimeKind.Utc);
761                         var tzRule = tz.GetApplicableRule (stdUtcDateTime);
762
763                         DateTime dstUtcDateTime = DateTime.MinValue;
764                         if (tzRule != null) {
765                                 var dstTicks = stdUtcDateTime.Ticks - tzRule.DaylightDelta.Ticks;
766                                 if (dstTicks < 0 || dstTicks > DateTime.MaxValue.Ticks)
767                                         return tz.BaseUtcOffset;
768
769                                 dstUtcDateTime = new DateTime (dstTicks, DateTimeKind.Utc);
770                         }
771
772                         if (tzRule != null && tz.IsInDST (tzRule, stdUtcDateTime) && tz.IsInDST (tzRule, dstUtcDateTime)) {
773                                 isDST = true;
774                                 return tz.BaseUtcOffset + tzRule.DaylightDelta;
775                         }
776
777                         return tz.BaseUtcOffset;
778                 }
779
780                 public bool HasSameRules (TimeZoneInfo other)
781                 {
782                         if (other == null)
783                                 throw new ArgumentNullException ("other");
784
785                         if ((this.adjustmentRules == null) != (other.adjustmentRules == null))
786                                 return false;
787
788                         if (this.adjustmentRules == null)
789                                 return true;
790
791                         if (this.BaseUtcOffset != other.BaseUtcOffset)
792                                 return false;
793
794                         if (this.adjustmentRules.Length != other.adjustmentRules.Length)
795                                 return false;
796
797                         for (int i = 0; i < adjustmentRules.Length; i++) {
798                                 if (! (this.adjustmentRules [i]).Equals (other.adjustmentRules [i]))
799                                         return false;
800                         }
801                         
802                         return true;
803                 }
804
805                 public bool IsAmbiguousTime (DateTime dateTime)
806                 {
807                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
808                                 throw new ArgumentException ("Kind is Local and time is Invalid");
809
810                         if (this == TimeZoneInfo.Utc)
811                                 return false;
812                         
813                         if (dateTime.Kind == DateTimeKind.Utc)
814                                 dateTime = ConvertTimeFromUtc (dateTime);
815
816                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
817                                 dateTime = ConvertTime (dateTime, TimeZoneInfo.Local, this);
818
819                         AdjustmentRule rule = GetApplicableRule (dateTime);
820                         if (rule != null) {
821                                 DateTime tpoint = TransitionPoint (rule.DaylightTransitionEnd, dateTime.Year);
822                                 if (dateTime > tpoint - rule.DaylightDelta  && dateTime <= tpoint)
823                                         return true;
824                         }
825                                 
826                         return false;
827                 }
828
829                 public bool IsAmbiguousTime (DateTimeOffset dateTimeOffset)
830                 {
831                         throw new NotImplementedException ();
832                 }
833
834                 private bool IsInDST (AdjustmentRule rule, DateTime dateTime)
835                 {
836                         // Check whether we're in the dateTime year's DST period
837                         if (IsInDSTForYear (rule, dateTime, dateTime.Year))
838                                 return true;
839
840                         // We might be in the dateTime previous year's DST period
841                         return IsInDSTForYear (rule, dateTime, dateTime.Year - 1);
842                 }
843
844                 bool IsInDSTForYear (AdjustmentRule rule, DateTime dateTime, int year)
845                 {
846                         DateTime DST_start = TransitionPoint (rule.DaylightTransitionStart, year);
847                         DateTime DST_end = TransitionPoint (rule.DaylightTransitionEnd, year + ((rule.DaylightTransitionStart.Month < rule.DaylightTransitionEnd.Month) ? 0 : 1));
848                         if (dateTime.Kind == DateTimeKind.Utc) {
849                                 DST_start -= BaseUtcOffset;
850                                 DST_end -= (BaseUtcOffset + rule.DaylightDelta);
851                         }
852
853                         return (dateTime >= DST_start && dateTime < DST_end);
854                 }
855                 
856                 public bool IsDaylightSavingTime (DateTime dateTime)
857                 {
858                         if (dateTime.Kind == DateTimeKind.Local && IsInvalidTime (dateTime))
859                                 throw new ArgumentException ("dateTime is invalid and Kind is Local");
860
861                         if (this == TimeZoneInfo.Utc)
862                                 return false;
863                         
864                         if (!SupportsDaylightSavingTime)
865                                 return false;
866
867                         bool isDst;
868                         GetUtcOffset (dateTime, out isDst);
869
870                         return isDst;
871                 }
872
873                 public bool IsDaylightSavingTime (DateTimeOffset dateTimeOffset)
874                 {
875                         throw new NotImplementedException ();
876                 }
877
878                 public bool IsInvalidTime (DateTime dateTime)
879                 {
880                         if (dateTime.Kind == DateTimeKind.Utc)
881                                 return false;
882                         if (dateTime.Kind == DateTimeKind.Local && this != Local)
883                                 return false;
884
885                         AdjustmentRule rule = GetApplicableRule (dateTime);
886                         if (rule != null) {
887                                 DateTime tpoint = TransitionPoint (rule.DaylightTransitionStart, dateTime.Year);
888                                 if (dateTime >= tpoint && dateTime < tpoint + rule.DaylightDelta)
889                                         return true;
890                         }
891                                 
892                         return false;
893                 }
894
895 #if NET_4_0
896                 void IDeserializationCallback.OnDeserialization (object sender)
897 #else
898                 public void OnDeserialization (object sender)
899 #endif
900                 {
901                         try {
902                                         TimeZoneInfo.Validate (id, baseUtcOffset, adjustmentRules);
903                                 } catch (ArgumentException ex) {
904                                         throw new SerializationException ("invalid serialization data", ex);
905                                 }
906                 }
907
908                 private static void Validate (string id, TimeSpan baseUtcOffset, AdjustmentRule [] adjustmentRules)
909                 {
910                         if (id == null)
911                                 throw new ArgumentNullException ("id");
912
913                         if (id == String.Empty)
914                                 throw new ArgumentException ("id parameter is an empty string");
915
916                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
917                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
918
919                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
920                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
921
922 #if STRICT
923                         if (id.Length > 32)
924                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
925 #endif
926
927                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
928                                 AdjustmentRule prev = null;
929                                 foreach (AdjustmentRule current in adjustmentRules) {
930                                         if (current == null)
931                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
932
933                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
934                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
935                                                 throw new InvalidTimeZoneException ("Sum of baseUtcOffset and DaylightDelta of one or more object in adjustmentRules array is greater than 14 or less than -14 hours;");
936
937                                         if (prev != null && prev.DateStart > current.DateStart)
938                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
939                                         
940                                         if (prev != null && prev.DateEnd > current.DateStart)
941                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
942
943                                         if (prev != null && prev.DateEnd == current.DateStart)
944                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
945
946                                         prev = current;
947                                 }
948                         }
949                 }
950                 
951                 public override string ToString ()
952                 {
953                         return DisplayName;
954                 }
955
956                 private TimeZoneInfo (SerializationInfo info, StreamingContext context)
957                 {
958                         if (info == null)
959                                 throw new ArgumentNullException ("info");
960                         id = (string) info.GetValue ("Id", typeof (string));
961                         displayName = (string) info.GetValue ("DisplayName", typeof (string));
962                         standardDisplayName = (string) info.GetValue ("StandardName", typeof (string));
963                         daylightDisplayName = (string) info.GetValue ("DaylightName", typeof (string));
964                         baseUtcOffset = (TimeSpan) info.GetValue ("BaseUtcOffset", typeof (TimeSpan));
965                         adjustmentRules = (TimeZoneInfo.AdjustmentRule []) info.GetValue ("AdjustmentRules", typeof (TimeZoneInfo.AdjustmentRule []));
966                         supportsDaylightSavingTime = (bool) info.GetValue ("SupportsDaylightSavingTime", typeof (bool));
967                 }
968
969                 private TimeZoneInfo (string id, TimeSpan baseUtcOffset, string displayName, string standardDisplayName, string daylightDisplayName, TimeZoneInfo.AdjustmentRule [] adjustmentRules, bool disableDaylightSavingTime)
970                 {
971                         if (id == null)
972                                 throw new ArgumentNullException ("id");
973
974                         if (id == String.Empty)
975                                 throw new ArgumentException ("id parameter is an empty string");
976
977                         if (baseUtcOffset.Ticks % TimeSpan.TicksPerMinute != 0)
978                                 throw new ArgumentException ("baseUtcOffset parameter does not represent a whole number of minutes");
979
980                         if (baseUtcOffset > new TimeSpan (14, 0, 0) || baseUtcOffset < new TimeSpan (-14, 0, 0))
981                                 throw new ArgumentOutOfRangeException ("baseUtcOffset parameter is greater than 14 hours or less than -14 hours");
982
983 #if STRICT
984                         if (id.Length > 32)
985                                 throw new ArgumentException ("id parameter shouldn't be longer than 32 characters");
986 #endif
987
988                         bool supportsDaylightSavingTime = !disableDaylightSavingTime;
989
990                         if (adjustmentRules != null && adjustmentRules.Length != 0) {
991                                 AdjustmentRule prev = null;
992                                 foreach (AdjustmentRule current in adjustmentRules) {
993                                         if (current == null)
994                                                 throw new InvalidTimeZoneException ("one or more elements in adjustmentRules are null");
995
996                                         if ((baseUtcOffset + current.DaylightDelta < new TimeSpan (-14, 0, 0)) ||
997                                                         (baseUtcOffset + current.DaylightDelta > new TimeSpan (14, 0, 0)))
998                                                 throw new InvalidTimeZoneException ("Sum of baseUtcOffset and DaylightDelta of one or more object in adjustmentRules array is greater than 14 or less than -14 hours;");
999
1000                                         if (prev != null && prev.DateStart > current.DateStart)
1001                                                 throw new InvalidTimeZoneException ("adjustment rules specified in adjustmentRules parameter are not in chronological order");
1002                                         
1003                                         if (prev != null && prev.DateEnd > current.DateStart)
1004                                                 throw new InvalidTimeZoneException ("some adjustment rules in the adjustmentRules parameter overlap");
1005
1006                                         if (prev != null && prev.DateEnd == current.DateStart)
1007                                                 throw new InvalidTimeZoneException ("a date can have multiple adjustment rules applied to it");
1008
1009                                         prev = current;
1010                                 }
1011                         } else {
1012                                 supportsDaylightSavingTime = false;
1013                         }
1014                         
1015                         this.id = id;
1016                         this.baseUtcOffset = baseUtcOffset;
1017                         this.displayName = displayName ?? id;
1018                         this.standardDisplayName = standardDisplayName ?? id;
1019                         this.daylightDisplayName = daylightDisplayName;
1020                         this.supportsDaylightSavingTime = supportsDaylightSavingTime;
1021                         this.adjustmentRules = adjustmentRules;
1022                 }
1023
1024                 private AdjustmentRule GetApplicableRule (DateTime dateTime)
1025                 {
1026                         //Transitions are always in standard time
1027                         DateTime date = dateTime;
1028
1029                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1030                                 date = date.ToUniversalTime () + BaseUtcOffset;
1031
1032                         if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1033                                 date = date + BaseUtcOffset;
1034
1035                         if (adjustmentRules != null) {
1036                                 foreach (AdjustmentRule rule in adjustmentRules) {
1037                                         if (rule.DateStart > date.Date)
1038                                                 return null;
1039                                         if (rule.DateEnd < date.Date)
1040                                                 continue;
1041                                         return rule;
1042                                 }
1043                         }
1044                         return null;
1045                 }
1046
1047                 private bool TryGetTransitionOffset (DateTime dateTime, out TimeSpan offset,out bool isDst)
1048                 {
1049                         offset = BaseUtcOffset;
1050                         isDst = false;
1051
1052                         if (transitions == null)
1053                                 return false;
1054
1055                         //Transitions are always in standard time
1056                         DateTime date = dateTime;
1057
1058                         if (dateTime.Kind == DateTimeKind.Local && this != TimeZoneInfo.Local)
1059                                 date = date.ToUniversalTime () + BaseUtcOffset;
1060
1061                         if (dateTime.Kind == DateTimeKind.Utc && this != TimeZoneInfo.Utc)
1062                                 date = date + BaseUtcOffset;
1063
1064                         for (var i =  transitions.Count - 1; i >= 0; i--) {
1065                                 var pair = transitions [i];
1066                                 DateTime ttime = pair.Key;
1067                                 TimeType ttype = pair.Value;
1068
1069                                 if (ttime > date)
1070                                         continue;
1071
1072                                 offset =  new TimeSpan (0, 0, ttype.Offset);
1073                                 isDst = ttype.IsDst;
1074
1075                                 return true;
1076                         }
1077
1078                         return false;
1079                 }
1080
1081                 private static DateTime TransitionPoint (TransitionTime transition, int year)
1082                 {
1083                         if (transition.IsFixedDateRule)
1084                                 return new DateTime (year, transition.Month, transition.Day) + transition.TimeOfDay.TimeOfDay;
1085
1086                         DayOfWeek first = (new DateTime (year, transition.Month, 1)).DayOfWeek;
1087                         int day = 1 + (transition.Week - 1) * 7 + (transition.DayOfWeek - first) % 7;
1088                         if (day >  DateTime.DaysInMonth (year, transition.Month))
1089                                 day -= 7;
1090                         if (day < 1)
1091                                 day += 7;
1092                         return new DateTime (year, transition.Month, day) + transition.TimeOfDay.TimeOfDay;
1093                 }
1094
1095                 static List<AdjustmentRule> ValidateRules (List<AdjustmentRule> adjustmentRules)
1096                 {
1097                         AdjustmentRule prev = null;
1098                         foreach (AdjustmentRule current in adjustmentRules.ToArray ()) {
1099                                 if (prev != null && prev.DateEnd > current.DateStart) {
1100                                         adjustmentRules.Remove (current);
1101                                 }
1102                                 prev = current;
1103                         }
1104                         return adjustmentRules;
1105                 }
1106
1107 #if LIBC || MONODROID
1108                 private static bool ValidTZFile (byte [] buffer, int length)
1109                 {
1110                         StringBuilder magic = new StringBuilder ();
1111
1112                         for (int i = 0; i < 4; i++)
1113                                 magic.Append ((char)buffer [i]);
1114                         
1115                         if (magic.ToString () != "TZif")
1116                                 return false;
1117
1118                         if (length >= BUFFER_SIZE)
1119                                 return false;
1120
1121                         return true;
1122                 }
1123
1124                 static int SwapInt32 (int i)
1125                 {
1126                         return (((i >> 24) & 0xff)
1127                                 | ((i >> 8) & 0xff00)
1128                                 | ((i << 8) & 0xff0000)
1129                                 | ((i << 24)));
1130                 }
1131
1132                 static int ReadBigEndianInt32 (byte [] buffer, int start)
1133                 {
1134                         int i = BitConverter.ToInt32 (buffer, start);
1135                         if (!BitConverter.IsLittleEndian)
1136                                 return i;
1137
1138                         return SwapInt32 (i);
1139                 }
1140
1141                 private static TimeZoneInfo ParseTZBuffer (string id, byte [] buffer, int length)
1142                 {
1143                         //Reading the header. 4 bytes for magic, 16 are reserved
1144                         int ttisgmtcnt = ReadBigEndianInt32 (buffer, 20);
1145                         int ttisstdcnt = ReadBigEndianInt32 (buffer, 24);
1146                         int leapcnt = ReadBigEndianInt32 (buffer, 28);
1147                         int timecnt = ReadBigEndianInt32 (buffer, 32);
1148                         int typecnt = ReadBigEndianInt32 (buffer, 36);
1149                         int charcnt = ReadBigEndianInt32 (buffer, 40);
1150
1151                         if (length < 44 + timecnt * 5 + typecnt * 6 + charcnt + leapcnt * 8 + ttisstdcnt + ttisgmtcnt)
1152                                 throw new InvalidTimeZoneException ();
1153
1154                         Dictionary<int, string> abbreviations = ParseAbbreviations (buffer, 44 + 4 * timecnt + timecnt + 6 * typecnt, charcnt);
1155                         Dictionary<int, TimeType> time_types = ParseTimesTypes (buffer, 44 + 4 * timecnt + timecnt, typecnt, abbreviations);
1156                         List<KeyValuePair<DateTime, TimeType>> transitions = ParseTransitions (buffer, 44, timecnt, time_types);
1157
1158                         if (time_types.Count == 0)
1159                                 throw new InvalidTimeZoneException ();
1160
1161                         if (time_types.Count == 1 && ((TimeType)time_types[0]).IsDst)
1162                                 throw new InvalidTimeZoneException ();
1163
1164                         TimeSpan baseUtcOffset = new TimeSpan (0);
1165                         TimeSpan dstDelta = new TimeSpan (0);
1166                         string standardDisplayName = null;
1167                         string daylightDisplayName = null;
1168                         bool dst_observed = false;
1169                         DateTime dst_start = DateTime.MinValue;
1170                         List<AdjustmentRule> adjustmentRules = new List<AdjustmentRule> ();
1171                         bool storeTransition = false;
1172
1173                         for (int i = 0; i < transitions.Count; i++) {
1174                                 var pair = transitions [i];
1175                                 DateTime ttime = pair.Key;
1176                                 TimeType ttype = pair.Value;
1177                                 if (!ttype.IsDst) {
1178                                         if (standardDisplayName != ttype.Name)
1179                                                 standardDisplayName = ttype.Name;
1180                                         if (baseUtcOffset.TotalSeconds != ttype.Offset) {
1181                                                 baseUtcOffset = new TimeSpan (0, 0, ttype.Offset);
1182                                                 if (adjustmentRules.Count > 0) // We ignore AdjustmentRules but store transitions.
1183                                                         storeTransition = true;
1184                                                 adjustmentRules = new List<AdjustmentRule> ();
1185                                                 dst_observed = false;
1186                                         }
1187                                         if (dst_observed) {
1188                                                 //FIXME: check additional fields for this:
1189                                                 //most of the transitions are expressed in GMT 
1190                                                 dst_start += baseUtcOffset;
1191                                                 DateTime dst_end = ttime + baseUtcOffset + dstDelta;
1192
1193                                                 //some weird timezone (America/Phoenix) have end dates on Jan 1st
1194                                                 if (dst_end.Date == new DateTime (dst_end.Year, 1, 1) && dst_end.Year > dst_start.Year)
1195                                                         dst_end -= new TimeSpan (24, 0, 0);
1196
1197                                                 DateTime dateStart, dateEnd;
1198                                                 if (dst_start.Month < 7)
1199                                                         dateStart = new DateTime (dst_start.Year, 1, 1);
1200                                                 else
1201                                                         dateStart = new DateTime (dst_start.Year, 7, 1);
1202
1203                                                 if (dst_end.Month >= 7)
1204                                                         dateEnd = new DateTime (dst_end.Year, 12, 31);
1205                                                 else
1206                                                         dateEnd = new DateTime (dst_end.Year, 6, 30);
1207
1208                                                 
1209                                                 TransitionTime transition_start = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_start.TimeOfDay, dst_start.Month, dst_start.Day);
1210                                                 TransitionTime transition_end = TransitionTime.CreateFixedDateRule (new DateTime (1, 1, 1) + dst_end.TimeOfDay, dst_end.Month, dst_end.Day);
1211                                                 if  (transition_start != transition_end) //y, that happened in Argentina in 1943-1946
1212                                                         adjustmentRules.Add (AdjustmentRule.CreateAdjustmentRule (dateStart, dateEnd, dstDelta, transition_start, transition_end));
1213                                         }
1214                                         dst_observed = false;
1215                                 } else {
1216                                         if (daylightDisplayName != ttype.Name)
1217                                                 daylightDisplayName = ttype.Name;
1218                                         if (dstDelta.TotalSeconds != ttype.Offset - baseUtcOffset.TotalSeconds)
1219                                                 dstDelta = new TimeSpan(0, 0, ttype.Offset) - baseUtcOffset;
1220
1221                                         dst_start = ttime;
1222                                         dst_observed = true;
1223                                 }
1224                         }
1225
1226                         TimeZoneInfo tz;
1227                         if (adjustmentRules.Count == 0 && !storeTransition) {
1228                                 TimeType t = (TimeType)time_types [0];
1229                                 if (standardDisplayName == null) {
1230                                         standardDisplayName = t.Name;
1231                                         baseUtcOffset = new TimeSpan (0, 0, t.Offset);
1232                                 }
1233                                 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName);
1234                         } else {
1235                                 tz = CreateCustomTimeZone (id, baseUtcOffset, id, standardDisplayName, daylightDisplayName, ValidateRules (adjustmentRules).ToArray ());
1236                         }
1237
1238                         if (storeTransition)
1239                                 tz.transitions = transitions;
1240
1241                         return tz;
1242                 }
1243
1244                 static Dictionary<int, string> ParseAbbreviations (byte [] buffer, int index, int count)
1245                 {
1246                         var abbrevs = new Dictionary<int, string> ();
1247                         int abbrev_index = 0;
1248                         var sb = new StringBuilder ();
1249                         for (int i = 0; i < count; i++) {
1250                                 char c = (char) buffer [index + i];
1251                                 if (c != '\0')
1252                                         sb.Append (c);
1253                                 else {
1254                                         abbrevs.Add (abbrev_index, sb.ToString ());
1255                                         //Adding all the substrings too, as it seems to be used, at least for Africa/Windhoek
1256                                         for (int j = 1; j < sb.Length; j++)
1257                                                 abbrevs.Add (abbrev_index + j, sb.ToString (j, sb.Length - j));
1258                                         abbrev_index = i + 1;
1259                                         sb = new StringBuilder ();
1260                                 }
1261                         }
1262                         return abbrevs;
1263                 }
1264
1265                 static Dictionary<int, TimeType> ParseTimesTypes (byte [] buffer, int index, int count, Dictionary<int, string> abbreviations)
1266                 {
1267                         var types = new Dictionary<int, TimeType> (count);
1268                         for (int i = 0; i < count; i++) {
1269                                 int offset = ReadBigEndianInt32 (buffer, index + 6 * i);
1270                                 byte is_dst = buffer [index + 6 * i + 4];
1271                                 byte abbrev = buffer [index + 6 * i + 5];
1272                                 types.Add (i, new TimeType (offset, (is_dst != 0), abbreviations [(int)abbrev]));
1273                         }
1274                         return types;
1275                 }
1276
1277                 static List<KeyValuePair<DateTime, TimeType>> ParseTransitions (byte [] buffer, int index, int count, Dictionary<int, TimeType> time_types)
1278                 {
1279                         var list = new List<KeyValuePair<DateTime, TimeType>> (count);
1280                         for (int i = 0; i < count; i++) {
1281                                 int unixtime = ReadBigEndianInt32 (buffer, index + 4 * i);
1282                                 DateTime ttime = DateTimeFromUnixTime (unixtime);
1283                                 byte ttype = buffer [index + 4 * count + i];
1284                                 list.Add (new KeyValuePair<DateTime, TimeType> (ttime, time_types [(int)ttype]));
1285                         }
1286                         return list;
1287                 }
1288
1289                 static DateTime DateTimeFromUnixTime (long unix_time)
1290                 {
1291                         DateTime date_time = new DateTime (1970, 1, 1);
1292                         return date_time.AddSeconds (unix_time);
1293                 }
1294         }
1295
1296         struct TimeType {
1297                 public readonly int Offset;
1298                 public readonly bool IsDst;
1299                 public string Name;
1300
1301                 public TimeType (int offset, bool is_dst, string abbrev)
1302                 {
1303                         this.Offset = offset;
1304                         this.IsDst = is_dst;
1305                         this.Name = abbrev;
1306                 }
1307
1308                 public override string ToString ()
1309                 {
1310                         return "offset: " + Offset + "s, is_dst: " + IsDst + ", zone name: " + Name;
1311                 }
1312 #else
1313         }
1314 #endif
1315         }
1316 }
1317
1318 #endif