xref: /PHP-8.1/ext/date/lib/timelib.h (revision 0747616f)
1 /*
2  * The MIT License (MIT)
3  *
4  * Copyright (c) 2015-2022 Derick Rethans
5  * Copyright (c) 2018,2021 MongoDB, Inc.
6  *
7  * Permission is hereby granted, free of charge, to any person obtaining a copy
8  * of this software and associated documentation files (the "Software"), to deal
9  * in the Software without restriction, including without limitation the rights
10  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11  * copies of the Software, and to permit persons to whom the Software is
12  * furnished to do so, subject to the following conditions:
13  *
14  * The above copyright notice and this permission notice shall be included in
15  * all copies or substantial portions of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23  * THE SOFTWARE.
24  */
25 
26 #ifndef __TIMELIB_H__
27 #define __TIMELIB_H__
28 
29 #ifdef HAVE_TIMELIB_CONFIG_H
30 # include "timelib_config.h"
31 #endif
32 
33 #define TIMELIB_VERSION 202119
34 #define TIMELIB_EXTENDED_VERSION 20211901
35 #define TIMELIB_ASCII_VERSION "2021.19"
36 
37 #include <stdlib.h>
38 #include <stdbool.h>
39 #include <limits.h>
40 #include <inttypes.h>
41 
42 # ifndef HAVE_INT32_T
43 #  if SIZEOF_INT == 4
44 typedef int int32_t;
45 #  elif SIZEOF_LONG == 4
46 typedef long int int32_t;
47 #  endif
48 # endif
49 
50 # ifndef HAVE_UINT32_T
51 #  if SIZEOF_INT == 4
52 typedef unsigned int uint32_t;
53 #  elif SIZEOF_LONG == 4
54 typedef unsigned long int uint32_t;
55 #  endif
56 # endif
57 
58 #ifdef _WIN32
59 # if _MSC_VER >= 1600
60 # include <stdint.h>
61 # endif
62 # ifndef SIZEOF_INT
63 #  define SIZEOF_INT 4
64 # endif
65 # ifndef SIZEOF_LONG
66 #  define SIZEOF_LONG 4
67 # endif
68 # ifndef int32_t
69 typedef __int32           int32_t;
70 # endif
71 # ifndef uint32_t
72 typedef unsigned __int32  uint32_t;
73 # endif
74 # ifndef int64_t
75 typedef __int64           int64_t;
76 # endif
77 # ifndef uint64_t
78 typedef unsigned __int64  uint64_t;
79 # endif
80 # ifndef PRId32
81 #  define PRId32       "I32d"
82 # endif
83 # ifndef PRIu32
84 #  define PRIu32       "I32u"
85 # endif
86 # ifndef PRId64
87 #  define PRId64       "I64d"
88 # endif
89 # ifndef PRIu64
90 #  define PRIu64       "I64u"
91 # endif
92 # ifndef INT32_MAX
93 #define INT32_MAX    _I32_MAX
94 # endif
95 # ifndef INT32_MIN
96 #define INT32_MIN    ((int32_t)_I32_MIN)
97 # endif
98 # ifndef UINT32_MAX
99 #define UINT32_MAX   _UI32_MAX
100 # endif
101 # ifndef INT64_MIN
102 #define INT64_MIN    ((int64_t)_I64_MIN)
103 # endif
104 # ifndef INT64_MAX
105 #define INT64_MAX    _I64_MAX
106 # endif
107 # ifndef UINT64_MAX
108 #define UINT64_MAX   _UI64_MAX
109 # endif
110 #endif
111 
112 #if (defined(__x86_64__) || defined(__LP64__) || defined(_LP64) || defined(_WIN64)) && !defined(TIMELIB_FORCE_LONG32)
113 typedef int64_t timelib_long;
114 typedef uint64_t timelib_ulong;
115 # define TIMELIB_LONG_MAX INT64_MAX
116 # define TIMELIB_LONG_MIN INT64_MIN
117 # define TIMELIB_ULONG_MAX UINT64_MAX
118 # define TIMELIB_LONG_FMT "%" PRId64
119 # define TIMELIB_ULONG_FMT "%" PRIu64
120 #else
121 typedef int32_t timelib_long;
122 typedef uint32_t timelib_ulong;
123 # define TIMELIB_LONG_MAX INT32_MAX
124 # define TIMELIB_LONG_MIN INT32_MIN
125 # define TIMELIB_ULONG_MAX UINT32_MAX
126 # define TIMELIB_LONG_FMT "%" PRId32
127 # define TIMELIB_ULONG_FMT "%" PRIu32
128 #endif
129 
130 #if defined(_MSC_VER)
131 typedef uint64_t timelib_ull;
132 typedef int64_t timelib_sll;
133 # define TIMELIB_LL_CONST(n) n ## i64
134 #else
135 typedef unsigned long long timelib_ull;
136 typedef signed long long timelib_sll;
137 # define TIMELIB_LL_CONST(n) n ## ll
138 #endif
139 
140 typedef struct _ttinfo ttinfo;
141 typedef struct _tlinfo tlinfo;
142 
143 typedef struct _tlocinfo
144 {
145 	char country_code[3];
146 	double latitude;
147 	double longitude;
148 	char *comments;
149 } tlocinfo;
150 
151 #define TIMELIB_POSIX_TRANS_TYPE_JULIAN_NO_FEB29   1
152 #define TIMELIB_POSIX_TRANS_TYPE_JULIAN_FEB29      2
153 #define TIMELIB_POSIX_TRANS_TYPE_MWD               3
154 
155 typedef struct _timelib_posix_trans_info
156 {
157 	int type; // 1=Jn, 2=n, 3=Mm.w.d
158 	union {
159 		int days;
160 		struct {
161 			int month;
162 			int week;
163 			int dow;
164 		} mwd;
165 	};
166 	int hour;
167 } timelib_posix_trans_info;
168 
169 typedef struct _timelib_posix_str
170 {
171 	char        *std;
172 	timelib_sll  std_offset;
173 	char        *dst;
174 	timelib_sll  dst_offset;
175 
176 	timelib_posix_trans_info *dst_begin;
177 	timelib_posix_trans_info *dst_end;
178 
179 	int type_index_std_type;  // index into tz->type
180 	int type_index_dst_type;  // index into tz->type
181 } timelib_posix_str;
182 
183 typedef struct _timelib_posix_transitions {
184 	size_t      count;
185 	timelib_sll times[6];
186 	timelib_sll types[6];
187 } timelib_posix_transitions;
188 
189 typedef struct _timelib_tzinfo
190 {
191 	char    *name;
192 	struct {
193 		uint32_t ttisgmtcnt;
194 		uint32_t ttisstdcnt;
195 		uint32_t leapcnt;
196 		uint32_t timecnt;
197 		uint32_t typecnt;
198 		uint32_t charcnt;
199 	} _bit32;
200 	struct {
201 		uint64_t ttisgmtcnt;
202 		uint64_t ttisstdcnt;
203 		uint64_t leapcnt;
204 		uint64_t timecnt;
205 		uint64_t typecnt;
206 		uint64_t charcnt;
207 	} bit64;
208 
209 	int64_t *trans;
210 	unsigned char *trans_idx;
211 
212 	ttinfo  *type;
213 	char    *timezone_abbr;
214 
215 	tlinfo  *leap_times;
216 	unsigned char bc;
217 	tlocinfo location;
218 
219 	char              *posix_string;
220 	timelib_posix_str *posix_info;
221 } timelib_tzinfo;
222 
223 typedef struct _timelib_rel_time {
224 	timelib_sll y, m, d; /* Years, Months and Days */
225 	timelib_sll h, i, s; /* Hours, mInutes and Seconds */
226 	timelib_sll us;      /* Microseconds */
227 
228 	int weekday; /* Stores the day in 'next monday' */
229 	int weekday_behavior; /* 0: the current day should *not* be counted when advancing forwards; 1: the current day *should* be counted */
230 
231 	int first_last_day_of;
232 	int invert; /* Whether the difference should be inverted */
233 	timelib_sll days; /* Contains the number of *days*, instead of Y-M-D differences */
234 
235 	struct {
236 		unsigned int type;
237 		timelib_sll amount;
238 	} special;
239 
240 	unsigned int   have_weekday_relative, have_special_relative;
241 } timelib_rel_time;
242 
243 typedef struct _timelib_time_offset {
244 	int32_t      offset;
245 	unsigned int leap_secs;
246 	unsigned int is_dst;
247 	char        *abbr;
248 	timelib_sll  transition_time;
249 } timelib_time_offset;
250 
251 typedef struct _timelib_time {
252 	timelib_sll      y, m, d;     /* Year, Month, Day */
253 	timelib_sll      h, i, s;     /* Hour, mInute, Second */
254 	timelib_sll      us;          /* Microseconds */
255 	int              z;           /* UTC offset in seconds */
256 	char            *tz_abbr;     /* Timezone abbreviation (display only) */
257 	timelib_tzinfo  *tz_info;     /* Timezone structure */
258 	signed int       dst;         /* Flag if we were parsing a DST zone */
259 	timelib_rel_time relative;
260 
261 	timelib_sll      sse;         /* Seconds since epoch */
262 
263 	unsigned int   have_time, have_date, have_zone, have_relative, have_weeknr_day;
264 
265 	unsigned int   sse_uptodate; /* !0 if the sse member is up to date with the date/time members */
266 	unsigned int   tim_uptodate; /* !0 if the date/time members are up to date with the sse member */
267 	unsigned int   is_localtime; /*  1 if the current struct represents localtime, 0 if it is in GMT */
268 	unsigned int   zone_type;    /*  1 time offset,
269 	                              *  3 TimeZone identifier,
270 	                              *  2 TimeZone abbreviation */
271 } timelib_time;
272 
273 typedef struct _timelib_abbr_info {
274 	timelib_sll  utc_offset;
275 	char        *abbr;
276 	int          dst;
277 } timelib_abbr_info;
278 
279 #define TIMELIB_WARN_MASK                      0x1ff
280 #define TIMELIB_ERR_MASK                       0x2ff
281 
282 #define TIMELIB_WARN_DOUBLE_TZ                 0x101
283 #define TIMELIB_WARN_INVALID_TIME              0x102
284 #define TIMELIB_WARN_INVALID_DATE              0x103
285 #define TIMELIB_WARN_TRAILING_DATA             0x11a
286 
287 #define TIMELIB_ERR_DOUBLE_TZ                  0x201
288 #define TIMELIB_ERR_TZID_NOT_FOUND             0x202
289 #define TIMELIB_ERR_DOUBLE_TIME                0x203
290 #define TIMELIB_ERR_DOUBLE_DATE                0x204
291 #define TIMELIB_ERR_UNEXPECTED_CHARACTER       0x205
292 #define TIMELIB_ERR_EMPTY_STRING               0x206
293 #define TIMELIB_ERR_UNEXPECTED_DATA            0x207
294 #define TIMELIB_ERR_NO_TEXTUAL_DAY             0x208
295 #define TIMELIB_ERR_NO_TWO_DIGIT_DAY           0x209
296 #define TIMELIB_ERR_NO_THREE_DIGIT_DAY_OF_YEAR 0x20a
297 #define TIMELIB_ERR_NO_TWO_DIGIT_MONTH         0x20b
298 #define TIMELIB_ERR_NO_TEXTUAL_MONTH           0x20c
299 #define TIMELIB_ERR_NO_TWO_DIGIT_YEAR          0x20d
300 #define TIMELIB_ERR_NO_FOUR_DIGIT_YEAR         0x20e
301 #define TIMELIB_ERR_NO_TWO_DIGIT_HOUR          0x20f
302 #define TIMELIB_ERR_HOUR_LARGER_THAN_12        0x210
303 #define TIMELIB_ERR_MERIDIAN_BEFORE_HOUR       0x211
304 #define TIMELIB_ERR_NO_MERIDIAN                0x212
305 #define TIMELIB_ERR_NO_TWO_DIGIT_MINUTE        0x213
306 #define TIMELIB_ERR_NO_TWO_DIGIT_SECOND        0x214
307 #define TIMELIB_ERR_NO_SIX_DIGIT_MICROSECOND   0x215
308 #define TIMELIB_ERR_NO_SEP_SYMBOL              0x216
309 #define TIMELIB_ERR_EXPECTED_ESCAPE_CHAR       0x217
310 #define TIMELIB_ERR_NO_ESCAPED_CHAR            0x218
311 #define TIMELIB_ERR_WRONG_FORMAT_SEP           0x219
312 #define TIMELIB_ERR_TRAILING_DATA              0x21a
313 #define TIMELIB_ERR_DATA_MISSING               0x21b
314 #define TIMELIB_ERR_NO_THREE_DIGIT_MILLISECOND 0x21c
315 #define TIMELIB_ERR_NO_FOUR_DIGIT_YEAR_ISO     0x21d
316 #define TIMELIB_ERR_NO_TWO_DIGIT_WEEK          0x21e
317 #define TIMELIB_ERR_INVALID_WEEK               0x21f
318 #define TIMELIB_ERR_NO_DAY_OF_WEEK             0x220
319 #define TIMELIB_ERR_INVALID_DAY_OF_WEEK        0x221
320 #define TIMELIB_ERR_INVALID_SPECIFIER          0x222
321 #define TIMELIB_ERR_INVALID_TZ_OFFSET          0x223
322 #define TIMELIB_ERR_FORMAT_LITERAL_MISMATCH    0x224
323 #define TIMELIB_ERR_MIX_ISO_WITH_NATURAL       0x225
324 
325 #define TIMELIB_ZONETYPE_NONE   0
326 #define TIMELIB_ZONETYPE_OFFSET 1
327 #define TIMELIB_ZONETYPE_ABBR   2
328 #define TIMELIB_ZONETYPE_ID     3
329 
330 typedef struct _timelib_error_message {
331 	int         error_code;
332 	int         position;
333 	char        character;
334 	char       *message;
335 } timelib_error_message;
336 
337 typedef struct _timelib_error_container {
338 	timelib_error_message *error_messages;
339 	timelib_error_message *warning_messages;
340 	int                    error_count;
341 	int                    warning_count;
342 } timelib_error_container;
343 
344 typedef struct _timelib_tz_lookup_table {
345 	const char *name;
346 	int         type;
347 	float       gmtoffset;
348 	const char *full_tz_name;
349 } timelib_tz_lookup_table;
350 
351 typedef struct _timelib_tzdb_index_entry {
352 	char *id;
353 	unsigned int pos;
354 } timelib_tzdb_index_entry;
355 
356 typedef struct _timelib_tzdb {
357 	const char                     *version;
358 	int                             index_size;
359 	const timelib_tzdb_index_entry *index;
360 	const unsigned char            *data;
361 } timelib_tzdb;
362 
363 #ifndef timelib_malloc
364 # define timelib_malloc  malloc
365 # define timelib_realloc realloc
366 # define timelib_calloc  calloc
367 # define timelib_strdup  strdup
368 # define timelib_free    free
369 # if defined(WIN32) || defined(_WIN32) || defined(__WIN32) && !defined(__CYGWIN__)
370 #  define TIMELIB_USE_BUILTIN_STRNDUP 1
371 # else
372 #  define TIMELIB_USE_BUILTIN_STRNDUP 0
373 #  define timelib_strndup strndup
374 # endif
375 #endif
376 
377 #define TIMELIB_NONE             0x00
378 #define TIMELIB_OVERRIDE_TIME    0x01
379 #define TIMELIB_NO_CLONE         0x02
380 
381 #define TIMELIB_UNSET   -9999999
382 
383 /* An entry for each of these error codes is also in the
384  * timelib_error_messages array in timelib.c.
385  * Codes 0x00, 0x07, and 0x09 are warnings only. */
386 #define TIMELIB_ERROR_NO_ERROR                            0x00
387 #define TIMELIB_ERROR_CANNOT_ALLOCATE                     0x01
388 #define TIMELIB_ERROR_CORRUPT_TRANSITIONS_DONT_INCREASE   0x02
389 #define TIMELIB_ERROR_CORRUPT_NO_64BIT_PREAMBLE           0x03
390 #define TIMELIB_ERROR_CORRUPT_NO_ABBREVIATION             0x04
391 #define TIMELIB_ERROR_UNSUPPORTED_VERSION                 0x05
392 #define TIMELIB_ERROR_NO_SUCH_TIMEZONE                    0x06
393 #define TIMELIB_ERROR_SLIM_FILE                           0x07 /* Warns if the file is SLIM, but we can't read it */
394 #define TIMELIB_ERROR_CORRUPT_POSIX_STRING                0x08
395 #define TIMELIB_ERROR_EMPTY_POSIX_STRING                  0x09 /* Warns if the POSIX string is empty, but still produces results */
396 
397 #ifdef __cplusplus
398 extern "C" {
399 #endif
400 
401 typedef enum _timelib_format_specifier_code {
402 	TIMELIB_FORMAT_ALLOW_EXTRA_CHARACTERS = 0,
403 	TIMELIB_FORMAT_ANY_SEPARATOR,
404 	TIMELIB_FORMAT_DAY_TWO_DIGIT,
405 	TIMELIB_FORMAT_DAY_TWO_DIGIT_PADDED,
406 	TIMELIB_FORMAT_DAY_OF_WEEK_ISO,
407 	TIMELIB_FORMAT_DAY_OF_WEEK,
408 	TIMELIB_FORMAT_DAY_OF_YEAR,
409 	TIMELIB_FORMAT_DAY_SUFFIX,
410 	TIMELIB_FORMAT_END,
411 	TIMELIB_FORMAT_EPOCH_SECONDS,
412 	TIMELIB_FORMAT_ESCAPE,
413 	TIMELIB_FORMAT_HOUR_TWO_DIGIT_12_MAX,
414 	TIMELIB_FORMAT_HOUR_TWO_DIGIT_12_MAX_PADDED,
415 	TIMELIB_FORMAT_HOUR_TWO_DIGIT_24_MAX,
416 	TIMELIB_FORMAT_HOUR_TWO_DIGIT_24_MAX_PADDED,
417 	TIMELIB_FORMAT_LITERAL,
418 	TIMELIB_FORMAT_MERIDIAN,
419 	TIMELIB_FORMAT_MICROSECOND_SIX_DIGIT,
420 	TIMELIB_FORMAT_MILLISECOND_THREE_DIGIT,
421 	TIMELIB_FORMAT_MINUTE_TWO_DIGIT,
422 	TIMELIB_FORMAT_MONTH_TWO_DIGIT,
423 	TIMELIB_FORMAT_MONTH_TWO_DIGIT_PADDED,
424 	TIMELIB_FORMAT_RANDOM_CHAR,
425 	TIMELIB_FORMAT_RESET_ALL,
426 	TIMELIB_FORMAT_RESET_ALL_WHEN_NOT_SET,
427 	TIMELIB_FORMAT_SECOND_TWO_DIGIT,
428 	TIMELIB_FORMAT_SEPARATOR,
429 	TIMELIB_FORMAT_SKIP_TO_SEPARATOR,
430 	TIMELIB_FORMAT_TEXTUAL_DAY_3_LETTER,
431 	TIMELIB_FORMAT_TEXTUAL_DAY_FULL,
432 	TIMELIB_FORMAT_TEXTUAL_MONTH_3_LETTER,
433 	TIMELIB_FORMAT_TEXTUAL_MONTH_FULL,
434 	TIMELIB_FORMAT_TIMEZONE_OFFSET,
435 	TIMELIB_FORMAT_TIMEZONE_OFFSET_MINUTES,
436 	TIMELIB_FORMAT_WEEK_OF_YEAR_ISO,
437 	TIMELIB_FORMAT_WEEK_OF_YEAR,
438 	TIMELIB_FORMAT_WHITESPACE,
439 	TIMELIB_FORMAT_YEAR_TWO_DIGIT,
440 	TIMELIB_FORMAT_YEAR_FOUR_DIGIT,
441 	TIMELIB_FORMAT_YEAR_ISO
442 } timelib_format_specifier_code;
443 
444 typedef struct _timelib_format_specifier {
445 	char                          specifier;
446 	timelib_format_specifier_code code;
447 } timelib_format_specifier;
448 
449 typedef struct _timelib_format_config {
450 	const timelib_format_specifier *format_map;
451 	/* Format speciifiers must be preceded by 'prefix_char' if not '\0'. */
452 	char                            prefix_char;
453 } timelib_format_config;
454 
455 /* Function pointers */
456 typedef timelib_tzinfo* (*timelib_tz_get_wrapper)(const char *tzname, const timelib_tzdb *tzdb, int *error_code);
457 
458 /* From dow.c */
459 /* Calculates the day of the week from y, m, and d. 0=Sunday..6=Saturday */
460 timelib_sll timelib_day_of_week(timelib_sll y, timelib_sll m, timelib_sll d);
461 
462 /* Calculates the day of the ISO week from y, m, and d. 1=Monday, 7=Sunday */
463 timelib_sll timelib_iso_day_of_week(timelib_sll y, timelib_sll m, timelib_sll d);
464 
465 /* Calculates the day of the year according to y-m-d. 0=Jan 1st..364/365=Dec
466  * 31st */
467 timelib_sll timelib_day_of_year(timelib_sll y, timelib_sll m, timelib_sll d);
468 
469 /* Calculates the day of the year according to y-w-dow. 0..364/365 */
470 timelib_sll timelib_daynr_from_weeknr(timelib_sll iy, timelib_sll iw, timelib_sll id);
471 
472 /* Calculates the number of days in month m for year y. 28..31 */
473 timelib_sll timelib_days_in_month(timelib_sll y, timelib_sll m);
474 
475 /* Calculates the ISO year and week from y, m, and d, into iw and iy */
476 void timelib_isoweek_from_date(timelib_sll y, timelib_sll m, timelib_sll d, timelib_sll *iw, timelib_sll *iy);
477 
478 /* Calculates the ISO year, week, and day of week from y, m, and d, into iy,
479  * iw, and id */
480 void timelib_isodate_from_date(timelib_sll y, timelib_sll m, timelib_sll d, timelib_sll *iy, timelib_sll *iw, timelib_sll *id);
481 
482 /* Calculates the year, month, and day from iy, iw, and iw, into y, m, and d */
483 void timelib_date_from_isodate(timelib_sll iy, timelib_sll iw, timelib_sll id, timelib_sll *y, timelib_sll *m, timelib_sll *d);
484 
485 /* Returns true if h, i and s fit in the range 00:00:00..23:59:59, false
486  * otherwise */
487 int timelib_valid_time(timelib_sll h, timelib_sll i, timelib_sll s);
488 
489 /* Returns true if m fits in the range 1..12, and d fits in the range
490  * 1..<days-in-month> for year y */
491 int timelib_valid_date(timelib_sll y, timelib_sll m, timelib_sll d);
492 
493 /* From parse_date.re */
494 
495 /* Parses the date/time string in 's' with length 'len' into the constituent
496  * parts of timelib_time*.
497  *
498  * Depending on the contents of the string 's', not all elements might be
499  * filled. You can check whether a specific element has been parsed by
500  * comparing with the TIMELIB_UNSET define.
501  *
502  * If errors occur, this function keeps already parsed elements in the
503  * returned timelib_time* value.
504  *
505  * If the **errors points to a timelib_error_container variable, warnings
506  * and errors will be recorded. You are responsible for freeing the stored
507  * information with timelib_error_container_dtor(). To see whether errors have
508  * occurred, inspect errors->errors_count. To see whether warnings have occurred,
509  * inspect errors->warnings_count.
510  *
511  * The returned timelib_time* value is dynamically allocated and should be
512  * freed with timelib_time_dtor().
513  */
514 timelib_time *timelib_strtotime(const char *s, size_t len, timelib_error_container **errors, const timelib_tzdb *tzdb, timelib_tz_get_wrapper tz_get_wrapper);
515 
516 /* Parses the date/time string in 's' with length 'len' into the constituent
517  * parts of timelib_time* according to the format in 'format'.
518  *
519  * Depending on the contents of the string 's', not all elements might be
520  * filled. You can check whether a specific element has been parsed by
521  * comparing with the TIMELIB_UNSET define.
522  *
523  * If errors occur, this function keeps already parsed elements in the
524  * returned timelib_time* value.
525  *
526  * If the **errors points to a timelib_error_container variable, warnings
527  * and errors will be recorded. You are responsible for freeing the stored
528  * information with timelib_error_container_dtor(). To see whether errors have
529  * occurred, inspect errors->errors_count. To see whether warnings have occurred,
530  * inspect errors->warnings_count.
531  *
532  * The returned timelib_time* value is dynamically allocated and should be
533  * freed with timelib_time_dtor().
534  */
535 timelib_time *timelib_parse_from_format(const char *format, const char *s, size_t len, timelib_error_container **errors, const timelib_tzdb *tzdb, timelib_tz_get_wrapper tz_get_wrapper);
536 
537 /* Parses the date/time string in 's' with length 'len' into the constituent
538  * parts of timelib_time* according to the format in 'format' with format
539  * specifier configuration 'format_config'.
540  *
541  * 'format_map' is an array of pairs, with the first element being the format
542  * specifier as a character and the second element corresponds to the
543  * representation of the specifier from the enum list
544  * 'timelib_format_specifier_code'.
545  *
546  * Note: 'format_map' must be terminated with specifier '\0' to indicate to the
547  * parser that there are no more format specifiers in the list.
548  */
549 timelib_time *timelib_parse_from_format_with_map(const char *format, const char *s, size_t len, timelib_error_container **errors, const timelib_tzdb *tzdb, timelib_tz_get_wrapper tz_get_wrapper, const timelib_format_config* format_config);
550 
551 /* Fills the gaps in the parsed timelib_time with information from the reference date/time in 'now'
552  *
553  * If any of the 'parsed' y, m, d, h, i or s parameters is unset (TIMELIB_UNSET):
554  * - if microtime (us) is unset, then the us of the parsed time is set to 0.
555  * - else if microtime (us) is unset and 'now'->'us' is set, use it, otherwise use 0.
556  *
557  * For either of the 'parsed' y, m, d, h, i, s, z (utc offset in seconds) or
558  * dst is unset, set it to the corresponding value in 'now' if set, otherwise
559  * set it to 0.
560  *
561  * It duplicates tz_abbr if unset in 'parsed' but set in 'now'.
562  *
563  * It duplicates tz_info if unset in 'parsed', but set in 'now' unless
564  * TIMELIB_NO_CLONE is passed, in which case only the pointer in 'parsed' is
565  * set to 'now'.
566  *
567  * If the option TIMELIB_OVERRIDE_TIME is passed and the parsed date/time has
568  * no time portion, the function will ignore the time aspect in 'now' and
569  * instead fill it with zeros.
570  */
571 void timelib_fill_holes(timelib_time *parsed, timelib_time *now, int options);
572 
573 /* Tries to convert a time zone abbreviation, gmtoffset and/or isdst flag
574  * combination to a time zone identifier.
575  *
576  * If 'abbr' is either 'utc' or 'gmt' (case insensitve) then "UTC" is
577  * returned.
578  *
579  * It first uses the data in the timezonemap.h file to find a matching
580  * abbreviation/GMT offset combination. If not found, it uses the data in
581  * fallbackmap.h to match only the GMT offset/isdst flag to try to find a
582  * match. If nothing is found, NULL is returned.
583  *
584  * The returned char* is not duplicated, and should not be freed.
585  */
586 const char *timelib_timezone_id_from_abbr(const char *abbr, timelib_long gmtoffset, int isdst);
587 
588 /* Returns an array of known time zone abbreviations
589  *
590  * This file is generated from the time zone database through the
591  * gettzmapping.php scripts, which requires that an up-to-date time zone
592  * database is used with the PHP binary that runs the script.
593  *
594  * Each item in the returned list contains the abbreviation, a flag whether
595  * it's an abbreviation used with DST, the UTC offset in seconds, and the name
596  * of the time zone identifier that this abbreviation belongs to.
597  *
598  * The order for each specific abbreviation is controlled through the
599  * preference list in the gettzmapping.php script. Time zones that match the
600  * pattern ±\d{2,4} are excluded
601  */
602 const timelib_tz_lookup_table *timelib_timezone_abbreviations_list(void);
603 
604 /**
605  * DEPRECATED, but still used by PHP.
606  */
607 timelib_long timelib_parse_zone(const char **ptr, int *dst, timelib_time *t, int *tz_not_found, const timelib_tzdb *tzdb, timelib_tz_get_wrapper tz_wrapper);
608 
609 /* From parse_iso_intervals.re */
610 
611 /**
612  * Parses a subset of an ISO 8601 intervals specification string into its
613  * constituent parts.
614  *
615  * If the **errors points to a timelib_error_container variable, warnings
616  * and errors will be recorded. You are responsible for freeing the stored
617  * information with timelib_error_container_dtor(). To see whether errors have
618  * occurred, inspect errors->errors_count. To see whether warnings have occurred,
619  * inspect errors->warnings_count.
620  */
621 void timelib_strtointerval(const char *s, size_t len,
622                            timelib_time **begin, timelib_time **end,
623                            timelib_rel_time **period, int *recurrences,
624                            timelib_error_container **errors);
625 
626 
627 /* From tm2unixtime.c */
628 
629 /**
630  * Uses the y/m/d/h/i/s fields to calculate and store the equivalent timestamp
631  * in the sse field.
632  *
633  * It uses the time zone information associated with 'time' to account for the
634  * right UTC offset and/or DST rules. You can associate time zone information
635  * with the timelib_set_timezone_* functions (see below).
636  *
637  * If the type is 'TIMELIB_ZONETYPE_ID' and there is no associated tzinfo, it
638  * will use the second argument 'tzi' to provide the rules necessary to
639  * calculate the right timestamp.
640  */
641 void timelib_update_ts(timelib_time* time, timelib_tzinfo* tzi);
642 
643 /**
644  * Returns the number of days from the y/m/d fields of 'time' since the Unix
645  * Epoch.
646  */
647 timelib_sll timelib_epoch_days_from_time(timelib_time *time);
648 
649 /**
650  * Takes the information from the y/m/d/h/i/s fields and makes sure their
651  * values are in the right range.
652  *
653  * If a value under- or overflows it will adjust the larger measure up (or
654  * down). It also takes into account leap days.
655  */
656 void timelib_do_normalize(timelib_time *base);
657 
658 /**
659  * Takes the information from the y/m/d/h/i/s fields of 'rt' and makes sure
660  * their values are in the right range.
661  *
662  * If a value under- or overflows it will adjust the larger measure up (or
663  * down). As this function operates on a *relative date/time*, it also takes
664  * into account leap days and correctly accounts for the difference depending
665  * on the base date/time in 'base'.
666  */
667 void timelib_do_rel_normalize(timelib_time *base, timelib_rel_time *rt);
668 
669 /* From unixtime2tm.c */
670 
671 /**
672  * Takes the unix timestamp in seconds from 'ts', and calculates y, m, and d,
673  * in the proleptic Gregorian calendar.
674  *
675  * It uses the algorithm from howardhinnant.github.io/date_algorithms.html
676  */
677 void timelib_unixtime2date(timelib_sll ts, timelib_sll *y, timelib_sll *m, timelib_sll *d);
678 
679 /**
680  * Takes the unix timestamp in seconds from 'ts' and populates the y/m/d/h/i/s
681  * fields of 'tm' without taking time zones into account
682  */
683 void timelib_unixtime2gmt(timelib_time* tm, timelib_sll ts);
684 
685 /**
686  * Takes the Unix timestamp from 'ts', and calculates the y/m/d/h/i/s fields
687  * according to the time zone information attached to 'tm'.
688  */
689 void timelib_unixtime2local(timelib_time *tm, timelib_sll ts);
690 
691 /**
692  * Takes the Unix timestamp stored in 'tm', and calculates the y/m/d/h/i/s
693  * fields according to the time zone information attached to 'tm'.
694  */
695 void timelib_update_from_sse(timelib_time *tm);
696 
697 /**
698  * Attaches the UTC offset as time zone information to 't'.
699  *
700  * 'utc_offset' is in seconds East of UTC.
701  */
702 void timelib_set_timezone_from_offset(timelib_time *t, timelib_sll utc_offset);
703 
704 /**
705  * Attaches the information from 'abbr_info' as time zone information to 't'.
706  *
707  * The timelib_abbr_info struct contains an abbreviation ('abbr') which string
708  * value is duplicated, as well as a 'utc_offset' and 'dst' flag. It only
709  * supports a 'dst' change over of 1 hour.
710  */
711 void timelib_set_timezone_from_abbr(timelib_time *t, timelib_abbr_info abbr_info);
712 
713 /**
714  * Attaches the time zone information in 'tz' to to 't'.
715  *
716  * It fetches the right UTC offset that is currently stored in the time
717  * stamp field in 't' ('sse'), and assigns that to the 'z' field and 'dst'
718  * field (whether DST is in effect at the time). It also sets the current
719  * abbreviation to the 'tz_addr' field, making sure that if a value was already
720  * set it was freed.
721  *
722  * The time zone information in 'tz' is *not* duplicated into the 't' field so
723  * it should not be freed until all timelib_time* variables have been freed as
724  * well.
725  */
726 void timelib_set_timezone(timelib_time *t, timelib_tzinfo *tz);
727 
728 /* From parse_tz.c */
729 
730 /**
731  * Returns whether the time zone ID 'timezone' is available in the time zone
732  * database as pointed to be 'tzdb'.
733  */
734 int timelib_timezone_id_is_valid(const char *timezone, const timelib_tzdb *tzdb);
735 
736 /**
737  * Converts the binary stored time zone information from 'tzdb' for the time
738  * zone 'timezone' into a structure the library can use for calculations.
739  *
740  * The function can be used on both timelib_builtin_db as well as a time zone
741  * db as opened by timelib_zoneinfo.
742  *
743  * 'error_code' must not be a null pointer, and will always be written to. If
744  * the value is TIMELIB_ERROR_NO_ERROR then the file was parsed without
745  * problems.
746  *
747  * The function will return null upon failure, and also set an error code
748  * through 'error_code'.
749  *
750  * The error code is one of the TIMELIB_ERROR_* constants as listed above.
751  * These error constants can be converted into a string by
752  * timelib_get_error_message.
753  *
754  * If the function returns not-null, the 'error_code' might have a non-null
755  * value that can be used to detect incompatibilities. The only one that is
756  * currently detected is whether the file is a 'slim' file, in which case
757  * 'error_code' will be set to TIMELIB_ERROR_SLIM_FILE.
758  *
759  * This function allocates memory for the new time zone structure, which must
760  * be freed after use. Although it is recommended that a cache of each used
761  * time zone is kept.
762  */
763 timelib_tzinfo *timelib_parse_tzfile(const char *timezone, const timelib_tzdb *tzdb, int *error_code);
764 
765 /**
766  * Frees up the resources allocated by 'timelib_parse_tzfile'.
767  */
768 void timelib_tzinfo_dtor(timelib_tzinfo *tz);
769 
770 /**
771  * Deep-clones a timelib_tzinfo structure.
772  *
773  * This allocates resources that need to be freed with 'timelib_tzinfo_dtor'
774  */
775 timelib_tzinfo* timelib_tzinfo_clone(timelib_tzinfo *tz);
776 
777 /**
778  * Returns whether DST is active with time zone 'tz' for the time stamp 'ts'.
779  *
780  * Returns 0 if DST is not active, 1 if DST is active, or -1 if no transitions
781  * were available through 'tz'.
782  */
783 int timelib_timestamp_is_in_dst(timelib_sll ts, timelib_tzinfo *tz);
784 
785 /**
786  * Returns offset information with time zone 'tz' for the time stamp 'ts'.
787  *
788  * The returned information contains: the offset in seconds East of UTC (in
789  * 'offset'), whether DST is active ('is_dst'), what the current time zone
790  * abbreviation is ('abbr') and the transition time that got to this state (in
791  * 'transition_time');
792  */
793 timelib_time_offset *timelib_get_time_zone_info(timelib_sll ts, timelib_tzinfo *tz);
794 
795 /**
796  * Returns the UTC offset currently applicable for the information stored in 't'.
797  *
798  * The value returned is the UTC offset in seconds East.
799  */
800 timelib_sll timelib_get_current_offset(timelib_time *t);
801 
802 /**
803  * Returns whether the timezone information in *one and *two are the same
804  *
805  * A timezone is considered the same if:
806  * - the ->zone_type values are the same for *one and *two
807  * - for TYPE_ABBR and TYPE_OFFSET, ->z + (->dst * 3600), is the same
808  * - for TYPE_ID, the zone's names are the same
809  */
810 int timelib_same_timezone(timelib_time *one, timelib_time *two);
811 
812 /**
813  * Displays debugging information about the time zone information in 'tz'.
814  */
815 void timelib_dump_tzinfo(timelib_tzinfo *tz);
816 
817 /**
818  * Returns a pointer to the built-in time zone database.
819  *
820  * You must *not* free the returned pointer as it is part of the text segment.
821  */
822 const timelib_tzdb *timelib_builtin_db(void);
823 
824 /**
825  * Returns a pointer to the start of an array containing a list of timezone identifiers.
826  *
827  * The amount of entries in the array is returned through the 'count' OUT parameter.
828  *
829  * Each entry contains the time zone ID ('id' field), and the position within the time zone
830  * information ('pos' field). The pos field should not be used.
831  */
832 const timelib_tzdb_index_entry *timelib_timezone_identifiers_list(const timelib_tzdb *tzdb, int *count);
833 
834 /* From parse_zoneinfo.c */
835 
836 /**
837  * Scans the directory and subdirectories of 'directory' for valid time zone files and builds
838  * a time zone database out of these files.
839  *
840  * Typically, the directory should point to '/usr/share/zoneinfo'.
841  *
842  * Unlike 'timelib_builtin_db', the return value of this function must be freed
843  * with the 'timelib_zoneinfo_dtor' function.
844  */
845 timelib_tzdb *timelib_zoneinfo(const char *directory);
846 
847 /**
848  * Frees up the resources as created through 'timelib_zoneinfo'.
849  *
850  * This function must be used to free up all the resources that have been
851  * allocated while calling 'timelib_zoneinfo'.
852  */
853 void timelib_zoneinfo_dtor(timelib_tzdb *tzdb);
854 
855 /* From timelib.c */
856 
857 /**
858  * Returns a static string containing an error message belonging to a specific
859  * error code.
860  */
861 const char *timelib_get_error_message(int error_code);
862 
863 /**
864  * Allocates resources for the relative time structure.
865  *
866  * Must be freed with 'timelib_rel_time_dtor'.
867  */
868 timelib_rel_time* timelib_rel_time_ctor(void);
869 
870 /**
871  * Frees up the resources as allocated through 'timelib_rel_time_ctor'.
872  */
873 void timelib_rel_time_dtor(timelib_rel_time* t);
874 
875 /**
876  * Creates a new timelib_rel_time resource and copies over the information
877  * from 'tz'.
878  *
879  * Must be freed with 'timelib_rel_time_dtor'.
880  */
881 timelib_rel_time* timelib_rel_time_clone(timelib_rel_time *tz);
882 
883 /**
884  * Allocates resources for the time structure.
885  *
886  * Must be freed with 'timelib_time_dtor'.
887  */
888 timelib_time* timelib_time_ctor(void);
889 
890 /**
891  * Frees up the resources as allocated through 'timelib_time_ctor'.
892  */
893 void timelib_time_dtor(timelib_time* t);
894 
895 /**
896  * Creates a new timelib_time resource and copies over the information
897  * from 'orig'.
898  *
899  * Must be freed with 'timelib_time_dtor'.
900  */
901 timelib_time* timelib_time_clone(timelib_time* orig);
902 
903 /**
904  * Compares two timelib_time structures and returns which one is earlier in
905  * time.
906  *
907  * To decide which comes earlier it uses the 'sse' (Seconds Since Epoch) and
908  * 'us' (microseconds) fields.
909  *
910  * Returns -1 if t1 < t2, 0 if t1 == t2, and -1 if t1 > t2.
911  */
912 int timelib_time_compare(timelib_time *t1, timelib_time *t2);
913 
914 /**
915  * Allocates resources for the time offset structure.
916  *
917  * Must be freed with 'timelib_time_offset_dtor'.
918  */
919 timelib_time_offset* timelib_time_offset_ctor(void);
920 
921 /**
922  * Frees up the resources as allocated through 'timelib_time_offset_ctor'.
923  */
924 void timelib_time_offset_dtor(timelib_time_offset* t);
925 
926 /**
927  * Frees up the resources allocated while converting strings to timelib_time
928  * structures with the timelib_strtotime and timelib_strtointerval functions.
929  */
930 void timelib_error_container_dtor(timelib_error_container *errors);
931 
932 /**
933  * Converts the 'sse' value of 'd' to a timelib_long type.
934  *
935  * If the value fits in the TIMELIB_LONG_MIN and TIMELIB_LONG_MAX range, the
936  * value is cast to (timelib_long) and returned. If *error is not a NULL
937  * pointer, it will be set to 0.
938  *
939  * If the value does *not* fit in the range, the function returns 0 and if
940  * *error is not a NULL pointer, it will be set to 1.
941  *
942  * timelib_long is a 32 bit signed long integer on 32 bit platforms, and a 64
943  * bit signed long long integer on 64 bit platforms. In other words, it makes
944  * sure that the value in 'sse' (which is always a signed long long 64 bit
945  * integer) can be used safely outside of the library.
946  */
947 timelib_long timelib_date_to_int(timelib_time *d, int *error);
948 
949 /**
950  * Displays debugging information about the date/time information stored in 'd'.
951  *
952  * 'options' is a bit field, where:
953  * - 1 controls whether the relative time portion is shown.
954  * - 2 controls whether the zone type is shown.
955  */
956 void timelib_dump_date(timelib_time *d, int options);
957 
958 /**
959  * Displays debugging information about the relative time information stored
960  * in 'd'.
961  */
962 void timelib_dump_rel_time(timelib_rel_time *d);
963 
964 /**
965  * Converts a decimal hour into hour/min/sec components
966  */
967 void timelib_decimal_hour_to_hms(double h, int *hour, int *min, int *sec);
968 
969 /**
970  * Converts hour/min/sec values into a decimal hour
971  */
972 void timelib_hms_to_decimal_hour(int hour, int min, int sec, double *h);
973 
974 /**
975  * Converts hour/min/sec/micro sec values into a decimal hour
976  */
977 void timelib_hmsf_to_decimal_hour(int hour, int min, int sec, int us, double *h);
978 
979 /**
980  * Converts hour/min/sec values into seconds
981  */
982 timelib_sll timelib_hms_to_seconds(timelib_sll h, timelib_sll m, timelib_sll s);
983 
984 
985 /* from astro.c */
986 
987 /**
988  * Converts the Unix Epoch time stamp 'ts' to a Julian Day
989  *
990  * The value returned is the number of whole days since -4714-11-24T12:00:00 UTC
991  * (in the proleptic Gregorian calendar):
992  * https://en.wikipedia.org/wiki/Julian_day
993  */
994 double timelib_ts_to_julianday(timelib_sll ts);
995 
996 /**
997  * Converts the Unix Epoch time stamp 'ts' to the J2000 epoch
998  *
999  * The value returned is the number of whole days since 2000-01-01T12:00:00
1000  * UTC: https://en.wikipedia.org/wiki/Epoch_(astronomy)#Julian_years_and_J2000
1001  */
1002 double timelib_ts_to_j2000(timelib_sll ts);
1003 
1004 /**
1005  * Calculates when the Sun is above a certain latitude.
1006  *
1007  * Parameters:
1008  * - time: A timelib_time time describing that needs to specific midnight for a
1009  *         specific day.
1010  * - lon: The longitude of the observer (East positive, West negative).
1011  * - lat: The latitude of the observer (North positive, South negative).
1012  * - altit: The altitude. Set to -35/60 for rise/set, -6 for civil twilight,
1013  *          -12 for nautical, and -18 for astronomical twilight.
1014  * - upper_limb: set to non-zero for rise/set calculations, and 0 for twilight
1015  *               calculations.
1016  *
1017  * Out Parameters:
1018  * - h_rise: The decimal hour when the Sun rises
1019  * - h_set: The decimal hour when the Sun sets
1020  * - ts_rise: The Unix timestamp of the Sun rising
1021  * - ts_set: The Unix timestamp of the Sun setting
1022  * - ts_transit: The Unix timestmap of the Sun transitting through South
1023  *
1024  * Return Values:
1025  * - 0: The Sun rises and sets.
1026  * - +1: The Sun is always above the horizon. (ts_rise is set to ts_transit -
1027  *       (12 * 3600); ts_set is set to ts_transit + (12 * 3600).
1028  * - -1: The Sun is awlays below the horizon. (ts_rise and ts_set are set
1029  *       to ts_transit)
1030  */
1031 int timelib_astro_rise_set_altitude(timelib_time *time, double lon, double lat, double altit, int upper_limb, double *h_rise, double *h_set, timelib_sll *ts_rise, timelib_sll *ts_set, timelib_sll *ts_transit);
1032 
1033 /* from interval.c */
1034 
1035 /**
1036  * Calculates the difference between two times
1037  *
1038  * The result is a timelib_rel_time structure that describes how you can
1039  * convert from 'one' to 'two' with 'timelib_add'. This does *not* necessarily
1040  * mean that you can go from 'two' to 'one' by using 'timelib_sub' due to the
1041  * way months and days are calculated.
1042  */
1043 timelib_rel_time *timelib_diff(timelib_time *one, timelib_time *two);
1044 
1045 /**
1046  * Calculates the difference in full days between two times
1047  *
1048  * The result is the number of full days between 'one' and 'two'. It does take
1049  * into account 23 and 25 hour (and variants) days when the zone_type
1050  * is TIMELIB_ZONETYPE_ID and have the same TZID for 'one' and 'two'.
1051  */
1052 int timelib_diff_days(timelib_time *one, timelib_time *two);
1053 
1054 /**
1055  * Adds the relative time information 'interval' to the base time 't'.
1056  *
1057  * This can be a relative time as created by 'timelib_diff', but also by more
1058  * complex statements such as "next workday".
1059  */
1060 timelib_time *timelib_add(timelib_time *t, timelib_rel_time *interval);
1061 timelib_time *timelib_add_wall(timelib_time *t, timelib_rel_time *interval);
1062 
1063 /**
1064  * Subtracts the relative time information 'interval' to the base time 't'.
1065  *
1066  * This can be a relative time as created by 'timelib_diff'. Unlike with
1067  * 'timelib_add', this does not support more complex statements such as "next
1068  * workday".
1069  */
1070 timelib_time *timelib_sub(timelib_time *t, timelib_rel_time *interval);
1071 timelib_time *timelib_sub_wall(timelib_time *t, timelib_rel_time *interval);
1072 
1073 /* from parse_posix.c */
1074 
1075 void timelib_posix_str_dtor(timelib_posix_str *ps);
1076 
1077 timelib_posix_str* timelib_parse_posix_str(const char *posix);
1078 
1079 /**
1080  * Calculate the two yearly to/from DST
1081  */
1082 void timelib_get_transitions_for_year(timelib_tzinfo *tz, timelib_sll year, timelib_posix_transitions *transitions);
1083 
1084 
1085 #ifdef __cplusplus
1086 } /* extern "C" */
1087 #endif
1088 
1089 #endif
1090