Skip to content
Myr

iso8601.c

This file

Path

src/iso8601.c

342 lines · 9.9 KiB · C

Last changed by

Parse the full ISO 8601 grammar in `fromdateiso8601` (#3617)itchynybefore adoptionfd25c3e

History of this file

Take it

Parse the full ISO 8601 grammar in `fromdateiso8601` (#3617)itchynybefore adoptionfd25c3e

lines 1–342why, one step back
1/*
2 * A self-contained ISO 8601 date and time parser.3 *4 * The C library is of no help here: strptime() has no format specifier for5 * fractional seconds, and no portable way to parse week dates (glibc6 * consumes %G and %V but then discards them). The results would also7 * differ between the host strptime() and the copy bundled in util.c.8 * Everything below is plain integer arithmetic instead, which also keeps9 * the computation clear of the range of a 32-bit time_t.10 *11 * The accepted grammar is12 *13 * datetime := date [ ("T"|"t"|" ") time ]14 * date := year "-" MM "-" DD | year MMDD15 * | year "-" DDD | year DDD16 * | year "-" ("W"|"w") ww "-" d | year ("W"|"w") ww d17 * year := YYYY | ("+"|"-") YYYYYY18 * time := hms [ ("."|",") digits ] [ offset ]19 * hms := hh [ ":" mm [ ":" ss ] ] | hh [ mm [ ss ] ]20 * offset := ("Z"|"z") | ("+"|"-") hh [ [":"] mm ]21 *22 * As in the standard's own notation a run of letters stands for that many23 * decimal digits -- DDD is the three-digit day of the year, d the one-digit24 * day of the week -- while "digits" is one or more of them.25 *26 * The decimal fraction belongs to the lowest component of the hms that is27 * present, so "23,5" is half past 23 and "2320,8" is 23:20:48.28 *29 * The date must always be complete, so "2015-03" is an error even though it30 * is a valid ISO 8601 date. The time may drop its seconds, or its minutes31 * and seconds, or be omitted altogether, in which case the value is32 * midnight UTC. The date and the time must agree on whether separators are33 * used, as ISO 8601 requires -- "2026-08-28T093015Z" is not a valid34 * representation. The offset is exempt from that rule, since "+0900" after35 * an extended time is common in the wild.36 */3738#include <stdint.h>3940#include "iso8601.h"4142/*43 * Days since 1970-01-01 of the civil date y-m-d in the proleptic Gregorian44 * calendar, negative before the epoch, after Howard Hinnant's45 * days_from_civil(). Requires 1 <= m <= 12 and 1 <= d <= days_in_month(y, m);46 * the callers check both.47 */48static int64_t days_from_civil(int64_t y, int m, int d) {49 y -= m <= 2;50 int64_t era = (y >= 0 ? y : y - 399) / 400;51 int64_t yoe = y - era * 400; /* [0, 399] */52 int64_t doy = (153 * (m + (m > 2 ? -3 : 9)) + 2) / 5 + d - 1; /* [0, 365] */53 int64_t doe = yoe * 365 + yoe / 4 - yoe / 100 + doy; /* [0, 146096] */54 return era * 146097 + doe - 719468;55}5657static int is_leap(int64_t y) {58 return (y % 4 == 0 && y % 100 != 0) || y % 400 == 0;59}6061static int days_in_month(int64_t y, int m) {62 static const int d[] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};63 return m == 2 && is_leap(y) ? 29 : d[m - 1];64}6566/* ISO weekday (1 = Monday .. 7 = Sunday) of a day count since the epoch. */67static int iso_wday(int64_t days) {68 int64_t w = (days + 3) % 7;69 if (w < 0)70 w += 7;71 return (int)w + 1;72}7374/*75 * An ISO year has 53 weeks if it starts on a Thursday, or if it is a leap76 * year starting on a Wednesday; otherwise it has 52.77 */78static int iso_weeks_in_year(int64_t y) {79 int jan1 = iso_wday(days_from_civil(y, 1, 1));80 return jan1 == 4 || (jan1 == 3 && is_leap(y)) ? 53 : 52;81}8283static int civil_to_days(int64_t y, int mon, int mday, int64_t *days) {84 if (mon < 1 || mon > 12 || mday < 1 || mday > days_in_month(y, mon))85 return 0;86 *days = days_from_civil(y, mon, mday);87 return 1;88}8990static int ordinal_to_days(int64_t y, int yday, int64_t *days) {91 if (yday < 1 || yday > (is_leap(y) ? 366 : 365))92 return 0;93 *days = days_from_civil(y, 1, 1) + yday - 1;94 return 1;95}9697static int week_to_days(int64_t y, int week, int wday, int64_t *days) {98 if (week < 1 || week > iso_weeks_in_year(y) || wday < 1 || wday > 7)99 return 0;100 int64_t jan4 = days_from_civil(y, 1, 4);101 *days = jan4 - (iso_wday(jan4) - 1) + (int64_t)(week - 1) * 7 + (wday - 1);102 return 1;103}104105/*106 * The scanner works over an explicit [p, end) range rather than a C string, so107 * that a NUL byte embedded in the input is a parse error instead of silently108 * truncating the value.109 */110typedef struct {111 const char *p;112 const char *end;113} iso8601_scanner;114115static int scan_at_end(iso8601_scanner *s) {116 return s->p == s->end;117}118119static int scan_peek(iso8601_scanner *s) {120 return scan_at_end(s) ? -1 : (unsigned char)*s->p;121}122123static int scan_eat(iso8601_scanner *s, char c) {124 if (scan_at_end(s) || *s->p != c)125 return 0;126 s->p++;127 return 1;128}129130/*131 * W, T and Z are what ISO 8601 calls designators. They are written in upper132 * case, but the standard notes that "lower case characters may be used when133 * upper case characters are not available", so match either.134 */135static int scan_designator(iso8601_scanner *s, char c) {136 if (scan_at_end(s) || (*s->p != c && *s->p != c + ('a' - 'A')))137 return 0;138 s->p++;139 return 1;140}141142static size_t scan_count_digits(iso8601_scanner *s) {143 size_t n = 0;144 while (s->p + n < s->end && s->p[n] >= '0' && s->p[n] <= '9')145 n++;146 return n;147}148149static int scan_digits(iso8601_scanner *s, int n, int *out) {150 if (s->end - s->p < n)151 return 0;152 int v = 0;153 for (int i = 0; i < n; i++) {154 unsigned char c = (unsigned char)s->p[i];155 if (c < '0' || c > '9')156 return 0;157 v = v * 10 + (c - '0');158 }159 s->p += n;160 *out = v;161 return 1;162}163164/*165 * A plain year is exactly four digits. An expanded year carries a mandatory166 * sign and exactly six digits, which is what makes it unambiguous in front of167 * a date in the basic form.168 */169static int parse_year(iso8601_scanner *s, int64_t *year) {170 int64_t sign = 1;171 int digits = 4;172 if (scan_peek(s) == '+' || scan_peek(s) == '-') {173 sign = *s->p == '-' ? -1 : 1;174 s->p++;175 digits = 6;176 }177 if (s->end - s->p < digits)178 return 0;179 int64_t v = 0;180 for (int i = 0; i < digits; i++) {181 unsigned char c = (unsigned char)s->p[i];182 if (c < '0' || c > '9')183 return 0;184 v = v * 10 + (c - '0');185 }186 s->p += digits;187 *year = sign * v;188 return 1;189}190191/* Sets *extended to whether the date was written with "-" separators. */192static int parse_date(iso8601_scanner *s, int64_t *days, int *extended) {193 int64_t year;194 int week, wday, mon, mday, yday;195196 if (!parse_year(s, &year))197 return 0;198199 if (scan_eat(s, '-')) {200 *extended = 1;201 if (scan_designator(s, 'W')) {202 return scan_digits(s, 2, &week) && scan_eat(s, '-') &&203 scan_digits(s, 1, &wday) && week_to_days(year, week, wday, days);204 }205 switch (scan_count_digits(s)) {206 case 3:207 return scan_digits(s, 3, &yday) && ordinal_to_days(year, yday, days);208 case 2:209 return scan_digits(s, 2, &mon) && scan_eat(s, '-') &&210 scan_digits(s, 2, &mday) && civil_to_days(year, mon, mday, days);211 default:212 return 0;213 }214 }215216 *extended = 0;217 if (scan_designator(s, 'W')) {218 return scan_digits(s, 2, &week) && scan_digits(s, 1, &wday) &&219 week_to_days(year, week, wday, days);220 }221 switch (scan_count_digits(s)) {222 case 4:223 return scan_digits(s, 2, &mon) && scan_digits(s, 2, &mday) &&224 civil_to_days(year, mon, mday, days);225 case 3:226 return scan_digits(s, 3, &yday) && ordinal_to_days(year, yday, days);227 default:228 /* A bare "YYYYMM" is ambiguous with "YYMMDD"; the standard forbids it. */229 return 0;230 }231}232233/*234 * Parses the time of day, storing the seconds since midnight in *secs. A235 * time of "24:00:00" is midnight of the following day, which *carry reports.236 *237 * The minutes and seconds may be omitted, in which case the decimal fraction238 * belongs to the lowest component that is present -- "23,5" is half past 23239 * -- so *unit* records how many seconds that component is worth.240 */241static int parse_time(iso8601_scanner *s, int extended, double *secs,242 int64_t *carry) {243 int hh, mm = 0, ss = 0, unit = 3600;244245 if (!scan_digits(s, 2, &hh))246 return 0;247 if (extended ? scan_eat(s, ':') : scan_count_digits(s) >= 2) {248 if (!scan_digits(s, 2, &mm))249 return 0;250 unit = 60;251 if (extended ? scan_eat(s, ':') : scan_count_digits(s) >= 2) {252 if (!scan_digits(s, 2, &ss))253 return 0;254 unit = 1;255 }256 }257258 double frac = 0;259 if (scan_peek(s) == '.' || scan_peek(s) == ',') {260 static const double pow10[] = {261 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7,262 1e8, 1e9, 1e10, 1e11, 1e12, 1e13, 1e14, 1e15263 };264 s->p++;265 if (scan_count_digits(s) == 0)266 return 0;267 uint64_t num = 0;268 int digits = 0;269 while (scan_peek(s) >= '0' && scan_peek(s) <= '9') {270 if (digits < 15) {271 num = num * 10 + (uint64_t)(*s->p - '0');272 digits++;273 }274 s->p++;275 }276 frac = (double)num / pow10[digits];277 }278279 *carry = 0;280 if (hh == 24) {281 if (mm != 0 || ss != 0 || frac != 0)282 return 0;283 hh = 0;284 *carry = 1;285 } else if (hh > 24 || mm > 59 || ss > 60) {286 return 0;287 } else if (ss == 60) {288 ss = 59;289 }290291 *secs = hh * 3600 + mm * 60 + ss + frac * unit;292 return 1;293}294295/* An absent offset means UTC, which is what jq has always assumed. */296static int parse_offset(iso8601_scanner *s, int *offset) {297 if (scan_designator(s, 'Z')) {298 *offset = 0;299 return 1;300 }301302 int sign = scan_peek(s);303 if (sign != '+' && sign != '-') {304 *offset = 0;305 return 1;306 }307308 s->p++;309 int oh, om = 0;310 if (!scan_digits(s, 2, &oh))311 return 0;312 int had_colon = scan_eat(s, ':');313 if (!scan_digits(s, 2, &om) && had_colon)314 return 0;315 if (oh > 23 || om > 59)316 return 0;317318 *offset = (sign == '+' ? 1 : -1) * (oh * 3600 + om * 60);319 return 1;320}321322int iso8601_parse(const char *buf, size_t len, double *out) {323 iso8601_scanner s = {buf, buf + len};324 int64_t days, carry = 0;325 int extended, offset = 0, sep;326 double secs = 0;327328 if (!parse_date(&s, &days, &extended))329 return 0;330331 sep = scan_peek(&s);332 if (sep == 'T' || sep == 't' || sep == ' ') {333 s.p++;334 if (!parse_time(&s, extended, &secs, &carry) || !parse_offset(&s, &offset))335 return 0;336 }337 if (!scan_at_end(&s))338 return 0;339340 *out = (double)(days + carry) * 86400.0 + secs - offset;341 return 1;342}