[PATCH v3 2/9] parse-time-string: add a date/time parser to notmuch
[notmuch-archives.git] / 7e / 1bf3e6e189667155f3b1df723208bc7be237ef
1 Return-Path: <jani@nikula.org>\r
2 X-Original-To: notmuch@notmuchmail.org\r
3 Delivered-To: notmuch@notmuchmail.org\r
4 Received: from localhost (localhost [127.0.0.1])\r
5         by olra.theworths.org (Postfix) with ESMTP id D1242431FC2\r
6         for <notmuch@notmuchmail.org>; Wed, 12 Sep 2012 14:28:00 -0700 (PDT)\r
7 X-Virus-Scanned: Debian amavisd-new at olra.theworths.org\r
8 X-Amavis-Alert: BAD HEADER SECTION, Duplicate header field: "References"\r
9 X-Spam-Flag: NO\r
10 X-Spam-Score: -0.7\r
11 X-Spam-Level: \r
12 X-Spam-Status: No, score=-0.7 tagged_above=-999 required=5\r
13         tests=[RCVD_IN_DNSWL_LOW=-0.7] autolearn=disabled\r
14 Received: from olra.theworths.org ([127.0.0.1])\r
15         by localhost (olra.theworths.org [127.0.0.1]) (amavisd-new, port 10024)\r
16         with ESMTP id n5J2ssKk+xIo for <notmuch@notmuchmail.org>;\r
17         Wed, 12 Sep 2012 14:27:48 -0700 (PDT)\r
18 Received: from mail-lb0-f181.google.com (mail-lb0-f181.google.com\r
19         [209.85.217.181]) (using TLSv1 with cipher RC4-SHA (128/128 bits))\r
20         (No client certificate requested)\r
21         by olra.theworths.org (Postfix) with ESMTPS id F2DC8431FD4\r
22         for <notmuch@notmuchmail.org>; Wed, 12 Sep 2012 14:27:38 -0700 (PDT)\r
23 Received: by mail-lb0-f181.google.com with SMTP id gk1so1587473lbb.26\r
24         for <notmuch@notmuchmail.org>; Wed, 12 Sep 2012 14:27:38 -0700 (PDT)\r
25 X-Google-DKIM-Signature: v=1; a=rsa-sha256; c=relaxed/relaxed;\r
26         d=google.com; s=20120113;\r
27         h=from:to:cc:subject:date:message-id:x-mailer:in-reply-to:references\r
28         :in-reply-to:references:mime-version:content-type\r
29         :content-transfer-encoding:x-gm-message-state;\r
30         bh=G7s4uncqdR20TGhJ6qrKuGzBKXtV67TnCDE4FyGQ1xY=;\r
31         b=M7S26ghUoqSjLTEgmTGWot/cKtloSi0dOATuhSYfCad/St6y2wiORSJYtfClPcHZpO\r
32         xaKPgiAEqTkIMo/vrd+xe0UvkzBkYDtQKi1Ad/0cnkJ12pq9m5P4dyQ7K0wRs65WXJND\r
33         WEjsLMSNHuGnPtV30qmWMg6xrSipjy3vPZ0ORudMR51YrgiSEJWH4VW0xiys+m2rJokT\r
34         8Wa7eqxORen/JmtY/DFHTXHYo+f+Nhx0p+jsuAKUyaYgY0MSnX4k6Fh5ckaGuExS3Zqf\r
35         WURSwtUWddzNsUW6NYEHS144hKCBaB0ZdN80Mer/Ug+LmCKUBcSWCAia1LTIFoheSQHM\r
36         cjNA==\r
37 Received: by 10.152.104.202 with SMTP id gg10mr3170658lab.56.1347485258483;\r
38         Wed, 12 Sep 2012 14:27:38 -0700 (PDT)\r
39 Received: from localhost (dsl-hkibrasgw4-fe51df00-27.dhcp.inet.fi.\r
40         [80.223.81.27])\r
41         by mx.google.com with ESMTPS id h8sm5528289lbi.13.2012.09.12.14.27.35\r
42         (version=SSLv3 cipher=OTHER); Wed, 12 Sep 2012 14:27:37 -0700 (PDT)\r
43 From: Jani Nikula <jani@nikula.org>\r
44 To: notmuch@notmuchmail.org,\r
45         David Bremner <david@tethera.net>\r
46 Subject: [PATCH v3 2/9] parse-time-string: add a date/time parser to notmuch\r
47 Date: Thu, 13 Sep 2012 00:27:19 +0300\r
48 Message-Id:\r
49  <89741ec9a9687fca8b30aa1a4877392d355dd3ce.1347484177.git.jani@nikula.org>\r
50 X-Mailer: git-send-email 1.7.9.5\r
51 In-Reply-To: <cover.1347484177.git.jani@nikula.org>\r
52 References: <cover.1347484177.git.jani@nikula.org>\r
53 In-Reply-To: <cover.1347484177.git.jani@nikula.org>\r
54 References: <cover.1347484177.git.jani@nikula.org>\r
55 MIME-Version: 1.0\r
56 Content-Type: text/plain; charset=UTF-8\r
57 Content-Transfer-Encoding: 8bit\r
58 X-Gm-Message-State:\r
59  ALoCoQkv2uQUr/+697gvV3JG4LJ8qQEYChkeE2nx+qRqPKS36fWYuk6kfosLFSXD/2/tfH5qMIYi\r
60 X-BeenThere: notmuch@notmuchmail.org\r
61 X-Mailman-Version: 2.1.13\r
62 Precedence: list\r
63 List-Id: "Use and development of the notmuch mail system."\r
64         <notmuch.notmuchmail.org>\r
65 List-Unsubscribe: <http://notmuchmail.org/mailman/options/notmuch>,\r
66         <mailto:notmuch-request@notmuchmail.org?subject=unsubscribe>\r
67 List-Archive: <http://notmuchmail.org/pipermail/notmuch>\r
68 List-Post: <mailto:notmuch@notmuchmail.org>\r
69 List-Help: <mailto:notmuch-request@notmuchmail.org?subject=help>\r
70 List-Subscribe: <http://notmuchmail.org/mailman/listinfo/notmuch>,\r
71         <mailto:notmuch-request@notmuchmail.org?subject=subscribe>\r
72 X-List-Received-Date: Wed, 12 Sep 2012 21:28:01 -0000\r
73 \r
74 Add a date/time parser to notmuch, to be used for adding date range\r
75 query support for notmuch lib later on. Add the parser to a directory\r
76 of its own to make it independent of the rest of the notmuch code\r
77 base.\r
78 \r
79 Signed-off-by: Jani Nikula <jani@nikula.org>\r
80 ---\r
81  Makefile                              |    2 +-\r
82  parse-time-string/Makefile            |    5 +\r
83  parse-time-string/Makefile.local      |   12 +\r
84  parse-time-string/README              |    9 +\r
85  parse-time-string/parse-time-string.c | 1484 +++++++++++++++++++++++++++++++++\r
86  parse-time-string/parse-time-string.h |   95 +++\r
87  6 files changed, 1606 insertions(+), 1 deletion(-)\r
88  create mode 100644 parse-time-string/Makefile\r
89  create mode 100644 parse-time-string/Makefile.local\r
90  create mode 100644 parse-time-string/README\r
91  create mode 100644 parse-time-string/parse-time-string.c\r
92  create mode 100644 parse-time-string/parse-time-string.h\r
93 \r
94 diff --git a/Makefile b/Makefile\r
95 index e5e2e3a..bb9c316 100644\r
96 --- a/Makefile\r
97 +++ b/Makefile\r
98 @@ -3,7 +3,7 @@\r
99  all:\r
100  \r
101  # List all subdirectories here. Each contains its own Makefile.local\r
102 -subdirs = compat completion emacs lib man util test\r
103 +subdirs = compat completion emacs lib man parse-time-string util test\r
104  \r
105  # We make all targets depend on the Makefiles themselves.\r
106  global_deps = Makefile Makefile.config Makefile.local \\r
107 diff --git a/parse-time-string/Makefile b/parse-time-string/Makefile\r
108 new file mode 100644\r
109 index 0000000..fa25832\r
110 --- /dev/null\r
111 +++ b/parse-time-string/Makefile\r
112 @@ -0,0 +1,5 @@\r
113 +all:\r
114 +       $(MAKE) -C .. all\r
115 +\r
116 +.DEFAULT:\r
117 +       $(MAKE) -C .. $@\r
118 diff --git a/parse-time-string/Makefile.local b/parse-time-string/Makefile.local\r
119 new file mode 100644\r
120 index 0000000..53534f3\r
121 --- /dev/null\r
122 +++ b/parse-time-string/Makefile.local\r
123 @@ -0,0 +1,12 @@\r
124 +dir := parse-time-string\r
125 +extra_cflags += -I$(srcdir)/$(dir)\r
126 +\r
127 +libparse-time-string_c_srcs := $(dir)/parse-time-string.c\r
128 +\r
129 +libparse-time-string_modules := $(libparse-time-string_c_srcs:.c=.o)\r
130 +\r
131 +$(dir)/libparse-time-string.a: $(libparse-time-string_modules)\r
132 +       $(call quiet,AR) rcs $@ $^\r
133 +\r
134 +SRCS := $(SRCS) $(libparse-time-string_c_srcs)\r
135 +CLEAN := $(CLEAN) $(libparse-time-string_modules) $(dir)/libparse-time-string.a\r
136 diff --git a/parse-time-string/README b/parse-time-string/README\r
137 new file mode 100644\r
138 index 0000000..300ff1f\r
139 --- /dev/null\r
140 +++ b/parse-time-string/README\r
141 @@ -0,0 +1,9 @@\r
142 +PARSE TIME STRING\r
143 +=================\r
144 +\r
145 +parse_time_string() is a date/time parser originally written for\r
146 +notmuch by Jani Nikula <jani@nikula.org>. However, there is nothing\r
147 +notmuch specific in it, and it should be kept reusable for other\r
148 +projects, and ready to be packaged on its own as needed. Please do not\r
149 +add dependencies on or references to anything notmuch specific. The\r
150 +parser should only depend on the C library.\r
151 diff --git a/parse-time-string/parse-time-string.c b/parse-time-string/parse-time-string.c\r
152 new file mode 100644\r
153 index 0000000..15cf686\r
154 --- /dev/null\r
155 +++ b/parse-time-string/parse-time-string.c\r
156 @@ -0,0 +1,1484 @@\r
157 +/*\r
158 + * parse time string - user friendly date and time parser\r
159 + * Copyright © 2012 Jani Nikula\r
160 + *\r
161 + * This program is free software: you can redistribute it and/or modify\r
162 + * it under the terms of the GNU General Public License as published by\r
163 + * the Free Software Foundation, either version 2 of the License, or\r
164 + * (at your option) any later version.\r
165 + *\r
166 + * This program is distributed in the hope that it will be useful,\r
167 + * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
168 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
169 + * GNU General Public License for more details.\r
170 + *\r
171 + * You should have received a copy of the GNU General Public License\r
172 + * along with this program.  If not, see <http://www.gnu.org/licenses/>.\r
173 + *\r
174 + * Author: Jani Nikula <jani@nikula.org>\r
175 + */\r
176 +\r
177 +#include <assert.h>\r
178 +#include <ctype.h>\r
179 +#include <errno.h>\r
180 +#include <limits.h>\r
181 +#include <stdio.h>\r
182 +#include <stdarg.h>\r
183 +#include <stdbool.h>\r
184 +#include <stdlib.h>\r
185 +#include <string.h>\r
186 +#include <strings.h>\r
187 +#include <time.h>\r
188 +#include <sys/time.h>\r
189 +#include <sys/types.h>\r
190 +\r
191 +#include "parse-time-string.h"\r
192 +\r
193 +/*\r
194 + * IMPLEMENTATION DETAILS\r
195 + *\r
196 + * At a high level, the parsing is done in two phases: 1) actual\r
197 + * parsing of the input string and storing the parsed data into\r
198 + * 'struct state', and 2) processing of the data in 'struct state'\r
199 + * according to current time (or provided reference time) and\r
200 + * rounding. This is evident in the main entry point function\r
201 + * parse_time_string().\r
202 + *\r
203 + * 1) The parsing phase - parse_input()\r
204 + *\r
205 + * Parsing is greedy and happens from left to right. The parsing is as\r
206 + * unambiguous as possible; only unambiguous date/time formats are\r
207 + * accepted. Redundant or contradictory absolute date/time in the\r
208 + * input (e.g. date specified multiple times/ways) is not\r
209 + * accepted. Relative date/time on the other hand just accumulates if\r
210 + * present multiple times (e.g. "5 days 5 days" just turns into 10\r
211 + * days).\r
212 + *\r
213 + * Parsing decisions are made on the input format, not value. For\r
214 + * example, "20/5/2005" fails because the recognized format here is\r
215 + * MM/D/YYYY, even though the values would suggest DD/M/YYYY.\r
216 + *\r
217 + * Parsing is mostly stateless in the sense that parsing decisions are\r
218 + * not made based on the values of previously parsed data, or whether\r
219 + * certain data is present in the first place. (There are a few\r
220 + * exceptions to the latter part, though, such as parsing of time zone\r
221 + * that would otherwise look like plain time.)\r
222 + *\r
223 + * When the parser encounters a number that is not greedily parsed as\r
224 + * part of a format, the interpretation is postponed until the next\r
225 + * token is parsed. The parser for the next token may consume the\r
226 + * previously postponed number. For example, when parsing "20 May" the\r
227 + * meaning of "20" is not known until "May" is parsed. If the parser\r
228 + * for the next token does not consume the postponed number, the\r
229 + * number is handled as a "lone" number before parser for the next\r
230 + * token finishes.\r
231 + *\r
232 + * 2) The processing phase - create_output()\r
233 + *\r
234 + * Once the parser in phase 1 has finished, 'struct state' contains\r
235 + * all the information from the input string, and it's no longer\r
236 + * needed. Since the parser does not even handle the concept of "now",\r
237 + * the processing initializes the fields referring to the current\r
238 + * date/time.\r
239 + *\r
240 + * If requested, the result is rounded towards past or future. The\r
241 + * idea behind rounding is to support parsing date/time ranges in an\r
242 + * obvious way. For example, for a range defined as two dates (without\r
243 + * time), one would typically want to have an inclusive range from the\r
244 + * beginning of start date to the end of the end date. The caller\r
245 + * would use rounding towards past in the start date, and towards\r
246 + * future in the end date.\r
247 + *\r
248 + * The absolute date and time is shifted by the relative date and\r
249 + * time, and time zone adjustments are made. Daylight saving time\r
250 + * (DST) is specifically *not* handled at all.\r
251 + *\r
252 + * Finally, the result is stored to time_t.\r
253 + */\r
254 +\r
255 +#define unused(x) x __attribute__ ((unused))\r
256 +\r
257 +/* XXX: Redefine these to add i18n support. The keyword table uses\r
258 + * N_() to mark strings to be translated; they are accessed\r
259 + * dynamically using _(). */\r
260 +#define _(s) (s)       /* i18n: define as gettext (s) */\r
261 +#define N_(s) (s)      /* i18n: define as gettext_noop (s) */\r
262 +\r
263 +#define ARRAY_SIZE(a) (sizeof (a) / sizeof (a[0]))\r
264 +\r
265 +/*\r
266 + * Field indices in the tm and set arrays of struct state.\r
267 + *\r
268 + * NOTE: There's some code that depends on the ordering of this enum.\r
269 + */\r
270 +enum field {\r
271 +    /* Keep SEC...YEAR in this order. */\r
272 +    TM_ABS_SEC,                /* seconds */\r
273 +    TM_ABS_MIN,                /* minutes */\r
274 +    TM_ABS_HOUR,       /* hours */\r
275 +    TM_ABS_MDAY,       /* day of the month */\r
276 +    TM_ABS_MON,                /* month */\r
277 +    TM_ABS_YEAR,       /* year */\r
278 +\r
279 +    TM_ABS_WDAY,       /* day of the week. special: may be relative */\r
280 +    TM_ABS_ISDST,      /* daylight saving time */\r
281 +\r
282 +    TM_AMPM,           /* am vs. pm */\r
283 +    TM_TZ,             /* timezone in minutes */\r
284 +\r
285 +    /* Keep SEC...YEAR in this order. */\r
286 +    TM_REL_SEC,                /* seconds relative to now */\r
287 +    TM_REL_MIN,                /* minutes ... */\r
288 +    TM_REL_HOUR,       /* hours ... */\r
289 +    TM_REL_DAY,                /* days ... */\r
290 +    TM_REL_MON,                /* months ... */\r
291 +    TM_REL_YEAR,       /* years ... */\r
292 +    TM_REL_WEEK,       /* weeks ... */\r
293 +\r
294 +    TM_NONE,           /* not a field */\r
295 +\r
296 +    TM_SIZE = TM_NONE,\r
297 +    TM_FIRST_ABS = TM_ABS_SEC,\r
298 +    TM_FIRST_REL = TM_REL_SEC,\r
299 +};\r
300 +\r
301 +/* Values for the set array of struct state. */\r
302 +enum field_set {\r
303 +    FIELD_UNSET,       /* The field has not been touched by parser. */\r
304 +    FIELD_SET,         /* The field has been set by parser. */\r
305 +    FIELD_NOW,         /* The field will be set to "now". */\r
306 +};\r
307 +\r
308 +static enum field\r
309 +next_abs_field (enum field field)\r
310 +{\r
311 +    /* NOTE: Depends on the enum ordering. */\r
312 +    return field < TM_ABS_YEAR ? field + 1 : TM_NONE;\r
313 +}\r
314 +\r
315 +static enum field\r
316 +abs_to_rel_field (enum field field)\r
317 +{\r
318 +    assert (field <= TM_ABS_YEAR);\r
319 +\r
320 +    /* NOTE: Depends on the enum ordering. */\r
321 +    return field + (TM_FIRST_REL - TM_FIRST_ABS);\r
322 +}\r
323 +\r
324 +/* Get epoch value for field. */\r
325 +static int\r
326 +field_epoch (enum field field)\r
327 +{\r
328 +    if (field == TM_ABS_MDAY || field == TM_ABS_MON)\r
329 +       return 1;\r
330 +    else if (field == TM_ABS_YEAR)\r
331 +       return 1970;\r
332 +    else\r
333 +       return 0;\r
334 +}\r
335 +\r
336 +/* The parsing state. */\r
337 +struct state {\r
338 +    int tm[TM_SIZE];                   /* parsed date and time */\r
339 +    enum field_set set[TM_SIZE];       /* set status of tm */\r
340 +\r
341 +    enum field last_field;     /* Previously set field. */\r
342 +    enum field next_field;     /* Next field for parse_postponed_number() */\r
343 +    char delim;\r
344 +\r
345 +    int postponed_length;      /* Number of digits in postponed value. */\r
346 +    int postponed_value;\r
347 +    char postponed_delim;      /* The delimiter preceding postponed number. */\r
348 +};\r
349 +\r
350 +/*\r
351 + * Helpers for postponed numbers.\r
352 + *\r
353 + * postponed_length is the number of digits in postponed value. 0\r
354 + * means there is no postponed number. -1 means there is a postponed\r
355 + * number, but it comes from a keyword, and it doesn't have digits.\r
356 + */\r
357 +static int\r
358 +get_postponed_length (struct state *state)\r
359 +{\r
360 +    return state->postponed_length;\r
361 +}\r
362 +\r
363 +/*\r
364 + * Consume a previously postponed number. Return true if a number was\r
365 + * in fact postponed, false otherwise. Store the postponed number's\r
366 + * value in *v, length in the input string in *n (or -1 if the number\r
367 + * was written out and parsed as a keyword), and the preceding\r
368 + * delimiter to *d.\r
369 + */\r
370 +static bool\r
371 +get_postponed_number (struct state *state, int *v, int *n, char *d)\r
372 +{\r
373 +    if (!state->postponed_length)\r
374 +       return false;\r
375 +\r
376 +    if (n)\r
377 +       *n = state->postponed_length;\r
378 +\r
379 +    if (v)\r
380 +       *v = state->postponed_value;\r
381 +\r
382 +    if (d)\r
383 +       *d = state->postponed_delim;\r
384 +\r
385 +    state->postponed_length = 0;\r
386 +    state->postponed_value = 0;\r
387 +    state->postponed_delim = 0;\r
388 +\r
389 +    return true;\r
390 +}\r
391 +\r
392 +/* Parse a previously postponed number if one exists. */\r
393 +static int parse_postponed_number (struct state *state, int v, int n, char d);\r
394 +static int\r
395 +handle_postponed_number (struct state *state, enum field next_field)\r
396 +{\r
397 +    int v = state->postponed_value;\r
398 +    int n = state->postponed_length;\r
399 +    char d = state->postponed_delim;\r
400 +    int r;\r
401 +\r
402 +    if (!n)\r
403 +       return 0;\r
404 +\r
405 +    state->postponed_value = 0;\r
406 +    state->postponed_length = 0;\r
407 +    state->postponed_delim = 0;\r
408 +\r
409 +    state->next_field = next_field;\r
410 +    r = parse_postponed_number (state, v, n, d);\r
411 +    state->next_field = TM_NONE;\r
412 +\r
413 +    return r;\r
414 +}\r
415 +\r
416 +/*\r
417 + * Postpone a number to be handled later. If one exists already,\r
418 + * handle it first. n may be -1 to indicate a keyword that has no\r
419 + * number length.\r
420 + */\r
421 +static int\r
422 +set_postponed_number (struct state *state, int v, int n)\r
423 +{\r
424 +    int r;\r
425 +    char d = state->delim;\r
426 +\r
427 +    /* Parse a previously postponed number, if any. */\r
428 +    r = handle_postponed_number (state, TM_NONE);\r
429 +    if (r)\r
430 +       return r;\r
431 +\r
432 +    state->postponed_length = n;\r
433 +    state->postponed_value = v;\r
434 +    state->postponed_delim = d;\r
435 +\r
436 +    return 0;\r
437 +}\r
438 +\r
439 +static void\r
440 +set_delim (struct state *state, char delim)\r
441 +{\r
442 +    state->delim = delim;\r
443 +}\r
444 +\r
445 +static void\r
446 +unset_delim (struct state *state)\r
447 +{\r
448 +    state->delim = 0;\r
449 +}\r
450 +\r
451 +/*\r
452 + * Field set/get/mod helpers.\r
453 + */\r
454 +\r
455 +/* Return true if field has been set. */\r
456 +static bool\r
457 +is_field_set (struct state *state, enum field field)\r
458 +{\r
459 +    assert (field < ARRAY_SIZE (state->tm));\r
460 +\r
461 +    return field < ARRAY_SIZE (state->set) &&\r
462 +          state->set[field] != FIELD_UNSET;\r
463 +}\r
464 +\r
465 +static void\r
466 +unset_field (struct state *state, enum field field)\r
467 +{\r
468 +    assert (field < ARRAY_SIZE (state->tm));\r
469 +\r
470 +    state->set[field] = FIELD_UNSET;\r
471 +    state->tm[field] = 0;\r
472 +}\r
473 +\r
474 +/*\r
475 + * Set field to value. A field can only be set once to ensure the\r
476 + * input does not contain redundant and potentially conflicting data.\r
477 + */\r
478 +static int\r
479 +set_field (struct state *state, enum field field, int value)\r
480 +{\r
481 +    int r;\r
482 +\r
483 +    assert (field < ARRAY_SIZE (state->tm));\r
484 +\r
485 +    /* Fields can only be set once. */\r
486 +    if (field < ARRAY_SIZE (state->set) && state->set[field] != FIELD_UNSET)\r
487 +       return -PARSE_TIME_ERR_ALREADYSET;\r
488 +\r
489 +    state->set[field] = FIELD_SET;\r
490 +\r
491 +    /* Parse postponed number, if any. */\r
492 +    r = handle_postponed_number (state, field);\r
493 +    if (r)\r
494 +       return r;\r
495 +\r
496 +    unset_delim (state);\r
497 +\r
498 +    state->tm[field] = value;\r
499 +    state->last_field = field;\r
500 +\r
501 +    return 0;\r
502 +}\r
503 +\r
504 +/*\r
505 + * Mark n fields in fields to be set to current date/time in the\r
506 + * specified time zone, or local timezone if not specified. The fields\r
507 + * will be initialized after parsing is complete and timezone is\r
508 + * known.\r
509 + */\r
510 +static int\r
511 +set_fields_to_now (struct state *state, enum field *fields, size_t n)\r
512 +{\r
513 +    size_t i;\r
514 +    int r;\r
515 +\r
516 +    for (i = 0; i < n; i++) {\r
517 +       r = set_field (state, fields[i], 0);\r
518 +       if (r)\r
519 +           return r;\r
520 +       state->set[fields[i]] = FIELD_NOW;\r
521 +    }\r
522 +\r
523 +    return 0;\r
524 +}\r
525 +\r
526 +/* Modify field by adding value to it. To be used on relative fields,\r
527 + * which can be modified multiple times (to accumulate). */\r
528 +static int\r
529 +mod_field (struct state *state, enum field field, int value)\r
530 +{\r
531 +    int r;\r
532 +\r
533 +    assert (field < ARRAY_SIZE (state->tm));   /* assert relative??? */\r
534 +\r
535 +    if (field < ARRAY_SIZE (state->set))\r
536 +       state->set[field] = FIELD_SET;\r
537 +\r
538 +    /* Parse postponed number, if any. */\r
539 +    r = handle_postponed_number (state, field);\r
540 +    if (r)\r
541 +       return r;\r
542 +\r
543 +    unset_delim (state);\r
544 +\r
545 +    state->tm[field] += value;\r
546 +    state->last_field = field;\r
547 +\r
548 +    return 0;\r
549 +}\r
550 +\r
551 +/*\r
552 + * Get field value. Make sure the field is set before query. It's most\r
553 + * likely an error to call this while parsing (for example fields set\r
554 + * as FIELD_NOW will only be set to some value after parsing).\r
555 + */\r
556 +static int\r
557 +get_field (struct state *state, enum field field)\r
558 +{\r
559 +    assert (field < ARRAY_SIZE (state->tm));\r
560 +\r
561 +    return state->tm[field];\r
562 +}\r
563 +\r
564 +/*\r
565 + * Validity checkers.\r
566 + */\r
567 +static bool is_valid_12hour (int h)\r
568 +{\r
569 +    return h >= 0 && h <= 12;\r
570 +}\r
571 +\r
572 +static bool is_valid_time (int h, int m, int s)\r
573 +{\r
574 +    /* Allow 24:00:00 to denote end of day. */\r
575 +    if (h == 24 && m == 0 && s == 0)\r
576 +       return true;\r
577 +\r
578 +    return h >= 0 && h <= 23 && m >= 0 && m <= 59 && s >= 0 && s <= 59;\r
579 +}\r
580 +\r
581 +static bool is_valid_mday (int mday)\r
582 +{\r
583 +    return mday >= 1 && mday <= 31;\r
584 +}\r
585 +\r
586 +static bool is_valid_mon (int mon)\r
587 +{\r
588 +    return mon >= 1 && mon <= 12;\r
589 +}\r
590 +\r
591 +static bool is_valid_year (int year)\r
592 +{\r
593 +    return year >= 1970;\r
594 +}\r
595 +\r
596 +static bool is_valid_date (int year, int mon, int mday)\r
597 +{\r
598 +    return is_valid_year (year) && is_valid_mon (mon) && is_valid_mday (mday);\r
599 +}\r
600 +\r
601 +/* Unset indicator for time and date set helpers. */\r
602 +#define UNSET -1\r
603 +\r
604 +/* Time set helper. No input checking. Use UNSET (-1) to leave unset. */\r
605 +static int\r
606 +set_abs_time (struct state *state, int hour, int min, int sec)\r
607 +{\r
608 +    int r;\r
609 +\r
610 +    if (hour != UNSET) {\r
611 +       if ((r = set_field (state, TM_ABS_HOUR, hour)))\r
612 +           return r;\r
613 +    }\r
614 +\r
615 +    if (min != UNSET) {\r
616 +       if ((r = set_field (state, TM_ABS_MIN, min)))\r
617 +           return r;\r
618 +    }\r
619 +\r
620 +    if (sec != UNSET) {\r
621 +       if ((r = set_field (state, TM_ABS_SEC, sec)))\r
622 +           return r;\r
623 +    }\r
624 +\r
625 +    return 0;\r
626 +}\r
627 +\r
628 +/* Date set helper. No input checking. Use UNSET (-1) to leave unset. */\r
629 +static int\r
630 +set_abs_date (struct state *state, int year, int mon, int mday)\r
631 +{\r
632 +    int r;\r
633 +\r
634 +    if (year != UNSET) {\r
635 +       if ((r = set_field (state, TM_ABS_YEAR, year)))\r
636 +           return r;\r
637 +    }\r
638 +\r
639 +    if (mon != UNSET) {\r
640 +       if ((r = set_field (state, TM_ABS_MON, mon)))\r
641 +           return r;\r
642 +    }\r
643 +\r
644 +    if (mday != UNSET) {\r
645 +       if ((r = set_field (state, TM_ABS_MDAY, mday)))\r
646 +           return r;\r
647 +    }\r
648 +\r
649 +    return 0;\r
650 +}\r
651 +\r
652 +/*\r
653 + * Keyword parsing and handling.\r
654 + */\r
655 +struct keyword;\r
656 +typedef int (*setter_t)(struct state *state, struct keyword *kw);\r
657 +\r
658 +struct keyword {\r
659 +    const char *name;  /* keyword */\r
660 +    enum field field;  /* field to set, or FIELD_NONE if N/A */\r
661 +    int value;         /* value to set, or 0 if N/A */\r
662 +    setter_t set;      /* function to use for setting, if non-NULL */\r
663 +};\r
664 +\r
665 +/*\r
666 + * Setter callback functions for keywords.\r
667 + */\r
668 +static int\r
669 +kw_set_default (struct state *state, struct keyword *kw)\r
670 +{\r
671 +    return set_field (state, kw->field, kw->value);\r
672 +}\r
673 +\r
674 +static int\r
675 +kw_set_rel (struct state *state, struct keyword *kw)\r
676 +{\r
677 +    int multiplier = 1;\r
678 +\r
679 +    /* Get a previously set multiplier, if any. */\r
680 +    get_postponed_number (state, &multiplier, NULL, NULL);\r
681 +\r
682 +    /* Accumulate relative field values. */\r
683 +    return mod_field (state, kw->field, multiplier * kw->value);\r
684 +}\r
685 +\r
686 +static int\r
687 +kw_set_number (struct state *state, struct keyword *kw)\r
688 +{\r
689 +    /* -1 = no length, from keyword. */\r
690 +    return set_postponed_number (state, kw->value, -1);\r
691 +}\r
692 +\r
693 +static int\r
694 +kw_set_month (struct state *state, struct keyword *kw)\r
695 +{\r
696 +    int n = get_postponed_length (state);\r
697 +\r
698 +    /* Consume postponed number if it could be mday. This handles "20\r
699 +     * January". */\r
700 +    if (n == 1 || n == 2) {\r
701 +       int r, v;\r
702 +\r
703 +       get_postponed_number (state, &v, NULL, NULL);\r
704 +\r
705 +       if (!is_valid_mday (v))\r
706 +           return -PARSE_TIME_ERR_INVALIDDATE;\r
707 +\r
708 +       r = set_field (state, TM_ABS_MDAY, v);\r
709 +       if (r)\r
710 +           return r;\r
711 +    }\r
712 +\r
713 +    return set_field (state, kw->field, kw->value);\r
714 +}\r
715 +\r
716 +static int\r
717 +kw_set_ampm (struct state *state, struct keyword *kw)\r
718 +{\r
719 +    int n = get_postponed_length (state);\r
720 +\r
721 +    /* Consume postponed number if it could be hour. This handles\r
722 +     * "5pm". */\r
723 +    if (n == 1 || n == 2) {\r
724 +       int r, v;\r
725 +\r
726 +       get_postponed_number (state, &v, NULL, NULL);\r
727 +\r
728 +       if (!is_valid_12hour (v))\r
729 +           return -PARSE_TIME_ERR_INVALIDTIME;\r
730 +\r
731 +       r = set_abs_time (state, v, 0, 0);\r
732 +       if (r)\r
733 +           return r;\r
734 +    }\r
735 +\r
736 +    return set_field (state, kw->field, kw->value);\r
737 +}\r
738 +\r
739 +static int\r
740 +kw_set_timeofday (struct state *state, struct keyword *kw)\r
741 +{\r
742 +    return set_abs_time (state, kw->value, 0, 0);\r
743 +}\r
744 +\r
745 +static int\r
746 +kw_set_today (struct state *state, unused (struct keyword *kw))\r
747 +{\r
748 +    enum field fields[] = { TM_ABS_YEAR, TM_ABS_MON, TM_ABS_MDAY };\r
749 +\r
750 +    return set_fields_to_now (state, fields, ARRAY_SIZE (fields));\r
751 +}\r
752 +\r
753 +static int\r
754 +kw_set_now (struct state *state, unused (struct keyword *kw))\r
755 +{\r
756 +    enum field fields[] = { TM_ABS_HOUR, TM_ABS_MIN, TM_ABS_SEC };\r
757 +\r
758 +    return set_fields_to_now (state, fields, ARRAY_SIZE (fields));\r
759 +}\r
760 +\r
761 +static int\r
762 +kw_set_ordinal (struct state *state, struct keyword *kw)\r
763 +{\r
764 +    int n, v;\r
765 +\r
766 +    /* Require a postponed number. */\r
767 +    if (!get_postponed_number (state, &v, &n, NULL))\r
768 +       return -PARSE_TIME_ERR_DATEFORMAT;\r
769 +\r
770 +    /* Ordinals are mday. */\r
771 +    if (n != 1 && n != 2)\r
772 +       return -PARSE_TIME_ERR_DATEFORMAT;\r
773 +\r
774 +    /* Be strict about st, nd, rd, and lax about th. */\r
775 +    if (strcasecmp (kw->name, "st") == 0 && v != 1 && v != 21 && v != 31)\r
776 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
777 +    else if (strcasecmp (kw->name, "nd") == 0 && v != 2 && v != 22)\r
778 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
779 +    else if (strcasecmp (kw->name, "rd") == 0 && v != 3 && v != 23)\r
780 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
781 +    else if (strcasecmp (kw->name, "th") == 0 && !is_valid_mday (v))\r
782 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
783 +\r
784 +    return set_field (state, TM_ABS_MDAY, v);\r
785 +}\r
786 +\r
787 +/*\r
788 + * Accepted keywords.\r
789 + *\r
790 + * A keyword may optionally contain a '|' to indicate the minimum\r
791 + * match length. Without one, full match is required. It's advisable\r
792 + * to keep the minimum match parts unique across all keywords.\r
793 + *\r
794 + * If keyword begins with upper case letter, then the matching will be\r
795 + * case sensitive. Otherwise the matching is case insensitive.\r
796 + *\r
797 + * If setter is NULL, set_default will be used.\r
798 + *\r
799 + * Note: Order matters. Matching is greedy, longest match is used, but\r
800 + * of equal length matches the first one is used, unless there's an\r
801 + * equal length case sensitive match which trumps case insensitive\r
802 + * matches.\r
803 + */\r
804 +static struct keyword keywords[] = {\r
805 +    /* Weekdays. */\r
806 +    { N_("sun|day"),   TM_ABS_WDAY,    0,      NULL },\r
807 +    { N_("mon|day"),   TM_ABS_WDAY,    1,      NULL },\r
808 +    { N_("tue|sday"),  TM_ABS_WDAY,    2,      NULL },\r
809 +    { N_("wed|nesday"),        TM_ABS_WDAY,    3,      NULL },\r
810 +    { N_("thu|rsday"), TM_ABS_WDAY,    4,      NULL },\r
811 +    { N_("fri|day"),   TM_ABS_WDAY,    5,      NULL },\r
812 +    { N_("sat|urday"), TM_ABS_WDAY,    6,      NULL },\r
813 +\r
814 +    /* Months. */\r
815 +    { N_("jan|uary"),  TM_ABS_MON,     1,      kw_set_month },\r
816 +    { N_("feb|ruary"), TM_ABS_MON,     2,      kw_set_month },\r
817 +    { N_("mar|ch"),    TM_ABS_MON,     3,      kw_set_month },\r
818 +    { N_("apr|il"),    TM_ABS_MON,     4,      kw_set_month },\r
819 +    { N_("may"),       TM_ABS_MON,     5,      kw_set_month },\r
820 +    { N_("jun|e"),     TM_ABS_MON,     6,      kw_set_month },\r
821 +    { N_("jul|y"),     TM_ABS_MON,     7,      kw_set_month },\r
822 +    { N_("aug|ust"),   TM_ABS_MON,     8,      kw_set_month },\r
823 +    { N_("sep|tember"),        TM_ABS_MON,     9,      kw_set_month },\r
824 +    { N_("oct|ober"),  TM_ABS_MON,     10,     kw_set_month },\r
825 +    { N_("nov|ember"), TM_ABS_MON,     11,     kw_set_month },\r
826 +    { N_("dec|ember"), TM_ABS_MON,     12,     kw_set_month },\r
827 +\r
828 +    /* Durations. */\r
829 +    { N_("y|ears"),    TM_REL_YEAR,    1,      kw_set_rel },\r
830 +    { N_("w|eeks"),    TM_REL_WEEK,    1,      kw_set_rel },\r
831 +    { N_("d|ays"),     TM_REL_DAY,     1,      kw_set_rel },\r
832 +    { N_("h|ours"),    TM_REL_HOUR,    1,      kw_set_rel },\r
833 +    { N_("hr|s"),      TM_REL_HOUR,    1,      kw_set_rel },\r
834 +    { N_("m|inutes"),  TM_REL_MIN,     1,      kw_set_rel },\r
835 +    /* M=months, m=minutes */\r
836 +    { N_("M"),         TM_REL_MON,     1,      kw_set_rel },\r
837 +    { N_("mins"),      TM_REL_MIN,     1,      kw_set_rel },\r
838 +    { N_("mo|nths"),   TM_REL_MON,     1,      kw_set_rel },\r
839 +    { N_("s|econds"),  TM_REL_SEC,     1,      kw_set_rel },\r
840 +    { N_("secs"),      TM_REL_SEC,     1,      kw_set_rel },\r
841 +\r
842 +    /* Numbers. */\r
843 +    { N_("one"),       TM_NONE,        1,      kw_set_number },\r
844 +    { N_("two"),       TM_NONE,        2,      kw_set_number },\r
845 +    { N_("three"),     TM_NONE,        3,      kw_set_number },\r
846 +    { N_("four"),      TM_NONE,        4,      kw_set_number },\r
847 +    { N_("five"),      TM_NONE,        5,      kw_set_number },\r
848 +    { N_("six"),       TM_NONE,        6,      kw_set_number },\r
849 +    { N_("seven"),     TM_NONE,        7,      kw_set_number },\r
850 +    { N_("eight"),     TM_NONE,        8,      kw_set_number },\r
851 +    { N_("nine"),      TM_NONE,        9,      kw_set_number },\r
852 +    { N_("ten"),       TM_NONE,        10,     kw_set_number },\r
853 +    { N_("dozen"),     TM_NONE,        12,     kw_set_number },\r
854 +    { N_("hundred"),   TM_NONE,        100,    kw_set_number },\r
855 +\r
856 +    /* Special number forms. */\r
857 +    { N_("this"),      TM_NONE,        0,      kw_set_number },\r
858 +    { N_("last"),      TM_NONE,        1,      kw_set_number },\r
859 +\r
860 +    /* Other special keywords. */\r
861 +    { N_("yesterday"), TM_REL_DAY,     1,      kw_set_rel },\r
862 +    { N_("today"),     TM_NONE,        0,      kw_set_today },\r
863 +    { N_("now"),       TM_NONE,        0,      kw_set_now },\r
864 +    { N_("noon"),      TM_NONE,        12,     kw_set_timeofday },\r
865 +    { N_("midnight"),  TM_NONE,        0,      kw_set_timeofday },\r
866 +    { N_("am"),                TM_AMPM,        0,      kw_set_ampm },\r
867 +    { N_("a.m."),      TM_AMPM,        0,      kw_set_ampm },\r
868 +    { N_("pm"),                TM_AMPM,        1,      kw_set_ampm },\r
869 +    { N_("p.m."),      TM_AMPM,        1,      kw_set_ampm },\r
870 +    { N_("st"),                TM_NONE,        0,      kw_set_ordinal },\r
871 +    { N_("nd"),                TM_NONE,        0,      kw_set_ordinal },\r
872 +    { N_("rd"),                TM_NONE,        0,      kw_set_ordinal },\r
873 +    { N_("th"),                TM_NONE,        0,      kw_set_ordinal },\r
874 +\r
875 +    /* Timezone codes: offset in minutes. XXX: Add more codes. */\r
876 +    { N_("pst"),       TM_TZ,          -8*60,  NULL },\r
877 +    { N_("mst"),       TM_TZ,          -7*60,  NULL },\r
878 +    { N_("cst"),       TM_TZ,          -6*60,  NULL },\r
879 +    { N_("est"),       TM_TZ,          -5*60,  NULL },\r
880 +    { N_("ast"),       TM_TZ,          -4*60,  NULL },\r
881 +    { N_("nst"),       TM_TZ,          -(3*60+30),     NULL },\r
882 +\r
883 +    { N_("gmt"),       TM_TZ,          0,      NULL },\r
884 +    { N_("utc"),       TM_TZ,          0,      NULL },\r
885 +\r
886 +    { N_("wet"),       TM_TZ,          0,      NULL },\r
887 +    { N_("cet"),       TM_TZ,          1*60,   NULL },\r
888 +    { N_("eet"),       TM_TZ,          2*60,   NULL },\r
889 +    { N_("fet"),       TM_TZ,          3*60,   NULL },\r
890 +\r
891 +    { N_("wat"),       TM_TZ,          1*60,   NULL },\r
892 +    { N_("cat"),       TM_TZ,          2*60,   NULL },\r
893 +    { N_("eat"),       TM_TZ,          3*60,   NULL },\r
894 +};\r
895 +\r
896 +/*\r
897 + * Compare strings s and keyword. Return number of matching chars on\r
898 + * match, 0 for no match. Match must be at least n chars, or all of\r
899 + * keyword if n < 0, otherwise it's not a match. Use match_case for\r
900 + * case sensitive matching.\r
901 + */\r
902 +static size_t\r
903 +stringcmp (const char *s, const char *keyword, ssize_t n, bool match_case)\r
904 +{\r
905 +    ssize_t i;\r
906 +\r
907 +    if (!n)\r
908 +       return 0;\r
909 +\r
910 +    for (i = 0; *s && *keyword; i++, s++, keyword++) {\r
911 +       if (match_case) {\r
912 +           if (*s != *keyword)\r
913 +               break;\r
914 +       } else {\r
915 +           if (tolower ((unsigned char) *s) !=\r
916 +               tolower ((unsigned char) *keyword))\r
917 +               break;\r
918 +       }\r
919 +    }\r
920 +\r
921 +    if (n > 0)\r
922 +       return i < n ? 0 : i;\r
923 +    else\r
924 +       return *keyword ? 0 : i;\r
925 +}\r
926 +\r
927 +/*\r
928 + * Parse a keyword. Return < 0 on error, number of parsed chars on\r
929 + * success.\r
930 + */\r
931 +static ssize_t\r
932 +parse_keyword (struct state *state, const char *s)\r
933 +{\r
934 +    unsigned int i;\r
935 +    size_t n, max_n = 0;\r
936 +    struct keyword *kw = NULL;\r
937 +    int r;\r
938 +\r
939 +    /* Match longest keyword */\r
940 +    for (i = 0; i < ARRAY_SIZE (keywords); i++) {\r
941 +       /* Match case if keyword begins with upper case letter. */\r
942 +       bool mcase = isupper ((unsigned char) keywords[i].name[0]);\r
943 +       ssize_t minlen = -1;\r
944 +       char keyword[128];\r
945 +       char *p;\r
946 +\r
947 +       strncpy (keyword, _(keywords[i].name), sizeof (keyword));\r
948 +\r
949 +       /* Truncate too long keywords. XXX: Make this dynamic? */\r
950 +       keyword[sizeof (keyword) - 1] = '\0';\r
951 +\r
952 +       /* Minimum match length. */\r
953 +       p = strchr (keyword, '|');\r
954 +       if (p) {\r
955 +           minlen = p - keyword;\r
956 +\r
957 +           /* Remove the minimum match length separator. */\r
958 +           memmove (p, p + 1, strlen (p + 1) + 1);\r
959 +       }\r
960 +\r
961 +       n = stringcmp (s, keyword, minlen, mcase);\r
962 +       if (n > max_n || (n == max_n && mcase)) {\r
963 +           max_n = n;\r
964 +           kw = &keywords[i];\r
965 +       }\r
966 +    }\r
967 +\r
968 +    if (!kw)\r
969 +       return -PARSE_TIME_ERR_KEYWORD;\r
970 +\r
971 +    if (kw->set)\r
972 +       r = kw->set (state, kw);\r
973 +    else\r
974 +       r = kw_set_default (state, kw);\r
975 +\r
976 +    if (r < 0)\r
977 +       return r;\r
978 +\r
979 +    return max_n;\r
980 +}\r
981 +\r
982 +/*\r
983 + * Non-keyword parsers and their helpers.\r
984 + */\r
985 +\r
986 +static int\r
987 +set_user_tz (struct state *state, char sign, int hour, int min)\r
988 +{\r
989 +    int tz = hour * 60 + min;\r
990 +\r
991 +    assert (sign == '+' || sign == '-');\r
992 +\r
993 +    if (hour < 0 || hour > 14 || min < 0 || min > 59 || min % 15)\r
994 +       return -PARSE_TIME_ERR_INVALIDTIME;\r
995 +\r
996 +    if (sign == '-')\r
997 +       tz = -tz;\r
998 +\r
999 +    return set_field (state, TM_TZ, tz);\r
1000 +}\r
1001 +\r
1002 +/*\r
1003 + * Independent parsing of a postponed number when it wasn't consumed\r
1004 + * during parsing of the following token.\r
1005 + */\r
1006 +static int\r
1007 +parse_postponed_number (struct state *state, int v, int n, char d)\r
1008 +{\r
1009 +    /*\r
1010 +     * alright, these are really lone, won't affect parsing of\r
1011 +     * following items... it's not a multiplier, those have been eaten\r
1012 +     * away.\r
1013 +     *\r
1014 +     * also note numbers eaten away by parse_single_number.\r
1015 +     */\r
1016 +\r
1017 +    assert (n < 8);\r
1018 +\r
1019 +    if (n == 1 || n == 2) {\r
1020 +       /* Notable exception: Previous field affects parsing. This\r
1021 +        * handles "January 20". */\r
1022 +       if (state->last_field == TM_ABS_MON) {\r
1023 +           /* D[D] */\r
1024 +           if (!is_valid_mday (v))\r
1025 +               return -PARSE_TIME_ERR_INVALIDDATE;\r
1026 +\r
1027 +           return set_field (state, TM_ABS_MDAY, v);\r
1028 +       } else if (n == 2) {\r
1029 +           /* XXX: Only allow if last field is hour, min, or sec? */\r
1030 +           if (d == '+' || d == '-') {\r
1031 +               /* +/-HH */\r
1032 +               return set_user_tz (state, d, v, 0);\r
1033 +           }\r
1034 +       }\r
1035 +    } else if (n == 4) {\r
1036 +       /* Notable exception: Value affects parsing. Time zones are\r
1037 +        * always at most 1400 and we don't understand years before\r
1038 +        * 1970. */\r
1039 +       if (!is_valid_year (v)) {\r
1040 +           if (d == '+' || d == '-') {\r
1041 +               /* +/-HHMM */\r
1042 +               return set_user_tz (state, d, v / 100, v % 100);\r
1043 +           }\r
1044 +       } else {\r
1045 +           /* YYYY */\r
1046 +           return set_field (state, TM_ABS_YEAR, v);\r
1047 +       }\r
1048 +    } else if (n == 6) {\r
1049 +       /* HHMMSS */\r
1050 +       int hour = v / 10000;\r
1051 +       int min = (v / 100) % 100;\r
1052 +       int sec = v % 100;\r
1053 +\r
1054 +       if (!is_valid_time (hour, min, sec))\r
1055 +           return -PARSE_TIME_ERR_INVALIDTIME;\r
1056 +\r
1057 +       return set_abs_time (state, hour, min, sec);\r
1058 +    }\r
1059 +\r
1060 +    /* else n is one of {-1, 3, 5, 7 } */\r
1061 +\r
1062 +    return -PARSE_TIME_ERR_FORMAT;\r
1063 +}\r
1064 +\r
1065 +/* Parse a single number. Typically postpone parsing until later. */\r
1066 +static int\r
1067 +parse_single_number (struct state *state, unsigned long v,\r
1068 +                    unsigned long n)\r
1069 +{\r
1070 +    assert (n);\r
1071 +\r
1072 +    /* Parse things that can be parsed immediately. */\r
1073 +    if (n == 8) {\r
1074 +       /* YYYYMMDD */\r
1075 +       int year = v / 10000;\r
1076 +       int mon = (v / 100) % 100;\r
1077 +       int mday = v % 100;\r
1078 +\r
1079 +       if (!is_valid_date (year, mon, mday))\r
1080 +           return -PARSE_TIME_ERR_INVALIDDATE;\r
1081 +\r
1082 +       return set_abs_date (state, year, mon, mday);\r
1083 +    } else if (n > 8) {\r
1084 +       /* XXX: Seconds since epoch. */\r
1085 +       return -PARSE_TIME_ERR_FORMAT;\r
1086 +    }\r
1087 +\r
1088 +    if (v > INT_MAX)\r
1089 +       return -PARSE_TIME_ERR_FORMAT;\r
1090 +\r
1091 +    return set_postponed_number (state, v, n);\r
1092 +}\r
1093 +\r
1094 +static bool\r
1095 +is_time_sep (char c)\r
1096 +{\r
1097 +    return c == ':';\r
1098 +}\r
1099 +\r
1100 +static bool\r
1101 +is_date_sep (char c)\r
1102 +{\r
1103 +    return c == '/' || c == '-' || c == '.';\r
1104 +}\r
1105 +\r
1106 +static bool\r
1107 +is_sep (char c)\r
1108 +{\r
1109 +    return is_time_sep (c) || is_date_sep (c);\r
1110 +}\r
1111 +\r
1112 +/* Two-digit year: 00...69 is 2000s, 70...99 1900s, if n == 0 keep\r
1113 + * unset. */\r
1114 +static int\r
1115 +expand_year (unsigned long year, size_t n)\r
1116 +{\r
1117 +    if (n == 2) {\r
1118 +       return (year < 70 ? 2000 : 1900) + year;\r
1119 +    } else if (n == 4) {\r
1120 +       return year;\r
1121 +    } else {\r
1122 +       return UNSET;\r
1123 +    }\r
1124 +}\r
1125 +\r
1126 +/* Parse a date number triplet. */\r
1127 +static int\r
1128 +parse_date (struct state *state, char sep,\r
1129 +           unsigned long v1, unsigned long v2, unsigned long v3,\r
1130 +           size_t n1, size_t n2, size_t n3)\r
1131 +{\r
1132 +    int year = UNSET, mon = UNSET, mday = UNSET;\r
1133 +\r
1134 +    assert (is_date_sep (sep));\r
1135 +\r
1136 +    switch (sep) {\r
1137 +    case '/': /* Date: M[M]/D[D][/YY[YY]] or M[M]/YYYY */\r
1138 +       if (n1 != 1 && n1 != 2)\r
1139 +           return -PARSE_TIME_ERR_DATEFORMAT;\r
1140 +\r
1141 +       if ((n2 == 1 || n2 == 2) && (n3 == 0 || n3 == 2 || n3 == 4)) {\r
1142 +           /* M[M]/D[D][/YY[YY]] */\r
1143 +           year = expand_year (v3, n3);\r
1144 +           mon = v1;\r
1145 +           mday = v2;\r
1146 +       } else if (n2 == 4 && n3 == 0) {\r
1147 +           /* M[M]/YYYY */\r
1148 +           year = v2;\r
1149 +           mon = v1;\r
1150 +       } else {\r
1151 +           return -PARSE_TIME_ERR_DATEFORMAT;\r
1152 +       }\r
1153 +       break;\r
1154 +\r
1155 +    case '-': /* Date: YYYY-MM[-DD] or DD-MM[-YY[YY]] or MM-YYYY */\r
1156 +       if (n1 == 4 && n2 == 2 && (n3 == 0 || n3 == 2)) {\r
1157 +           /* YYYY-MM[-DD] */\r
1158 +           year = v1;\r
1159 +           mon = v2;\r
1160 +           if (n3)\r
1161 +               mday = v3;\r
1162 +       } else if (n1 == 2 && n2 == 2 && (n3 == 0 || n3 == 2 || n3 == 4)) {\r
1163 +           /* DD-MM[-YY[YY]] */\r
1164 +           year = expand_year (v3, n3);\r
1165 +           mon = v2;\r
1166 +           mday = v1;\r
1167 +       } else if (n1 == 2 && n2 == 4 && n3 == 0) {\r
1168 +           /* MM-YYYY */\r
1169 +           year = v2;\r
1170 +           mon = v1;\r
1171 +       } else {\r
1172 +           return -PARSE_TIME_ERR_DATEFORMAT;\r
1173 +       }\r
1174 +       break;\r
1175 +\r
1176 +    case '.': /* Date: D[D].M[M][.[YY[YY]]] */\r
1177 +       if ((n1 != 1 && n1 != 2) || (n2 != 1 && n2 != 2) ||\r
1178 +           (n3 != 0 && n3 != 2 && n3 != 4))\r
1179 +           return -PARSE_TIME_ERR_DATEFORMAT;\r
1180 +\r
1181 +       year = expand_year (v3, n3);\r
1182 +       mon = v2;\r
1183 +       mday = v1;\r
1184 +       break;\r
1185 +    }\r
1186 +\r
1187 +    if (year != UNSET && !is_valid_year (year))\r
1188 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
1189 +\r
1190 +    if (mon != UNSET && !is_valid_mon (mon))\r
1191 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
1192 +\r
1193 +    if (mday != UNSET && !is_valid_mday (mday))\r
1194 +       return -PARSE_TIME_ERR_INVALIDDATE;\r
1195 +\r
1196 +    return set_abs_date (state, year, mon, mday);\r
1197 +}\r
1198 +\r
1199 +/* Parse a time number triplet. */\r
1200 +static int\r
1201 +parse_time (struct state *state, char sep,\r
1202 +           unsigned long v1, unsigned long v2, unsigned long v3,\r
1203 +           size_t n1, size_t n2, size_t n3)\r
1204 +{\r
1205 +    assert (is_time_sep (sep));\r
1206 +\r
1207 +    if ((n1 != 1 && n1 != 2) || n2 != 2 || (n3 != 0 && n3 != 2))\r
1208 +       return -PARSE_TIME_ERR_TIMEFORMAT;\r
1209 +\r
1210 +    /*\r
1211 +     * Notable exception: Previously set fields affect\r
1212 +     * parsing. Interpret (+|-)HH:MM as time zone only if hour and\r
1213 +     * minute have been set.\r
1214 +     *\r
1215 +     * XXX: This could be fixed by restricting the delimiters\r
1216 +     * preceding time. For '+' it would be justified, but for '-' it\r
1217 +     * might be inconvenient. However prefer to allow '-' as an\r
1218 +     * insignificant delimiter preceding time for convenience, and\r
1219 +     * handle '+' the same way for consistency between positive and\r
1220 +     * negative time zones.\r
1221 +     */\r
1222 +    if (is_field_set (state, TM_ABS_HOUR) &&\r
1223 +       is_field_set (state, TM_ABS_MIN) &&\r
1224 +       n1 == 2 && n2 == 2 && n3 == 0 &&\r
1225 +       (state->delim == '+' || state->delim == '-')) {\r
1226 +       return set_user_tz (state, state->delim, v1, v2);\r
1227 +    }\r
1228 +\r
1229 +    if (!is_valid_time (v1, v2, v3))\r
1230 +       return -PARSE_TIME_ERR_INVALIDTIME;\r
1231 +\r
1232 +    return set_abs_time (state, v1, v2, n3 ? v3 : 0);\r
1233 +}\r
1234 +\r
1235 +/* strtoul helper that assigns length. */\r
1236 +static unsigned long\r
1237 +strtoul_len (const char *s, const char **endp, size_t *len)\r
1238 +{\r
1239 +    unsigned long val = strtoul (s, (char **) endp, 10);\r
1240 +\r
1241 +    *len = *endp - s;\r
1242 +    return val;\r
1243 +}\r
1244 +\r
1245 +/*\r
1246 + * Parse a (group of) number(s). Return < 0 on error, number of parsed\r
1247 + * chars on success.\r
1248 + */\r
1249 +static ssize_t\r
1250 +parse_number (struct state *state, const char *s)\r
1251 +{\r
1252 +    int r;\r
1253 +    unsigned long v1, v2, v3 = 0;\r
1254 +    size_t n1, n2, n3 = 0;\r
1255 +    const char *p = s;\r
1256 +    char sep;\r
1257 +\r
1258 +    v1 = strtoul_len (p, &p, &n1);\r
1259 +\r
1260 +    if (is_sep (*p) && isdigit ((unsigned char) *(p + 1))) {\r
1261 +       sep = *p;\r
1262 +       v2 = strtoul_len (p + 1, &p, &n2);\r
1263 +    } else {\r
1264 +       /* A single number. */\r
1265 +       r = parse_single_number (state, v1, n1);\r
1266 +       if (r)\r
1267 +           return r;\r
1268 +\r
1269 +       return p - s;\r
1270 +    }\r
1271 +\r
1272 +    /* A group of two or three numbers? */\r
1273 +    if (*p == sep && isdigit ((unsigned char) *(p + 1)))\r
1274 +       v3 = strtoul_len (p + 1, &p, &n3);\r
1275 +\r
1276 +    if (is_time_sep (sep))\r
1277 +       r = parse_time (state, sep, v1, v2, v3, n1, n2, n3);\r
1278 +    else\r
1279 +       r = parse_date (state, sep, v1, v2, v3, n1, n2, n3);\r
1280 +\r
1281 +    if (r)\r
1282 +       return r;\r
1283 +\r
1284 +    return p - s;\r
1285 +}\r
1286 +\r
1287 +/*\r
1288 + * Parse delimiter(s). Throw away all except the last one, which is\r
1289 + * stored for parsing the next non-delimiter. Return < 0 on error,\r
1290 + * number of parsed chars on success.\r
1291 + *\r
1292 + * XXX: We might want to be more strict here.\r
1293 + */\r
1294 +static ssize_t\r
1295 +parse_delim (struct state *state, const char *s)\r
1296 +{\r
1297 +    const char *p = s;\r
1298 +\r
1299 +    /*\r
1300 +     * Skip non-alpha and non-digit, and store the last for further\r
1301 +     * processing.\r
1302 +     */\r
1303 +    while (*p && !isalnum ((unsigned char) *p)) {\r
1304 +       set_delim (state, *p);\r
1305 +       p++;\r
1306 +    }\r
1307 +\r
1308 +    return p - s;\r
1309 +}\r
1310 +\r
1311 +/*\r
1312 + * Parse a date/time string. Return < 0 on error, number of parsed\r
1313 + * chars on success.\r
1314 + */\r
1315 +static ssize_t\r
1316 +parse_input (struct state *state, const char *s)\r
1317 +{\r
1318 +    const char *p = s;\r
1319 +    ssize_t n;\r
1320 +    int r;\r
1321 +\r
1322 +    while (*p) {\r
1323 +       if (isalpha ((unsigned char) *p)) {\r
1324 +           n = parse_keyword (state, p);\r
1325 +       } else if (isdigit ((unsigned char) *p)) {\r
1326 +           n = parse_number (state, p);\r
1327 +       } else {\r
1328 +           n = parse_delim (state, p);\r
1329 +       }\r
1330 +\r
1331 +       if (n <= 0) {\r
1332 +           if (n == 0)\r
1333 +               n = -PARSE_TIME_ERR;\r
1334 +\r
1335 +           return n;\r
1336 +       }\r
1337 +\r
1338 +       p += n;\r
1339 +    }\r
1340 +\r
1341 +    /* Parse postponed number, if any. */\r
1342 +    r = handle_postponed_number (state, TM_NONE);\r
1343 +    if (r < 0)\r
1344 +       return r;\r
1345 +\r
1346 +    return p - s;\r
1347 +}\r
1348 +\r
1349 +/*\r
1350 + * Processing the parsed input.\r
1351 + */\r
1352 +\r
1353 +/*\r
1354 + * Initialize reference time to tm. Use time zone in state if\r
1355 + * specified, otherwise local time. Use now for reference time if\r
1356 + * non-NULL, otherwise current time.\r
1357 + */\r
1358 +static int\r
1359 +initialize_now (struct state *state, struct tm *tm, const time_t *now)\r
1360 +{\r
1361 +    time_t t;\r
1362 +\r
1363 +    if (now) {\r
1364 +       t = *now;\r
1365 +    } else {\r
1366 +       if (time (&t) == (time_t) -1)\r
1367 +           return -PARSE_TIME_ERR_LIB;\r
1368 +    }\r
1369 +\r
1370 +    if (is_field_set (state, TM_TZ)) {\r
1371 +       /* Some other time zone. */\r
1372 +\r
1373 +       /* Adjust now according to the TZ. */\r
1374 +       t += get_field (state, TM_TZ) * 60;\r
1375 +\r
1376 +       /* It's not gm, but this doesn't mess with the TZ. */\r
1377 +       if (gmtime_r (&t, tm) == NULL)\r
1378 +           return -PARSE_TIME_ERR_LIB;\r
1379 +    } else {\r
1380 +       /* Local time. */\r
1381 +       if (localtime_r (&t, tm) == NULL)\r
1382 +           return -PARSE_TIME_ERR_LIB;\r
1383 +    }\r
1384 +\r
1385 +    return 0;\r
1386 +}\r
1387 +\r
1388 +/*\r
1389 + * Normalize tm according to mktime(3). Both mktime(3) and\r
1390 + * localtime_r(3) use local time, but they cancel each other out here,\r
1391 + * making this function agnostic to time zone.\r
1392 + */\r
1393 +static int\r
1394 +normalize_tm (struct tm *tm)\r
1395 +{\r
1396 +    time_t t = mktime (tm);\r
1397 +\r
1398 +    if (t == (time_t) -1)\r
1399 +       return -PARSE_TIME_ERR_LIB;\r
1400 +\r
1401 +    if (!localtime_r (&t, tm))\r
1402 +       return -PARSE_TIME_ERR_LIB;\r
1403 +\r
1404 +    return 0;\r
1405 +}\r
1406 +\r
1407 +/* Get field out of a struct tm. */\r
1408 +static int\r
1409 +tm_get_field (const struct tm *tm, enum field field)\r
1410 +{\r
1411 +    switch (field) {\r
1412 +    case TM_ABS_SEC:   return tm->tm_sec;\r
1413 +    case TM_ABS_MIN:   return tm->tm_min;\r
1414 +    case TM_ABS_HOUR:  return tm->tm_hour;\r
1415 +    case TM_ABS_MDAY:  return tm->tm_mday;\r
1416 +    case TM_ABS_MON:   return tm->tm_mon + 1; /* 0- to 1-based */\r
1417 +    case TM_ABS_YEAR:  return 1900 + tm->tm_year;\r
1418 +    case TM_ABS_WDAY:  return tm->tm_wday;\r
1419 +    case TM_ABS_ISDST: return tm->tm_isdst;\r
1420 +    default:\r
1421 +       assert (false);\r
1422 +       break;\r
1423 +    }\r
1424 +\r
1425 +    return 0;\r
1426 +}\r
1427 +\r
1428 +/* Modify hour according to am/pm setting. */\r
1429 +static int\r
1430 +fixup_ampm (struct state *state)\r
1431 +{\r
1432 +    int hour, hdiff = 0;\r
1433 +\r
1434 +    if (!is_field_set (state, TM_AMPM))\r
1435 +       return 0;\r
1436 +\r
1437 +    if (!is_field_set (state, TM_ABS_HOUR))\r
1438 +       return -PARSE_TIME_ERR_TIMEFORMAT;\r
1439 +\r
1440 +    hour = get_field (state, TM_ABS_HOUR);\r
1441 +    if (!is_valid_12hour (hour))\r
1442 +       return -PARSE_TIME_ERR_INVALIDTIME;\r
1443 +\r
1444 +    if (get_field (state, TM_AMPM)) {\r
1445 +       /* 12pm is noon. */\r
1446 +       if (hour != 12)\r
1447 +           hdiff = 12;\r
1448 +    } else {\r
1449 +       /* 12am is midnight, beginning of day. */\r
1450 +       if (hour == 12)\r
1451 +           hdiff = -12;\r
1452 +    }\r
1453 +\r
1454 +    mod_field (state, TM_REL_HOUR, -hdiff);\r
1455 +\r
1456 +    return 0;\r
1457 +}\r
1458 +\r
1459 +/* Combine absolute and relative fields, and round. */\r
1460 +static int\r
1461 +create_output (struct state *state, time_t *t_out, const time_t *tnow,\r
1462 +              int round)\r
1463 +{\r
1464 +    struct tm tm = { .tm_isdst = -1 };\r
1465 +    struct tm now;\r
1466 +    time_t t;\r
1467 +    enum field f;\r
1468 +    int r;\r
1469 +    int week_round = PARSE_TIME_NO_ROUND;\r
1470 +\r
1471 +    r = initialize_now (state, &now, tnow);\r
1472 +    if (r)\r
1473 +       return r;\r
1474 +\r
1475 +    /* Initialize uninitialized fields to now. */\r
1476 +    for (f = TM_ABS_SEC; f != TM_NONE; f = next_abs_field (f)) {\r
1477 +       if (state->set[f] == FIELD_NOW) {\r
1478 +           state->tm[f] = tm_get_field (&now, f);\r
1479 +           state->set[f] = FIELD_SET;\r
1480 +       }\r
1481 +    }\r
1482 +\r
1483 +    /*\r
1484 +     * If MON is set but YEAR is not, refer to past month.\r
1485 +     *\r
1486 +     * XXX: Why are month/week special in this regard? What about\r
1487 +     * mday, or time. Should refer to past.\r
1488 +     */\r
1489 +    if (is_field_set (state, TM_ABS_MON) &&\r
1490 +       !is_field_set (state, TM_ABS_YEAR)) {\r
1491 +       if (get_field (state, TM_ABS_MON) >= tm_get_field (&now, TM_ABS_MON))\r
1492 +           mod_field (state, TM_REL_YEAR, 1);\r
1493 +    }\r
1494 +\r
1495 +    /*\r
1496 +     * If WDAY is set but MDAY is not, we consider WDAY relative\r
1497 +     *\r
1498 +     * XXX: This fails on stuff like "two months ago monday" because\r
1499 +     * two months ago wasn't the same day as today. Postpone until we\r
1500 +     * know date?\r
1501 +     */\r
1502 +    if (is_field_set (state, TM_ABS_WDAY) &&\r
1503 +       !is_field_set (state, TM_ABS_MDAY)) {\r
1504 +       int wday = get_field (state, TM_ABS_WDAY);\r
1505 +       int today = tm_get_field (&now, TM_ABS_WDAY);\r
1506 +       int rel_days;\r
1507 +\r
1508 +       if (today > wday)\r
1509 +           rel_days = today - wday;\r
1510 +       else\r
1511 +           rel_days = today + 7 - wday;\r
1512 +\r
1513 +       /* This also prevents special week rounding from happening. */\r
1514 +       mod_field (state, TM_REL_DAY, rel_days);\r
1515 +\r
1516 +       unset_field (state, TM_ABS_WDAY);\r
1517 +    }\r
1518 +\r
1519 +    r = fixup_ampm (state);\r
1520 +    if (r)\r
1521 +       return r;\r
1522 +\r
1523 +    /*\r
1524 +     * Iterate fields from most accurate to least accurate, and set\r
1525 +     * unset fields according to requested rounding.\r
1526 +     */\r
1527 +    for (f = TM_ABS_SEC; f != TM_NONE; f = next_abs_field (f)) {\r
1528 +       if (round != PARSE_TIME_NO_ROUND) {\r
1529 +           enum field r = abs_to_rel_field (f);\r
1530 +\r
1531 +           if (is_field_set (state, f) || is_field_set (state, r)) {\r
1532 +               if (round >= PARSE_TIME_ROUND_UP)\r
1533 +                   mod_field (state, r, -1);\r
1534 +               round = PARSE_TIME_NO_ROUND; /* No more rounding. */\r
1535 +           } else {\r
1536 +               if (f == TM_ABS_MDAY &&\r
1537 +                   is_field_set (state, TM_REL_WEEK)) {\r
1538 +                   /* Week is most accurate. */\r
1539 +                   week_round = round;\r
1540 +                   round = PARSE_TIME_NO_ROUND;\r
1541 +               } else {\r
1542 +                   set_field (state, f, field_epoch (f));\r
1543 +               }\r
1544 +           }\r
1545 +       }\r
1546 +\r
1547 +       if (!is_field_set (state, f))\r
1548 +           set_field (state, f, tm_get_field (&now, f));\r
1549 +    }\r
1550 +\r
1551 +    /* Special case: rounding with week accuracy. */\r
1552 +    if (week_round != PARSE_TIME_NO_ROUND) {\r
1553 +       /* Temporarily set more accurate fields to now. */\r
1554 +       set_field (state, TM_ABS_SEC, tm_get_field (&now, TM_ABS_SEC));\r
1555 +       set_field (state, TM_ABS_MIN, tm_get_field (&now, TM_ABS_MIN));\r
1556 +       set_field (state, TM_ABS_HOUR, tm_get_field (&now, TM_ABS_HOUR));\r
1557 +       set_field (state, TM_ABS_MDAY, tm_get_field (&now, TM_ABS_MDAY));\r
1558 +    }\r
1559 +\r
1560 +    /*\r
1561 +     * Set all fields. They may contain out of range values before\r
1562 +     * normalization by mktime(3).\r
1563 +     */\r
1564 +    tm.tm_sec = get_field (state, TM_ABS_SEC) - get_field (state, TM_REL_SEC);\r
1565 +    tm.tm_min = get_field (state, TM_ABS_MIN) - get_field (state, TM_REL_MIN);\r
1566 +    tm.tm_hour = get_field (state, TM_ABS_HOUR) - get_field (state, TM_REL_HOUR);\r
1567 +    tm.tm_mday = get_field (state, TM_ABS_MDAY) -\r
1568 +                get_field (state, TM_REL_DAY) - 7 * get_field (state, TM_REL_WEEK);\r
1569 +    tm.tm_mon = get_field (state, TM_ABS_MON) - get_field (state, TM_REL_MON);\r
1570 +    tm.tm_mon--; /* 1- to 0-based */\r
1571 +    tm.tm_year = get_field (state, TM_ABS_YEAR) - get_field (state, TM_REL_YEAR) - 1900;\r
1572 +\r
1573 +    /*\r
1574 +     * It's always normal time.\r
1575 +     *\r
1576 +     * XXX: This is probably not a solution that universally\r
1577 +     * works. Just make sure DST is not taken into account. We don't\r
1578 +     * want rounding to be affected by DST.\r
1579 +     */\r
1580 +    tm.tm_isdst = -1;\r
1581 +\r
1582 +    /* Special case: rounding with week accuracy. */\r
1583 +    if (week_round != PARSE_TIME_NO_ROUND) {\r
1584 +       /* Normalize to get proper tm.wday. */\r
1585 +       r = normalize_tm (&tm);\r
1586 +       if (r < 0)\r
1587 +           return r;\r
1588 +\r
1589 +       /* Set more accurate fields back to zero. */\r
1590 +       tm.tm_sec = 0;\r
1591 +       tm.tm_min = 0;\r
1592 +       tm.tm_hour = 0;\r
1593 +       tm.tm_isdst = -1;\r
1594 +\r
1595 +       /* Monday is the true 1st day of week, but this is easier. */\r
1596 +       if (week_round <= PARSE_TIME_ROUND_DOWN)\r
1597 +           tm.tm_mday -= tm.tm_wday;\r
1598 +       else\r
1599 +           tm.tm_mday += 7 - tm.tm_wday;\r
1600 +    }\r
1601 +\r
1602 +    if (is_field_set (state, TM_TZ)) {\r
1603 +       /* tm is in specified TZ, convert to UTC for timegm(3). */\r
1604 +       tm.tm_min -= get_field (state, TM_TZ);\r
1605 +       t = timegm (&tm);\r
1606 +    } else {\r
1607 +       /* tm is in local time. */\r
1608 +       t = mktime (&tm);\r
1609 +    }\r
1610 +\r
1611 +    if (t == (time_t) -1)\r
1612 +       return -PARSE_TIME_ERR_LIB;\r
1613 +\r
1614 +    *t_out = t;\r
1615 +\r
1616 +    return 0;\r
1617 +}\r
1618 +\r
1619 +/* Internally, all errors are < 0. parse_time_string() returns errors > 0. */\r
1620 +#define EXTERNAL_ERR(r) (-r)\r
1621 +\r
1622 +int\r
1623 +parse_time_string (const char *s, time_t *t, const time_t *now, int round)\r
1624 +{\r
1625 +    struct state state = { .last_field = TM_NONE };\r
1626 +    int r;\r
1627 +\r
1628 +    if (!s || !t)\r
1629 +       return EXTERNAL_ERR (-PARSE_TIME_ERR);\r
1630 +\r
1631 +    r = parse_input (&state, s);\r
1632 +    if (r < 0)\r
1633 +       return EXTERNAL_ERR (r);\r
1634 +\r
1635 +    r = create_output (&state, t, now, round);\r
1636 +    if (r < 0)\r
1637 +       return EXTERNAL_ERR (r);\r
1638 +\r
1639 +    return 0;\r
1640 +}\r
1641 diff --git a/parse-time-string/parse-time-string.h b/parse-time-string/parse-time-string.h\r
1642 new file mode 100644\r
1643 index 0000000..50b7c6f\r
1644 --- /dev/null\r
1645 +++ b/parse-time-string/parse-time-string.h\r
1646 @@ -0,0 +1,95 @@\r
1647 +/*\r
1648 + * parse time string - user friendly date and time parser\r
1649 + * Copyright © 2012 Jani Nikula\r
1650 + *\r
1651 + * This program is free software: you can redistribute it and/or modify\r
1652 + * it under the terms of the GNU General Public License as published by\r
1653 + * the Free Software Foundation, either version 2 of the License, or\r
1654 + * (at your option) any later version.\r
1655 + *\r
1656 + * This program is distributed in the hope that it will be useful,\r
1657 + * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
1658 + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
1659 + * GNU General Public License for more details.\r
1660 + *\r
1661 + * You should have received a copy of the GNU General Public License\r
1662 + * along with this program.  If not, see <http://www.gnu.org/licenses/>.\r
1663 + *\r
1664 + * Author: Jani Nikula <jani@nikula.org>\r
1665 + */\r
1666 +\r
1667 +#ifndef PARSE_TIME_STRING_H\r
1668 +#define PARSE_TIME_STRING_H\r
1669 +\r
1670 +#ifdef __cplusplus\r
1671 +extern "C" {\r
1672 +#endif\r
1673 +\r
1674 +#include <time.h>\r
1675 +\r
1676 +/* return values for parse_time_string() */\r
1677 +enum {\r
1678 +    PARSE_TIME_OK = 0,\r
1679 +    PARSE_TIME_ERR,            /* unspecified error */\r
1680 +    PARSE_TIME_ERR_LIB,                /* library call failed */\r
1681 +    PARSE_TIME_ERR_ALREADYSET, /* attempt to set unit twice */\r
1682 +    PARSE_TIME_ERR_FORMAT,     /* generic date/time format error */\r
1683 +    PARSE_TIME_ERR_DATEFORMAT, /* date format error */\r
1684 +    PARSE_TIME_ERR_TIMEFORMAT, /* time format error */\r
1685 +    PARSE_TIME_ERR_INVALIDDATE,        /* date value error */\r
1686 +    PARSE_TIME_ERR_INVALIDTIME,        /* time value error */\r
1687 +    PARSE_TIME_ERR_KEYWORD,    /* unknown keyword */\r
1688 +};\r
1689 +\r
1690 +/* round values for parse_time_string() */\r
1691 +enum {\r
1692 +    PARSE_TIME_ROUND_DOWN = -1,\r
1693 +    PARSE_TIME_NO_ROUND = 0,\r
1694 +    PARSE_TIME_ROUND_UP = 1,\r
1695 +};\r
1696 +\r
1697 +/**\r
1698 + * parse_time_string() - user friendly date and time parser\r
1699 + * @s:         string to parse\r
1700 + * @t:         pointer to time_t to store parsed time in\r
1701 + * @now:       pointer to time_t containing reference date/time, or NULL\r
1702 + * @round:     PARSE_TIME_NO_ROUND, PARSE_TIME_ROUND_DOWN, or\r
1703 + *             PARSE_TIME_ROUND_UP\r
1704 + *\r
1705 + * Parse a date/time string 's' and store the parsed date/time result\r
1706 + * in 't'.\r
1707 + *\r
1708 + * A reference date/time is used for determining the "date/time units"\r
1709 + * (roughly equivalent to struct tm members) not specified by 's'. If\r
1710 + * 'now' is non-NULL, it must contain a pointer to a time_t to be used\r
1711 + * as reference date/time. Otherwise, the current time is used.\r
1712 + *\r
1713 + * If 's' does not specify a full date/time, the 'round' parameter\r
1714 + * specifies if and how the result should be rounded as follows:\r
1715 + *\r
1716 + *   PARSE_TIME_NO_ROUND: All date/time units that are not specified\r
1717 + *   by 's' are set to the corresponding unit derived from the\r
1718 + *   reference date/time.\r
1719 + *\r
1720 + *   PARSE_TIME_ROUND_DOWN: All date/time units that are more accurate\r
1721 + *   than the most accurate unit specified by 's' are set to the\r
1722 + *   smallest valid value for that unit. Rest of the unspecified units\r
1723 + *   are set as in PARSE_TIME_NO_ROUND.\r
1724 + *\r
1725 + *   PARSE_TIME_ROUND_UP: All date/time units that are more accurate\r
1726 + *   than the most accurate unit specified by 's' are set to the\r
1727 + *   smallest valid value for that unit. The most accurate unit\r
1728 + *   specified by 's' is incremented by one (and this is rolled over\r
1729 + *   to the less accurate units as necessary). Rest of the unspecified\r
1730 + *   units are set as in PARSE_TIME_NO_ROUND.\r
1731 + *\r
1732 + * Return 0 (PARSE_TIME_OK) for succesfully parsed date/time, or one\r
1733 + * of PARSE_TIME_ERR_* on error. 't' is not modified on error.\r
1734 + */\r
1735 +int parse_time_string (const char *s, time_t *t, const time_t *now, int round);\r
1736 +\r
1737 +#ifdef __cplusplus\r
1738 +}\r
1739 +#endif\r
1740 +\r
1741 +#endif /* PARSE_TIME_STRING_H */\r
1742 -- \r
1743 1.7.9.5\r
1744 \r