blob: 3d35d4f4b463f8d0dcff7ff9040560757d58ffe8 [file] [log] [blame]
Paul Ganssle62972d92020-05-16 04:20:06 -04001import struct
2
3
4def load_tzdata(key):
5 import importlib.resources
6
7 components = key.split("/")
8 package_name = ".".join(["tzdata.zoneinfo"] + components[:-1])
9 resource_name = components[-1]
10
11 try:
12 return importlib.resources.open_binary(package_name, resource_name)
13 except (ImportError, FileNotFoundError, UnicodeEncodeError):
14 # There are three types of exception that can be raised that all amount
15 # to "we cannot find this key":
16 #
17 # ImportError: If package_name doesn't exist (e.g. if tzdata is not
18 # installed, or if there's an error in the folder name like
19 # Amrica/New_York)
20 # FileNotFoundError: If resource_name doesn't exist in the package
21 # (e.g. Europe/Krasnoy)
22 # UnicodeEncodeError: If package_name or resource_name are not UTF-8,
23 # such as keys containing a surrogate character.
24 raise ZoneInfoNotFoundError(f"No time zone found with key {key}")
25
26
27def load_data(fobj):
28 header = _TZifHeader.from_file(fobj)
29
30 if header.version == 1:
31 time_size = 4
32 time_type = "l"
33 else:
34 # Version 2+ has 64-bit integer transition times
35 time_size = 8
36 time_type = "q"
37
38 # Version 2+ also starts with a Version 1 header and data, which
39 # we need to skip now
40 skip_bytes = (
41 header.timecnt * 5 # Transition times and types
42 + header.typecnt * 6 # Local time type records
43 + header.charcnt # Time zone designations
44 + header.leapcnt * 8 # Leap second records
45 + header.isstdcnt # Standard/wall indicators
46 + header.isutcnt # UT/local indicators
47 )
48
49 fobj.seek(skip_bytes, 1)
50
51 # Now we need to read the second header, which is not the same
52 # as the first
53 header = _TZifHeader.from_file(fobj)
54
55 typecnt = header.typecnt
56 timecnt = header.timecnt
57 charcnt = header.charcnt
58
59 # The data portion starts with timecnt transitions and indices
60 if timecnt:
61 trans_list_utc = struct.unpack(
62 f">{timecnt}{time_type}", fobj.read(timecnt * time_size)
63 )
64 trans_idx = struct.unpack(f">{timecnt}B", fobj.read(timecnt))
65 else:
66 trans_list_utc = ()
67 trans_idx = ()
68
69 # Read the ttinfo struct, (utoff, isdst, abbrind)
70 if typecnt:
71 utcoff, isdst, abbrind = zip(
72 *(struct.unpack(">lbb", fobj.read(6)) for i in range(typecnt))
73 )
74 else:
75 utcoff = ()
76 isdst = ()
77 abbrind = ()
78
79 # Now read the abbreviations. They are null-terminated strings, indexed
80 # not by position in the array but by position in the unsplit
81 # abbreviation string. I suppose this makes more sense in C, which uses
82 # null to terminate the strings, but it's inconvenient here...
83 char_total = 0
84 abbr_vals = {}
85 abbr_chars = fobj.read(charcnt)
86
87 def get_abbr(idx):
88 # Gets a string starting at idx and running until the next \x00
89 #
90 # We cannot pre-populate abbr_vals by splitting on \x00 because there
91 # are some zones that use subsets of longer abbreviations, like so:
92 #
93 # LMT\x00AHST\x00HDT\x00
94 #
95 # Where the idx to abbr mapping should be:
96 #
97 # {0: "LMT", 4: "AHST", 5: "HST", 9: "HDT"}
98 if idx not in abbr_vals:
99 span_end = abbr_chars.find(b"\x00", idx)
100 abbr_vals[idx] = abbr_chars[idx:span_end].decode()
101
102 return abbr_vals[idx]
103
104 abbr = tuple(get_abbr(idx) for idx in abbrind)
105
106 # The remainder of the file consists of leap seconds (currently unused) and
107 # the standard/wall and ut/local indicators, which are metadata we don't need.
108 # In version 2 files, we need to skip the unnecessary data to get at the TZ string:
109 if header.version >= 2:
110 # Each leap second record has size (time_size + 4)
111 skip_bytes = header.isutcnt + header.isstdcnt + header.leapcnt * 12
112 fobj.seek(skip_bytes, 1)
113
114 c = fobj.read(1) # Should be \n
115 assert c == b"\n", c
116
117 tz_bytes = b""
118 while (c := fobj.read(1)) != b"\n":
119 tz_bytes += c
120
121 tz_str = tz_bytes
122 else:
123 tz_str = None
124
125 return trans_idx, trans_list_utc, utcoff, isdst, abbr, tz_str
126
127
128class _TZifHeader:
129 __slots__ = [
130 "version",
131 "isutcnt",
132 "isstdcnt",
133 "leapcnt",
134 "timecnt",
135 "typecnt",
136 "charcnt",
137 ]
138
139 def __init__(self, *args):
140 assert len(self.__slots__) == len(args)
141 for attr, val in zip(self.__slots__, args):
142 setattr(self, attr, val)
143
144 @classmethod
145 def from_file(cls, stream):
146 # The header starts with a 4-byte "magic" value
147 if stream.read(4) != b"TZif":
148 raise ValueError("Invalid TZif file: magic not found")
149
150 _version = stream.read(1)
151 if _version == b"\x00":
152 version = 1
153 else:
154 version = int(_version)
155 stream.read(15)
156
157 args = (version,)
158
159 # Slots are defined in the order that the bytes are arranged
160 args = args + struct.unpack(">6l", stream.read(24))
161
162 return cls(*args)
163
164
165class ZoneInfoNotFoundError(KeyError):
166 """Exception raised when a ZoneInfo key is not found."""