source: mainline/uspace/lib/posix/time.c@ e7ed26be

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since e7ed26be was 55b1efd, checked in by Petr Koupy <petr.koupy@…>, 14 years ago

Minor corrections and unifications of the recently added documentation.

  • Property mode set to 100644
File size: 22.5 KB
Line 
1/*
2 * Copyright (c) 2011 Petr Koupy
3 * Copyright (c) 2011 Jiri Zarevucky
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
33/** @file Time measurement support.
34 */
35
36#define LIBPOSIX_INTERNAL
37
38/* Must be first. */
39#include "stdbool.h"
40
41#include "internal/common.h"
42#include "time.h"
43
44#include "ctype.h"
45#include "errno.h"
46#include "signal.h"
47
48#include "libc/malloc.h"
49#include "libc/task.h"
50#include "libc/stats.h"
51#include "libc/sys/time.h"
52
53// TODO: test everything in this file
54
55/* In some places in this file, phrase "normalized broken-down time" is used.
56 * This means time broken down to components (year, month, day, hour, min, sec),
57 * in which every component is in its proper bounds. Non-normalized time could
58 * e.g. be 2011-54-5 29:13:-5, which would semantically mean start of year 2011
59 * + 53 months + 4 days + 29 hours + 13 minutes - 5 seconds.
60 */
61
62
63
64/* Helper functions ***********************************************************/
65
66#define HOURS_PER_DAY (24)
67#define MINS_PER_HOUR (60)
68#define SECS_PER_MIN (60)
69#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
70#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
71#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
72
73/**
74 * Checks whether the year is a leap year.
75 *
76 * @param year Year since 1900 (e.g. for 1970, the value is 70).
77 * @return true if year is a leap year, false otherwise
78 */
79static bool _is_leap_year(time_t year)
80{
81 year += 1900;
82
83 if (year % 400 == 0)
84 return true;
85 if (year % 100 == 0)
86 return false;
87 if (year % 4 == 0)
88 return true;
89 return false;
90}
91
92/**
93 * Returns how many days there are in the given month of the given year.
94 * Note that year is only taken into account if month is February.
95 *
96 * @param year Year since 1900 (can be negative).
97 * @param mon Month of the year. 0 for January, 11 for December.
98 * @return Number of days in the specified month.
99 */
100static int _days_in_month(time_t year, time_t mon)
101{
102 assert(mon >= 0 && mon <= 11);
103
104 static int month_days[] =
105 { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
106
107 if (mon == 1) {
108 year += 1900;
109 /* february */
110 return _is_leap_year(year) ? 29 : 28;
111 } else {
112 return month_days[mon];
113 }
114}
115
116/**
117 * For specified year, month and day of month, returns which day of that year
118 * it is.
119 *
120 * For example, given date 2011-01-03, the corresponding expression is:
121 * _day_of_year(111, 0, 3) == 2
122 *
123 * @param year Year (year 1900 = 0, can be negative).
124 * @param mon Month (January = 0).
125 * @param mday Day of month (First day is 1).
126 * @return Day of year (First day is 0).
127 */
128static int _day_of_year(time_t year, time_t mon, time_t mday)
129{
130 static int mdays[] =
131 { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 };
132 static int leap_mdays[] =
133 { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 };
134
135 return (_is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
136}
137
138/**
139 * Integer division that rounds to negative infinity.
140 * Used by some functions in this file.
141 *
142 * @param op1 Divident.
143 * @param op2 Divisor.
144 * @return Rounded quotient.
145 */
146static time_t _floor_div(time_t op1, time_t op2)
147{
148 if (op1 >= 0 || op1 % op2 == 0) {
149 return op1 / op2;
150 } else {
151 return op1 / op2 - 1;
152 }
153}
154
155/**
156 * Modulo that rounds to negative infinity.
157 * Used by some functions in this file.
158 *
159 * @param op1 Divident.
160 * @param op2 Divisor.
161 * @return Remainder.
162 */
163static time_t _floor_mod(time_t op1, time_t op2)
164{
165 int div = _floor_div(op1, op2);
166
167 /* (a / b) * b + a % b == a */
168 /* thus, a % b == a - (a / b) * b */
169
170 int result = op1 - div * op2;
171
172 /* Some paranoid checking to ensure I didn't make a mistake here. */
173 assert(result >= 0);
174 assert(result < op2);
175 assert(div * op2 + result == op1);
176
177 return result;
178}
179
180/**
181 * Number of days since the Epoch.
182 * Epoch is 1970-01-01, which is also equal to day 0.
183 *
184 * @param year Year (year 1900 = 0, may be negative).
185 * @param mon Month (January = 0).
186 * @param mday Day of month (first day = 1).
187 * @return Number of days since the Epoch.
188 */
189static time_t _days_since_epoch(time_t year, time_t mon, time_t mday)
190{
191 return (year - 70) * 365 + _floor_div(year - 69, 4) -
192 _floor_div(year - 1, 100) + _floor_div(year + 299, 400) +
193 _day_of_year(year, mon, mday);
194}
195
196/**
197 * Seconds since the Epoch. see also _days_since_epoch().
198 *
199 * @param tm Normalized broken-down time.
200 * @return Number of seconds since the epoch, not counting leap seconds.
201 */
202static time_t _secs_since_epoch(const struct posix_tm *tm)
203{
204 return _days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
205 SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
206 tm->tm_min * SECS_PER_MIN + tm->tm_sec;
207}
208
209/**
210 * Which day of week the specified date is.
211 *
212 * @param year Year (year 1900 = 0).
213 * @param mon Month (January = 0).
214 * @param mday Day of month (first = 1).
215 * @return Day of week (Sunday = 0).
216 */
217static int _day_of_week(time_t year, time_t mon, time_t mday)
218{
219 /* 1970-01-01 is Thursday */
220 return _floor_mod((_days_since_epoch(year, mon, mday) + 4), 7);
221}
222
223/**
224 * Normalizes the broken-down time and optionally adds specified amount of
225 * seconds.
226 *
227 * @param tm Broken-down time to normalize.
228 * @param sec_add Seconds to add.
229 * @return 0 on success, -1 on overflow
230 */
231static int _normalize_time(struct posix_tm *tm, time_t sec_add)
232{
233 // TODO: DST correction
234
235 /* Set initial values. */
236 time_t sec = tm->tm_sec + sec_add;
237 time_t min = tm->tm_min;
238 time_t hour = tm->tm_hour;
239 time_t day = tm->tm_mday - 1;
240 time_t mon = tm->tm_mon;
241 time_t year = tm->tm_year;
242
243 /* Adjust time. */
244 min += _floor_div(sec, SECS_PER_MIN);
245 sec = _floor_mod(sec, SECS_PER_MIN);
246 hour += _floor_div(min, MINS_PER_HOUR);
247 min = _floor_mod(min, MINS_PER_HOUR);
248 day += _floor_div(hour, HOURS_PER_DAY);
249 hour = _floor_mod(hour, HOURS_PER_DAY);
250
251 /* Adjust month. */
252 year += _floor_div(mon, 12);
253 mon = _floor_mod(mon, 12);
254
255 /* Now the difficult part - days of month. */
256
257 /* First, deal with whole cycles of 400 years = 146097 days. */
258 year += _floor_div(day, 146097) * 400;
259 day = _floor_mod(day, 146097);
260
261 /* Then, go in one year steps. */
262 if (mon <= 1) {
263 /* January and February. */
264 while (day > 365) {
265 day -= _is_leap_year(year) ? 366 : 365;
266 year++;
267 }
268 } else {
269 /* Rest of the year. */
270 while (day > 365) {
271 day -= _is_leap_year(year + 1) ? 366 : 365;
272 year++;
273 }
274 }
275
276 /* Finally, finish it off month per month. */
277 while (day >= _days_in_month(year, mon)) {
278 day -= _days_in_month(year, mon);
279 mon++;
280 if (mon >= 12) {
281 mon -= 12;
282 year++;
283 }
284 }
285
286 /* Calculate the remaining two fields. */
287 tm->tm_yday = _day_of_year(year, mon, day + 1);
288 tm->tm_wday = _day_of_week(year, mon, day + 1);
289
290 /* And put the values back to the struct. */
291 tm->tm_sec = (int) sec;
292 tm->tm_min = (int) min;
293 tm->tm_hour = (int) hour;
294 tm->tm_mday = (int) day + 1;
295 tm->tm_mon = (int) mon;
296
297 /* Casts to work around libc brain-damage. */
298 if (year > ((int)INT_MAX) || year < ((int)INT_MIN)) {
299 tm->tm_year = (year < 0) ? ((int)INT_MIN) : ((int)INT_MAX);
300 return -1;
301 }
302
303 tm->tm_year = (int) year;
304 return 0;
305}
306
307/**
308 * Which day the week-based year starts on, relative to the first calendar day.
309 * E.g. if the year starts on December 31st, the return value is -1.
310 *
311 * @param Year since 1900.
312 * @return Offset of week-based year relative to calendar year.
313 */
314static int _wbyear_offset(int year)
315{
316 int start_wday = _day_of_week(year, 0, 1);
317 return _floor_mod(4 - start_wday, 7) - 3;
318}
319
320/**
321 * Returns week-based year of the specified time.
322 *
323 * @param tm Normalized broken-down time.
324 * @return Week-based year.
325 */
326static int _wbyear(const struct posix_tm *tm)
327{
328 int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
329 if (day < 0) {
330 /* Last week of previous year. */
331 return tm->tm_year - 1;
332 }
333 if (day > 364 + _is_leap_year(tm->tm_year)) {
334 /* First week of next year. */
335 return tm->tm_year + 1;
336 }
337 /* All the other days are in the calendar year. */
338 return tm->tm_year;
339}
340
341/**
342 * Week number of the year, assuming weeks start on sunday.
343 * The first Sunday of January is the first day of week 1;
344 * days in the new year before this are in week 0.
345 *
346 * @param tm Normalized broken-down time.
347 * @return The week number (0 - 53).
348 */
349static int _sun_week_number(const struct posix_tm *tm)
350{
351 int first_day = (7 - _day_of_week(tm->tm_year, 0, 1)) % 7;
352 return (tm->tm_yday - first_day + 7) / 7;
353}
354
355/**
356 * Week number of the year, assuming weeks start on monday.
357 * If the week containing January 1st has four or more days in the new year,
358 * then it is considered week 1. Otherwise, it is the last week of the previous
359 * year, and the next week is week 1. Both January 4th and the first Thursday
360 * of January are always in week 1.
361 *
362 * @param tm Normalized broken-down time.
363 * @return The week number (1 - 53).
364 */
365static int _iso_week_number(const struct posix_tm *tm)
366{
367 int day = tm->tm_yday - _wbyear_offset(tm->tm_year);
368 if (day < 0) {
369 /* Last week of previous year. */
370 return 53;
371 }
372 if (day > 364 + _is_leap_year(tm->tm_year)) {
373 /* First week of next year. */
374 return 1;
375 }
376 /* All the other days give correct answer. */
377 return (day / 7 + 1);
378}
379
380/**
381 * Week number of the year, assuming weeks start on monday.
382 * The first Monday of January is the first day of week 1;
383 * days in the new year before this are in week 0.
384 *
385 * @param tm Normalized broken-down time.
386 * @return The week number (0 - 53).
387 */
388static int _mon_week_number(const struct posix_tm *tm)
389{
390 int first_day = (1 - _day_of_week(tm->tm_year, 0, 1)) % 7;
391 return (tm->tm_yday - first_day + 7) / 7;
392}
393
394/******************************************************************************/
395
396int posix_daylight;
397long posix_timezone;
398char *posix_tzname[2];
399
400/**
401 * Set timezone conversion information.
402 */
403void posix_tzset(void)
404{
405 // TODO: read environment
406 posix_tzname[0] = (char *) "GMT";
407 posix_tzname[1] = (char *) "GMT";
408 posix_daylight = 0;
409 posix_timezone = 0;
410}
411
412/**
413 * Calculate the difference between two times, in seconds.
414 *
415 * @param time1 First time.
416 * @param time0 Second time.
417 * @return Time in seconds.
418 */
419double posix_difftime(time_t time1, time_t time0)
420{
421 return (double) (time1 - time0);
422}
423
424/**
425 * This function first normalizes the provided broken-down time
426 * (moves all values to their proper bounds) and then tries to
427 * calculate the appropriate time_t representation.
428 *
429 * @param tm Broken-down time.
430 * @return time_t representation of the time, undefined value on overflow.
431 */
432time_t posix_mktime(struct posix_tm *tm)
433{
434 // TODO: take DST flag into account
435 // TODO: detect overflow
436
437 _normalize_time(tm, 0);
438 return _secs_since_epoch(tm);
439}
440
441/**
442 * Converts a time value to a broken-down UTC time.
443 *
444 * @param timer Time to convert.
445 * @return Normalized broken-down time in UTC, NULL on overflow.
446 */
447struct posix_tm *posix_gmtime(const time_t *timer)
448{
449 assert(timer != NULL);
450
451 static struct posix_tm result;
452 return posix_gmtime_r(timer, &result);
453}
454
455/**
456 * Converts a time value to a broken-down UTC time.
457 *
458 * @param timer Time to convert.
459 * @param result Structure to store the result to.
460 * @return Value of result on success, NULL on overflow.
461 */
462struct posix_tm *posix_gmtime_r(const time_t *restrict timer,
463 struct posix_tm *restrict result)
464{
465 assert(timer != NULL);
466 assert(result != NULL);
467
468 /* Set result to epoch. */
469 result->tm_sec = 0;
470 result->tm_min = 0;
471 result->tm_hour = 0;
472 result->tm_mday = 1;
473 result->tm_mon = 0;
474 result->tm_year = 70; /* 1970 */
475
476 if (_normalize_time(result, *timer) == -1) {
477 errno = EOVERFLOW;
478 return NULL;
479 }
480
481 return result;
482}
483
484/**
485 * Converts a time value to a broken-down local time.
486 *
487 * @param timer Time to convert.
488 * @return Normalized broken-down time in local timezone, NULL on overflow.
489 */
490struct posix_tm *posix_localtime(const time_t *timer)
491{
492 static struct posix_tm result;
493 return posix_localtime_r(timer, &result);
494}
495
496/**
497 * Converts a time value to a broken-down local time.
498 *
499 * @param timer Time to convert.
500 * @param result Structure to store the result to.
501 * @return Value of result on success, NULL on overflow.
502 */
503struct posix_tm *posix_localtime_r(const time_t *restrict timer,
504 struct posix_tm *restrict result)
505{
506 // TODO: deal with timezone
507 // currently assumes system and all times are in GMT
508 return posix_gmtime_r(timer, result);
509}
510
511/**
512 * Converts broken-down time to a string in format
513 * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
514 *
515 * @param timeptr Broken-down time structure.
516 * @return Pointer to a statically allocated string.
517 */
518char *posix_asctime(const struct posix_tm *timeptr)
519{
520 static char buf[ASCTIME_BUF_LEN];
521 return posix_asctime_r(timeptr, buf);
522}
523
524/**
525 * Converts broken-down time to a string in format
526 * "Sun Jan 1 00:00:00 1970\n". (Obsolete)
527 *
528 * @param timeptr Broken-down time structure.
529 * @param buf Buffer to store string to, must be at least ASCTIME_BUF_LEN
530 * bytes long.
531 * @return Value of buf.
532 */
533char *posix_asctime_r(const struct posix_tm *restrict timeptr,
534 char *restrict buf)
535{
536 assert(timeptr != NULL);
537 assert(buf != NULL);
538
539 static const char *wday[] = {
540 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
541 };
542 static const char *mon[] = {
543 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
544 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
545 };
546
547 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
548 wday[timeptr->tm_wday],
549 mon[timeptr->tm_mon],
550 timeptr->tm_mday, timeptr->tm_hour,
551 timeptr->tm_min, timeptr->tm_sec,
552 1900 + timeptr->tm_year);
553
554 return buf;
555}
556
557/**
558 * Equivalent to asctime(localtime(clock)).
559 *
560 * @param timer Time to convert.
561 * @return Pointer to a statically allocated string holding the date.
562 */
563char *posix_ctime(const time_t *timer)
564{
565 struct posix_tm *loctime = posix_localtime(timer);
566 if (loctime == NULL) {
567 return NULL;
568 }
569 return posix_asctime(loctime);
570}
571
572/**
573 * Reentrant variant of ctime().
574 *
575 * @param timer Time to convert.
576 * @param buf Buffer to store string to. Must be at least ASCTIME_BUF_LEN
577 * bytes long.
578 * @return Pointer to buf on success, NULL on falure.
579 */
580char *posix_ctime_r(const time_t *timer, char *buf)
581{
582 struct posix_tm loctime;
583 if (posix_localtime_r(timer, &loctime) == NULL) {
584 return NULL;
585 }
586 return posix_asctime_r(&loctime, buf);
587}
588
589/**
590 * Convert time and date to a string, based on a specified format and
591 * current locale.
592 *
593 * @param s Buffer to write string to.
594 * @param maxsize Size of the buffer.
595 * @param format Format of the output.
596 * @param tm Broken-down time to format.
597 * @return Number of bytes written.
598 */
599size_t posix_strftime(char *restrict s, size_t maxsize,
600 const char *restrict format, const struct posix_tm *restrict tm)
601{
602 assert(s != NULL);
603 assert(format != NULL);
604 assert(tm != NULL);
605
606 // TODO: use locale
607 static const char *wday_abbr[] = {
608 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
609 };
610 static const char *wday[] = {
611 "Sunday", "Monday", "Tuesday", "Wednesday",
612 "Thursday", "Friday", "Saturday"
613 };
614 static const char *mon_abbr[] = {
615 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
616 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
617 };
618 static const char *mon[] = {
619 "January", "February", "March", "April", "May", "June", "July",
620 "August", "September", "October", "November", "December"
621 };
622
623 if (maxsize < 1) {
624 return 0;
625 }
626
627 char *ptr = s;
628 size_t consumed;
629 size_t remaining = maxsize;
630
631 #define append(...) { \
632 /* FIXME: this requires POSIX-correct snprintf */ \
633 /* otherwise it won't work with non-ascii chars */ \
634 consumed = snprintf(ptr, remaining, __VA_ARGS__); \
635 if (consumed >= remaining) { \
636 return 0; \
637 } \
638 ptr += consumed; \
639 remaining -= consumed; \
640 }
641
642 #define recurse(fmt) { \
643 consumed = posix_strftime(ptr, remaining, fmt, tm); \
644 if (consumed == 0) { \
645 return 0; \
646 } \
647 ptr += consumed; \
648 remaining -= consumed; \
649 }
650
651 #define TO_12H(hour) (((hour) > 12) ? ((hour) - 12) : \
652 (((hour) == 0) ? 12 : (hour)))
653
654 while (*format != '\0') {
655 if (*format != '%') {
656 append("%c", *format);
657 format++;
658 continue;
659 }
660
661 format++;
662 if (*format == '0' || *format == '+') {
663 // TODO: padding
664 format++;
665 }
666 while (isdigit(*format)) {
667 // TODO: padding
668 format++;
669 }
670 if (*format == 'O' || *format == 'E') {
671 // TODO: locale's alternative format
672 format++;
673 }
674
675 switch (*format) {
676 case 'a':
677 append("%s", wday_abbr[tm->tm_wday]); break;
678 case 'A':
679 append("%s", wday[tm->tm_wday]); break;
680 case 'b':
681 append("%s", mon_abbr[tm->tm_mon]); break;
682 case 'B':
683 append("%s", mon[tm->tm_mon]); break;
684 case 'c':
685 // TODO: locale-specific datetime format
686 recurse("%Y-%m-%d %H:%M:%S"); break;
687 case 'C':
688 append("%02d", (1900 + tm->tm_year) / 100); break;
689 case 'd':
690 append("%02d", tm->tm_mday); break;
691 case 'D':
692 recurse("%m/%d/%y"); break;
693 case 'e':
694 append("%2d", tm->tm_mday); break;
695 case 'F':
696 recurse("%+4Y-%m-%d"); break;
697 case 'g':
698 append("%02d", _wbyear(tm) % 100); break;
699 case 'G':
700 append("%d", _wbyear(tm)); break;
701 case 'h':
702 recurse("%b"); break;
703 case 'H':
704 append("%02d", tm->tm_hour); break;
705 case 'I':
706 append("%02d", TO_12H(tm->tm_hour)); break;
707 case 'j':
708 append("%03d", tm->tm_yday); break;
709 case 'k':
710 append("%2d", tm->tm_hour); break;
711 case 'l':
712 append("%2d", TO_12H(tm->tm_hour)); break;
713 case 'm':
714 append("%02d", tm->tm_mon); break;
715 case 'M':
716 append("%02d", tm->tm_min); break;
717 case 'n':
718 append("\n"); break;
719 case 'p':
720 append("%s", tm->tm_hour < 12 ? "AM" : "PM"); break;
721 case 'P':
722 append("%s", tm->tm_hour < 12 ? "am" : "PM"); break;
723 case 'r':
724 recurse("%I:%M:%S %p"); break;
725 case 'R':
726 recurse("%H:%M"); break;
727 case 's':
728 append("%ld", _secs_since_epoch(tm)); break;
729 case 'S':
730 append("%02d", tm->tm_sec); break;
731 case 't':
732 append("\t"); break;
733 case 'T':
734 recurse("%H:%M:%S"); break;
735 case 'u':
736 append("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday); break;
737 case 'U':
738 append("%02d", _sun_week_number(tm)); break;
739 case 'V':
740 append("%02d", _iso_week_number(tm)); break;
741 case 'w':
742 append("%d", tm->tm_wday); break;
743 case 'W':
744 append("%02d", _mon_week_number(tm)); break;
745 case 'x':
746 // TODO: locale-specific date format
747 recurse("%Y-%m-%d"); break;
748 case 'X':
749 // TODO: locale-specific time format
750 recurse("%H:%M:%S"); break;
751 case 'y':
752 append("%02d", tm->tm_year % 100); break;
753 case 'Y':
754 append("%d", 1900 + tm->tm_year); break;
755 case 'z':
756 // TODO: timezone
757 break;
758 case 'Z':
759 // TODO: timezone
760 break;
761 case '%':
762 append("%%");
763 break;
764 default:
765 /* Invalid specifier, print verbatim. */
766 while (*format != '%') {
767 format--;
768 }
769 append("%%");
770 break;
771 }
772 format++;
773 }
774
775 #undef append
776 #undef recurse
777
778 return maxsize - remaining;
779}
780
781/**
782 * Get clock resolution. Only CLOCK_REALTIME is supported.
783 *
784 * @param clock_id Clock ID.
785 * @param res Pointer to the variable where the resolution is to be written.
786 * @return 0 on success, -1 with errno set on failure.
787 */
788int posix_clock_getres(posix_clockid_t clock_id, struct posix_timespec *res)
789{
790 assert(res != NULL);
791
792 switch (clock_id) {
793 case CLOCK_REALTIME:
794 res->tv_sec = 0;
795 res->tv_nsec = 1000; /* Microsecond resolution. */
796 return 0;
797 default:
798 errno = EINVAL;
799 return -1;
800 }
801}
802
803/**
804 * Get time. Only CLOCK_REALTIME is supported.
805 *
806 * @param clock_id ID of the clock to query.
807 * @param tp Pointer to the variable where the time is to be written.
808 * @return 0 on success, -1 with errno on failure.
809 */
810int posix_clock_gettime(posix_clockid_t clock_id, struct posix_timespec *tp)
811{
812 assert(tp != NULL);
813
814 switch (clock_id) {
815 case CLOCK_REALTIME:
816 ;
817 struct timeval tv;
818 gettimeofday(&tv, NULL);
819 tp->tv_sec = tv.tv_sec;
820 tp->tv_nsec = tv.tv_usec * 1000;
821 return 0;
822 default:
823 errno = EINVAL;
824 return -1;
825 }
826}
827
828/**
829 * Set time on a specified clock. As HelenOS doesn't support this yet,
830 * this function always fails.
831 *
832 * @param clock_id ID of the clock to set.
833 * @param tp Time to set.
834 * @return 0 on success, -1 with errno on failure.
835 */
836int posix_clock_settime(posix_clockid_t clock_id,
837 const struct posix_timespec *tp)
838{
839 assert(tp != NULL);
840
841 switch (clock_id) {
842 case CLOCK_REALTIME:
843 // TODO: setting clock
844 // FIXME: HelenOS doesn't actually support hardware
845 // clock yet
846 errno = EPERM;
847 return -1;
848 default:
849 errno = EINVAL;
850 return -1;
851 }
852}
853
854/**
855 * Sleep on a specified clock.
856 *
857 * @param clock_id ID of the clock to sleep on (only CLOCK_REALTIME supported).
858 * @param flags Flags (none supported).
859 * @param rqtp Sleep time.
860 * @param rmtp Remaining time is written here if sleep is interrupted.
861 * @return 0 on success, -1 with errno set on failure.
862 */
863int posix_clock_nanosleep(posix_clockid_t clock_id, int flags,
864 const struct posix_timespec *rqtp, struct posix_timespec *rmtp)
865{
866 assert(rqtp != NULL);
867 assert(rmtp != NULL);
868
869 switch (clock_id) {
870 case CLOCK_REALTIME:
871 // TODO: interruptible sleep
872 if (rqtp->tv_sec != 0) {
873 sleep(rqtp->tv_sec);
874 }
875 if (rqtp->tv_nsec != 0) {
876 usleep(rqtp->tv_nsec / 1000);
877 }
878 return 0;
879 default:
880 errno = EINVAL;
881 return -1;
882 }
883}
884
885/**
886 * Get CPU time used since the process invocation.
887 *
888 * @return Consumed CPU cycles by this process or -1 if not available.
889 */
890posix_clock_t posix_clock(void)
891{
892 posix_clock_t total_cycles = -1;
893 stats_task_t *task_stats = stats_get_task(task_get_id());
894 if (task_stats) {
895 total_cycles = (posix_clock_t) (task_stats->kcycles + task_stats->ucycles);
896 free(task_stats);
897 task_stats = 0;
898 }
899
900 return total_cycles;
901}
902
903/** @}
904 */
Note: See TracBrowser for help on using the repository browser.