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