Debian Codegraph @

time/date/tzdb.ha

raw
1 // SPDX-License-Identifier: MPL-2.0
2 // (c) Hare authors <https://harelang.org>
3
4 use bufio;
5 use bytes;
6 use encoding::utf8;
7 use endian;
8 use errors;
9 use fs;
10 use io;
11 use os;
12 use path;
13 use strings;
14 use time;
15 use time::chrono;
16
17 // Error concerning the Timezone database.
18 export type tzdberror = !(invalidtzif | fs::error | io::error);
19
20 // Invalid TZif data.
21 export type invalidtzif = !void;
22
23 // Loads a [[timezone]] from the system's TZDB (Timezone Database) as a
24 // [[locality]]. Each call returns a new instance. The caller must free the
25 // return value. See [[timezone_free]].
26 //
27 // The given "TZID" shall be a TZDB identifier and acts as the relative filepath
28 // to a TZif (Time Zone Information Format) file under [[TZDB_PATH]].
29 // For example, "Europe/Amsterdam" for "/usr/share/zoneinfo/Europe/Amsterdam".
30 //
31 // The loaded timezones are assigned the TZID as its name, the
32 // [[time::chrono::utc]] timescale, and the [[EARTH_DAY]] day-length
33 export fn tzdb(tzid: str) (locality | tzdberror | nomem) = {
34 const filepath = match (path::init(TZDB_PATH, tzid)) {
35 case let buf: path::buffer =>
36 yield buf;
37 case let err: path::error =>
38 assert(err is path::too_long);
39 return errors::noentry: fs::error;
40 };
41 const file = os::open(path::string(&filepath))?;
42
43 static let buf: [os::BUFSZ]u8 = [0...];
44 const bufstrm = bufio::init(file, buf, []);
45
46 let ok = false;
47 let name = strings::dup(tzid)?;
48 defer if (!ok) free(name);
49 let loc = alloc(timezone {
50 tsc = &chrono::utc,
51 daylength = EARTH_DAY,
52 petz = PETZ_EMPTY,
53 name = name,
54 ...
55 })?;
56 defer if (!ok) free(loc);
57 match (load_tzif(&bufstrm, loc)) {
58 case void =>
59 io::close(&bufstrm)?;
60 io::close(file)?;
61 ok = true;
62 return loc;
63 case invalidtzif =>
64 _ = io::close(&bufstrm);
65 _ = io::close(file);
66 return invalidtzif;
67 case let err: io::error =>
68 _ = io::close(&bufstrm);
69 _ = io::close(file);
70 return err;
71 };
72 };
73
74 // Loads TZif (Time Zone Information Format) data onto a given [[timezone]],
75 // initializing the fields ".phases", ".transitions", and ".petz".
76 //
77 // Refer to "RFC 8536" for the TZif format.
78 export fn load_tzif(h: io::handle, tz: *timezone) (void | invalidtzif | io::error | nomem) = {
79 const buf1: [1]u8 = [0...];
80 const buf4: [4]u8 = [0...];
81 const buf8: [8]u8 = [0...];
82 const buf15: [15]u8 = [0...];
83 let ok = false;
84
85 // test for magic "TZif"
86 mustread(h, buf4)?;
87 if (!bytes::equal(buf4, ['T', 'Z', 'i', 'f'])) {
88 return invalidtzif;
89 };
90
91 // read version
92 mustread(h, buf1)?;
93 const version = switch (buf1[0]) {
94 case 0 =>
95 yield 1;
96 case '2' =>
97 yield 2;
98 case '3' =>
99 yield 3;
100 case =>
101 return invalidtzif;
102 };
103
104 // skip padding
105 mustread(h, buf15)?;
106
107 // read counts
108 mustread(h, buf4)?; let isutcnt = endian::begetu32(buf4);
109 mustread(h, buf4)?; let isstdcnt = endian::begetu32(buf4);
110 mustread(h, buf4)?; let leapcnt = endian::begetu32(buf4);
111 mustread(h, buf4)?; let timecnt = endian::begetu32(buf4);
112 mustread(h, buf4)?; let typecnt = endian::begetu32(buf4);
113 mustread(h, buf4)?; let charcnt = endian::begetu32(buf4);
114
115 let is64 = false;
116 if (version > 1) {
117 is64 = true;
118
119 // skip to the version 2 data
120 const skip = (
121 // size of version 1 data block
122 timecnt * 4
123 + timecnt
124 + typecnt * 6
125 + charcnt
126 + leapcnt * 8
127 + isstdcnt
128 + isutcnt
129 // size of version 2 header
130 + 20
131 );
132 for (let i = 0z; i < skip; i += 1) {
133 mustread(h, buf1)?;
134 };
135
136 // read version 2 counts
137 mustread(h, buf4)?; isutcnt = endian::begetu32(buf4);
138 mustread(h, buf4)?; isstdcnt = endian::begetu32(buf4);
139 mustread(h, buf4)?; leapcnt = endian::begetu32(buf4);
140 mustread(h, buf4)?; timecnt = endian::begetu32(buf4);
141 mustread(h, buf4)?; typecnt = endian::begetu32(buf4);
142 mustread(h, buf4)?; charcnt = endian::begetu32(buf4);
143 };
144
145 if (typecnt == 0 || charcnt == 0) {
146 return invalidtzif;
147 };
148
149 if (!(isutcnt == 0 || isutcnt == typecnt)
150 && (isstdcnt == 0 && isstdcnt == typecnt)) {
151 return invalidtzif;
152 };
153
154 const timesz = if (is64) 8 else 4;
155
156 // read data
157
158 const transition_times: []i64 = [];
159 if (is64) {
160 readitems8(h, &transition_times, timecnt)?;
161 } else {
162 readitems4(h, &transition_times, timecnt)?;
163 };
164 defer free(transition_times);
165 const zone_indicies: []u8 = [];
166 defer free(zone_indicies);
167 readbytes(h, &zone_indicies, timecnt)?;
168 const zonedata: []u8 = [];
169 defer free(zonedata);
170 readbytes(h, &zonedata, typecnt * 6)?;
171 const abbrdata: []u8 = [];
172 defer free(abbrdata);
173 readbytes(h, &abbrdata, charcnt)?;
174 const leapdata: []u8 = [];
175 defer free(leapdata);
176 readbytes(h, &leapdata, leapcnt * (timesz: u32 + 4))?;
177 const stdwalldata: []u8 = [];
178 defer free(stdwalldata);
179 readbytes(h, &stdwalldata, isstdcnt)?;
180 const normlocaldata: []u8 = [];
181 defer free(normlocaldata);
182 readbytes(h, &normlocaldata, isutcnt)?;
183 // read footer
184
185 let footerdata: []u8 = [];
186 defer free(footerdata);
187 mustread(h, buf1)?;
188 if (buf1[0] != 0x0A) { // '\n' newline
189 return invalidtzif;
190 };
191 for (true) {
192 mustread(h, buf1)?;
193 if (buf1[0] == 0x0A) { // '\n' newline
194 break;
195 };
196 if (buf1[0] == 0x0) { // cannot contain NUL
197 return invalidtzif;
198 };
199 append(footerdata, buf1...)?;
200 };
201 const petz = match (strings::fromutf8(footerdata)) {
202 case let s: str =>
203 yield s;
204 case utf8::invalid =>
205 return invalidtzif;
206 };
207
208 // assemble structured data
209
210 // assemble zones
211 let zones: []zonephase = [];
212 defer if (!ok) free(zones);
213 for (let i = 0z; i < typecnt; i += 1) {
214 const idx = i * 6;
215 const zone = zonephase { ... };
216
217 // offset
218 const zoff = endian::begetu32(zonedata[idx..idx + 4]): i32;
219 if (zoff == -2147483648) { // -2^31
220 return invalidtzif;
221 };
222 zone.zoff = zoff * time::SECOND;
223
224 // daylight saving time indicator
225 zone.dst = switch (zonedata[idx + 4]) {
226 case 1u8 =>
227 yield true;
228 case 0u8 =>
229 yield false;
230 case =>
231 return invalidtzif;
232 };
233
234 // abbreviation
235 const abbridx = zonedata[idx + 5];
236 if (abbridx < 0 || abbridx > (charcnt - 1)) {
237 return invalidtzif;
238 };
239 let bytes: []u8 = [];
240 for (let j = abbridx; j < len(abbrdata); j += 1) {
241 if (abbrdata[j] == 0x0) {
242 bytes = abbrdata[abbridx..j];
243 break;
244 };
245 };
246 if (len(bytes) == 0) { // no NUL encountered
247 return invalidtzif;
248 };
249 const abbr = match (strings::fromutf8(bytes)) {
250 case let s: str =>
251 yield s;
252 case utf8::invalid =>
253 return invalidtzif;
254 };
255 zone.abbr = strings::dup(abbr)?;
256
257 if (append(zones, zone) is nomem) {
258 free(zone.abbr);
259 return nomem;
260 };
261 };
262
263 // assemble transitions
264 let transitions: []zonetransition = [];
265 defer if (!ok) free(transitions);
266
267 for (let i = 0z; i < timecnt; i += 1) {
268 const zoneindex = zone_indicies[i];
269 if (zoneindex < 0 || zoneindex > (typecnt - 1)) {
270 return invalidtzif;
271 };
272
273 const tx = zonetransition {
274 when = time::instant {
275 sec = transition_times[i],
276 ...
277 },
278 zoneindex = zoneindex,
279 };
280
281 // stdwalldata and normlocaldata have been omitted,
282 // until they show their utility.
283
284 append(transitions, tx)?;
285 };
286
287 // save and return data
288 tz.phases = zones;
289 tz.transitions = transitions;
290
291 if (parse_petz(&tz.petz, petz) is invalidpetzstr) {
292 return invalidtzif;
293 };
294
295 ok = true;
296 };
297
298 fn mustread(h: io::handle, buf: []u8) (void | invalidtzif | io::error) = {
299 match (io::readall(h, buf)) {
300 case let err: io::error =>
301 return err;
302 case io::EOF =>
303 return invalidtzif;
304 case size =>
305 return;
306 };
307 };
308
309 fn readbytes(
310 h: io::handle,
311 items: *[]u8,
312 n: size,
313 ) (void | invalidtzif | io::error | nomem) = {
314 const buf: [1]u8 = [0];
315 for (let i = 0z; i < n; i += 1) {
316 mustread(h, buf)?;
317 const it = buf[0];
318 append(items, it)?;
319 };
320 };
321
322 fn readitems8(
323 h: io::handle,
324 items: *[]i64,
325 n: size,
326 ) (void | invalidtzif | io::error | nomem) = {
327 const buf: [8]u8 = [0...];
328 for (let i = 0z; i < n; i += 1) {
329 mustread(h, buf)?;
330 const it = endian::begetu64(buf): i64;
331 append(items, it)?;
332 };
333 };
334
335 fn readitems4(
336 h: io::handle,
337 items: *[]i64,
338 n: size,
339 ) (void | invalidtzif | io::error | nomem) = {
340 const buf: [4]u8 = [0...];
341 for (let i = 0z; i < n; i += 1) {
342 mustread(h, buf)?;
343 const it = endian::begetu32(buf): i64;
344 append(items, it)?;
345 };
346 };