Changeset c2b0e10 in mainline for uspace/lib/c/generic/time.c


Ignore:
Timestamp:
2012-04-23T21:42:27Z (13 years ago)
Author:
Maurizio Lombardi <m.lombardi85@…>
Branches:
lfn, master, serial, ticket/834-toolchain-update, topic/msim-upgrade, topic/simplify-dev-export
Children:
5b3394c
Parents:
cb948777
Message:

libc: move mktime() and strftime() from libposix to libc, remove the helper functions left
unused in libposix.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • uspace/lib/c/generic/time.c

    rcb948777 rc2b0e10  
    11/*
    22 * Copyright (c) 2006 Ondrej Palkovsky
     3 * Copyright (c) 2011 Petr Koupy
     4 * Copyright (c) 2011 Jiri Zarevucky
    35 * All rights reserved.
    46 *
     
    4345#include <ddi.h>
    4446#include <libc.h>
     47#include <stdint.h>
     48#include <stdio.h>
     49#include <ctype.h>
    4550
    4651/** Pointer to kernel shared variables with time */
     
    5055        volatile sysarg_t seconds2;
    5156} *ktime = NULL;
     57
     58/* Helper functions ***********************************************************/
     59
     60#define HOURS_PER_DAY (24)
     61#define MINS_PER_HOUR (60)
     62#define SECS_PER_MIN (60)
     63#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
     64#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
     65#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
     66
     67/**
     68 * Checks whether the year is a leap year.
     69 *
     70 * @param year Year since 1900 (e.g. for 1970, the value is 70).
     71 * @return true if year is a leap year, false otherwise
     72 */
     73static bool _is_leap_year(time_t year)
     74{
     75        year += 1900;
     76
     77        if (year % 400 == 0)
     78                return true;
     79        if (year % 100 == 0)
     80                return false;
     81        if (year % 4 == 0)
     82                return true;
     83        return false;
     84}
     85
     86/**
     87 * Returns how many days there are in the given month of the given year.
     88 * Note that year is only taken into account if month is February.
     89 *
     90 * @param year Year since 1900 (can be negative).
     91 * @param mon Month of the year. 0 for January, 11 for December.
     92 * @return Number of days in the specified month.
     93 */
     94static int _days_in_month(time_t year, time_t mon)
     95{
     96        assert(mon >= 0 && mon <= 11);
     97
     98        static int month_days[] =
     99                { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
     100
     101        if (mon == 1) {
     102                year += 1900;
     103                /* february */
     104                return _is_leap_year(year) ? 29 : 28;
     105        } else {
     106                return month_days[mon];
     107        }
     108}
     109
     110/**
     111 * For specified year, month and day of month, returns which day of that year
     112 * it is.
     113 *
     114 * For example, given date 2011-01-03, the corresponding expression is:
     115 *     _day_of_year(111, 0, 3) == 2
     116 *
     117 * @param year Year (year 1900 = 0, can be negative).
     118 * @param mon Month (January = 0).
     119 * @param mday Day of month (First day is 1).
     120 * @return Day of year (First day is 0).
     121 */
     122static int _day_of_year(time_t year, time_t mon, time_t mday)
     123{
     124        static int mdays[] =
     125            { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
     126        static int leap_mdays[] =
     127            { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
     128
     129        return (_is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
     130}
     131
     132/**
     133 * Integer division that rounds to negative infinity.
     134 * Used by some functions in this file.
     135 *
     136 * @param op1 Dividend.
     137 * @param op2 Divisor.
     138 * @return Rounded quotient.
     139 */
     140static time_t _floor_div(time_t op1, time_t op2)
     141{
     142        if (op1 >= 0 || op1 % op2 == 0) {
     143                return op1 / op2;
     144        } else {
     145                return op1 / op2 - 1;
     146        }
     147}
     148
     149/**
     150 * Modulo that rounds to negative infinity.
     151 * Used by some functions in this file.
     152 *
     153 * @param op1 Dividend.
     154 * @param op2 Divisor.
     155 * @return Remainder.
     156 */
     157static time_t _floor_mod(time_t op1, time_t op2)
     158{
     159        int div = _floor_div(op1, op2);
     160
     161        /* (a / b) * b + a % b == a */
     162        /* thus, a % b == a - (a / b) * b */
     163
     164        int result = op1 - div * op2;
     165       
     166        /* Some paranoid checking to ensure I didn't make a mistake here. */
     167        assert(result >= 0);
     168        assert(result < op2);
     169        assert(div * op2 + result == op1);
     170       
     171        return result;
     172}
     173
     174/**
     175 * Number of days since the Epoch.
     176 * Epoch is 1970-01-01, which is also equal to day 0.
     177 *
     178 * @param year Year (year 1900 = 0, may be negative).
     179 * @param mon Month (January = 0).
     180 * @param mday Day of month (first day = 1).
     181 * @return Number of days since the Epoch.
     182 */
     183static time_t _days_since_epoch(time_t year, time_t mon, time_t mday)
     184{
     185        return (year - 70) * 365 + _floor_div(year - 69, 4) -
     186            _floor_div(year - 1, 100) + _floor_div(year + 299, 400) +
     187            _day_of_year(year, mon, mday);
     188}
     189
     190/**
     191 * Seconds since the Epoch. see also _days_since_epoch().
     192 *
     193 * @param tm Normalized broken-down time.
     194 * @return Number of seconds since the epoch, not counting leap seconds.
     195 */
     196static time_t _secs_since_epoch(const struct tm *tm)
     197{
     198        return _days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
     199            SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
     200            tm->tm_min * SECS_PER_MIN + tm->tm_sec;
     201}
     202
     203/**
     204 * Which day of week the specified date is.
     205 *
     206 * @param year Year (year 1900 = 0).
     207 * @param mon Month (January = 0).
     208 * @param mday Day of month (first = 1).
     209 * @return Day of week (Sunday = 0).
     210 */
     211static int _day_of_week(time_t year, time_t mon, time_t mday)
     212{
     213        /* 1970-01-01 is Thursday */
     214        return _floor_mod((_days_since_epoch(year, mon, mday) + 4), 7);
     215}
     216
     217/**
     218 * Normalizes the broken-down time and optionally adds specified amount of
     219 * seconds.
     220 *
     221 * @param tm Broken-down time to normalize.
     222 * @param sec_add Seconds to add.
     223 * @return 0 on success, -1 on overflow
     224 */
     225static int _normalize_time(struct tm *tm, time_t sec_add)
     226{
     227        // TODO: DST correction
     228
     229        /* Set initial values. */
     230        time_t sec = tm->tm_sec + sec_add;
     231        time_t min = tm->tm_min;
     232        time_t hour = tm->tm_hour;
     233        time_t day = tm->tm_mday - 1;
     234        time_t mon = tm->tm_mon;
     235        time_t year = tm->tm_year;
     236
     237        /* Adjust time. */
     238        min += _floor_div(sec, SECS_PER_MIN);
     239        sec = _floor_mod(sec, SECS_PER_MIN);
     240        hour += _floor_div(min, MINS_PER_HOUR);
     241        min = _floor_mod(min, MINS_PER_HOUR);
     242        day += _floor_div(hour, HOURS_PER_DAY);
     243        hour = _floor_mod(hour, HOURS_PER_DAY);
     244
     245        /* Adjust month. */
     246        year += _floor_div(mon, 12);
     247        mon = _floor_mod(mon, 12);
     248
     249        /* Now the difficult part - days of month. */
     250       
     251        /* First, deal with whole cycles of 400 years = 146097 days. */
     252        year += _floor_div(day, 146097) * 400;
     253        day = _floor_mod(day, 146097);
     254       
     255        /* Then, go in one year steps. */
     256        if (mon <= 1) {
     257                /* January and February. */
     258                while (day > 365) {
     259                        day -= _is_leap_year(year) ? 366 : 365;
     260                        year++;
     261                }
     262        } else {
     263                /* Rest of the year. */
     264                while (day > 365) {
     265                        day -= _is_leap_year(year + 1) ? 366 : 365;
     266                        year++;
     267                }
     268        }
     269       
     270        /* Finally, finish it off month per month. */
     271        while (day >= _days_in_month(year, mon)) {
     272                day -= _days_in_month(year, mon);
     273                mon++;
     274                if (mon >= 12) {
     275                        mon -= 12;
     276                        year++;
     277                }
     278        }
     279       
     280        /* Calculate the remaining two fields. */
     281        tm->tm_yday = _day_of_year(year, mon, day + 1);
     282        tm->tm_wday = _day_of_week(year, mon, day + 1);
     283       
     284        /* And put the values back to the struct. */
     285        tm->tm_sec = (int) sec;
     286        tm->tm_min = (int) min;
     287        tm->tm_hour = (int) hour;
     288        tm->tm_mday = (int) day + 1;
     289        tm->tm_mon = (int) mon;
     290       
     291        /* Casts to work around libc brain-damage. */
     292        if (year > ((int)INT_MAX) || year < ((int)INT_MIN)) {
     293                tm->tm_year = (year < 0) ? ((int)INT_MIN) : ((int)INT_MAX);
     294                return -1;
     295        }
     296       
     297        tm->tm_year = (int) year;
     298        return 0;
     299}
     300
     301/**
     302 * Which day the week-based year starts on, relative to the first calendar day.
     303 * E.g. if the year starts on December 31st, the return value is -1.
     304 *
     305 * @param Year since 1900.
     306 * @return Offset of week-based year relative to calendar year.
     307 */
     308static int _wbyear_offset(int year)
     309{
     310        int start_wday = _day_of_week(year, 0, 1);
     311        return _floor_mod(4 - start_wday, 7) - 3;
     312}
     313
     314/**
     315 * Returns week-based year of the specified time.
     316 *
     317 * @param tm Normalized broken-down time.
     318 * @return Week-based year.
     319 */
     320static int _wbyear(const struct tm *tm)
     321{
     322        int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
     323        if (day < 0) {
     324                /* Last week of previous year. */
     325                return tm->tm_year - 1;
     326        }
     327        if (day > 364 + _is_leap_year(tm->tm_year)) {
     328                /* First week of next year. */
     329                return tm->tm_year + 1;
     330        }
     331        /* All the other days are in the calendar year. */
     332        return tm->tm_year;
     333}
     334
     335/**
     336 * Week number of the year, assuming weeks start on sunday.
     337 * The first Sunday of January is the first day of week 1;
     338 * days in the new year before this are in week 0.
     339 *
     340 * @param tm Normalized broken-down time.
     341 * @return The week number (0 - 53).
     342 */
     343static int _sun_week_number(const struct tm *tm)
     344{
     345        int first_day = (7 - _day_of_week(tm->tm_year, 0, 1)) % 7;
     346        return (tm->tm_yday - first_day + 7) / 7;
     347}
     348
     349/**
     350 * Week number of the year, assuming weeks start on monday.
     351 * If the week containing January 1st has four or more days in the new year,
     352 * then it is considered week 1. Otherwise, it is the last week of the previous
     353 * year, and the next week is week 1. Both January 4th and the first Thursday
     354 * of January are always in week 1.
     355 *
     356 * @param tm Normalized broken-down time.
     357 * @return The week number (1 - 53).
     358 */
     359static int _iso_week_number(const struct tm *tm)
     360{
     361        int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
     362        if (day < 0) {
     363                /* Last week of previous year. */
     364                return 53;
     365        }
     366        if (day > 364 + _is_leap_year(tm->tm_year)) {
     367                /* First week of next year. */
     368                return 1;
     369        }
     370        /* All the other days give correct answer. */
     371        return (day / 7 + 1);
     372}
     373
     374/**
     375 * Week number of the year, assuming weeks start on monday.
     376 * The first Monday of January is the first day of week 1;
     377 * days in the new year before this are in week 0.
     378 *
     379 * @param tm Normalized broken-down time.
     380 * @return The week number (0 - 53).
     381 */
     382static int _mon_week_number(const struct tm *tm)
     383{
     384        int first_day = (1 - _day_of_week(tm->tm_year, 0, 1)) % 7;
     385        return (tm->tm_yday - first_day + 7) / 7;
     386}
     387
     388/******************************************************************************/
     389
    52390
    53391/** Add microseconds to given timeval.
     
    228566}
    229567
     568/**
     569 * This function first normalizes the provided broken-down time
     570 * (moves all values to their proper bounds) and then tries to
     571 * calculate the appropriate time_t representation.
     572 *
     573 * @param tm Broken-down time.
     574 * @return time_t representation of the time, undefined value on overflow.
     575 */
     576time_t mktime(struct tm *tm)
     577{
     578        // TODO: take DST flag into account
     579        // TODO: detect overflow
     580
     581        _normalize_time(tm, 0);
     582        return _secs_since_epoch(tm);
     583}
     584
     585/**
     586 * Convert time and date to a string, based on a specified format and
     587 * current locale.
     588 *
     589 * @param s Buffer to write string to.
     590 * @param maxsize Size of the buffer.
     591 * @param format Format of the output.
     592 * @param tm Broken-down time to format.
     593 * @return Number of bytes written.
     594 */
     595size_t strftime(char *restrict s, size_t maxsize,
     596    const char *restrict format, const struct tm *restrict tm)
     597{
     598        assert(s != NULL);
     599        assert(format != NULL);
     600        assert(tm != NULL);
     601
     602        // TODO: use locale
     603        static const char *wday_abbr[] = {
     604                "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
     605        };
     606        static const char *wday[] = {
     607                "Sunday", "Monday", "Tuesday", "Wednesday",
     608                "Thursday", "Friday", "Saturday"
     609        };
     610        static const char *mon_abbr[] = {
     611                "Jan", "Feb", "Mar", "Apr", "May", "Jun",
     612                "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
     613        };
     614        static const char *mon[] = {
     615                "January", "February", "March", "April", "May", "June", "July",
     616                "August", "September", "October", "November", "December"
     617        };
     618       
     619        if (maxsize < 1) {
     620                return 0;
     621        }
     622       
     623        char *ptr = s;
     624        size_t consumed;
     625        size_t remaining = maxsize;
     626       
     627        #define append(...) { \
     628                /* FIXME: this requires POSIX-correct snprintf */ \
     629                /*        otherwise it won't work with non-ascii chars */ \
     630                consumed = snprintf(ptr, remaining, __VA_ARGS__); \
     631                if (consumed >= remaining) { \
     632                        return 0; \
     633                } \
     634                ptr += consumed; \
     635                remaining -= consumed; \
     636        }
     637       
     638        #define recurse(fmt) { \
     639                consumed = strftime(ptr, remaining, fmt, tm); \
     640                if (consumed == 0) { \
     641                        return 0; \
     642                } \
     643                ptr += consumed; \
     644                remaining -= consumed; \
     645        }
     646       
     647        #define TO_12H(hour) (((hour) > 12) ? ((hour) - 12) : \
     648            (((hour) == 0) ? 12 : (hour)))
     649       
     650        while (*format != '\0') {
     651                if (*format != '%') {
     652                        append("%c", *format);
     653                        format++;
     654                        continue;
     655                }
     656               
     657                format++;
     658                if (*format == '0' || *format == '+') {
     659                        // TODO: padding
     660                        format++;
     661                }
     662                while (isdigit(*format)) {
     663                        // TODO: padding
     664                        format++;
     665                }
     666                if (*format == 'O' || *format == 'E') {
     667                        // TODO: locale's alternative format
     668                        format++;
     669                }
     670               
     671                switch (*format) {
     672                case 'a':
     673                        append("%s", wday_abbr[tm->tm_wday]); break;
     674                case 'A':
     675                        append("%s", wday[tm->tm_wday]); break;
     676                case 'b':
     677                        append("%s", mon_abbr[tm->tm_mon]); break;
     678                case 'B':
     679                        append("%s", mon[tm->tm_mon]); break;
     680                case 'c':
     681                        // TODO: locale-specific datetime format
     682                        recurse("%Y-%m-%d %H:%M:%S"); break;
     683                case 'C':
     684                        append("%02d", (1900 + tm->tm_year) / 100); break;
     685                case 'd':
     686                        append("%02d", tm->tm_mday); break;
     687                case 'D':
     688                        recurse("%m/%d/%y"); break;
     689                case 'e':
     690                        append("%2d", tm->tm_mday); break;
     691                case 'F':
     692                        recurse("%+4Y-%m-%d"); break;
     693                case 'g':
     694                        append("%02d", _wbyear(tm) % 100); break;
     695                case 'G':
     696                        append("%d", _wbyear(tm)); break;
     697                case 'h':
     698                        recurse("%b"); break;
     699                case 'H':
     700                        append("%02d", tm->tm_hour); break;
     701                case 'I':
     702                        append("%02d", TO_12H(tm->tm_hour)); break;
     703                case 'j':
     704                        append("%03d", tm->tm_yday); break;
     705                case 'k':
     706                        append("%2d", tm->tm_hour); break;
     707                case 'l':
     708                        append("%2d", TO_12H(tm->tm_hour)); break;
     709                case 'm':
     710                        append("%02d", tm->tm_mon); break;
     711                case 'M':
     712                        append("%02d", tm->tm_min); break;
     713                case 'n':
     714                        append("\n"); break;
     715                case 'p':
     716                        append("%s", tm->tm_hour < 12 ? "AM" : "PM"); break;
     717                case 'P':
     718                        append("%s", tm->tm_hour < 12 ? "am" : "PM"); break;
     719                case 'r':
     720                        recurse("%I:%M:%S %p"); break;
     721                case 'R':
     722                        recurse("%H:%M"); break;
     723                case 's':
     724                        append("%ld", _secs_since_epoch(tm)); break;
     725                case 'S':
     726                        append("%02d", tm->tm_sec); break;
     727                case 't':
     728                        append("\t"); break;
     729                case 'T':
     730                        recurse("%H:%M:%S"); break;
     731                case 'u':
     732                        append("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
     733                        break;
     734                case 'U':
     735                        append("%02d", _sun_week_number(tm)); break;
     736                case 'V':
     737                        append("%02d", _iso_week_number(tm)); break;
     738                case 'w':
     739                        append("%d", tm->tm_wday); break;
     740                case 'W':
     741                        append("%02d", _mon_week_number(tm)); break;
     742                case 'x':
     743                        // TODO: locale-specific date format
     744                        recurse("%Y-%m-%d"); break;
     745                case 'X':
     746                        // TODO: locale-specific time format
     747                        recurse("%H:%M:%S"); break;
     748                case 'y':
     749                        append("%02d", tm->tm_year % 100); break;
     750                case 'Y':
     751                        append("%d", 1900 + tm->tm_year); break;
     752                case 'z':
     753                        // TODO: timezone
     754                        break;
     755                case 'Z':
     756                        // TODO: timezone
     757                        break;
     758                case '%':
     759                        append("%%");
     760                        break;
     761                default:
     762                        /* Invalid specifier, print verbatim. */
     763                        while (*format != '%') {
     764                                format--;
     765                        }
     766                        append("%%");
     767                        break;
     768                }
     769                format++;
     770        }
     771       
     772        #undef append
     773        #undef recurse
     774       
     775        return maxsize - remaining;
     776}
     777
     778
    230779/** @}
    231780 */
Note: See TracChangeset for help on using the changeset viewer.