source: mainline/uspace/lib/c/generic/time.c@ 74017ce

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 74017ce was 582a0b8, checked in by Jakub Jermar <jakub@…>, 8 years ago

Remove unistd.h

  • Rename usleep() and sleep() to thread_usleep() and thread_sleep() and move to thread.[hc].
  • Include stddef.h in order to provide NULL.
  • Move getpagesize() to libposix.
  • Sync uspace/dist/src/c/demos with originals.
  • Property mode set to 100644
File size: 24.2 KB
Line 
1/*
2 * Copyright (c) 2006 Ondrej Palkovsky
3 * Copyright (c) 2011 Petr Koupy
4 * Copyright (c) 2011 Jiri Zarevucky
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 *
11 * - Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * - Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * - The name of the author may not be used to endorse or promote products
17 * derived from this software without specific prior written permission.
18 *
19 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
20 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
21 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
22 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
23 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
24 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
28 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29 */
30
31/** @addtogroup libc
32 * @{
33 */
34/** @file
35 */
36
37#include <sys/time.h>
38#include <time.h>
39#include <stdbool.h>
40#include <libarch/barrier.h>
41#include <macros.h>
42#include <errno.h>
43#include <sysinfo.h>
44#include <as.h>
45#include <ddi.h>
46#include <libc.h>
47#include <stdint.h>
48#include <stdio.h>
49#include <ctype.h>
50#include <assert.h>
51#include <loc.h>
52#include <device/clock_dev.h>
53#include <malloc.h>
54#include <thread.h>
55
56#define ASCTIME_BUF_LEN 26
57
58#define HOURS_PER_DAY 24
59#define MINS_PER_HOUR 60
60#define SECS_PER_MIN 60
61#define USECS_PER_SEC 1000000
62#define MINS_PER_DAY (MINS_PER_HOUR * HOURS_PER_DAY)
63#define SECS_PER_HOUR (SECS_PER_MIN * MINS_PER_HOUR)
64#define SECS_PER_DAY (SECS_PER_HOUR * HOURS_PER_DAY)
65
66/** Pointer to kernel shared variables with time */
67struct {
68 volatile sysarg_t seconds1;
69 volatile sysarg_t useconds;
70 volatile sysarg_t seconds2;
71} *ktime = NULL;
72
73static async_sess_t *clock_conn = NULL;
74
75/** Check whether the year is a leap year.
76 *
77 * @param year Year since 1900 (e.g. for 1970, the value is 70).
78 *
79 * @return true if year is a leap year, false otherwise
80 *
81 */
82static bool is_leap_year(time_t year)
83{
84 year += 1900;
85
86 if (year % 400 == 0)
87 return true;
88
89 if (year % 100 == 0)
90 return false;
91
92 if (year % 4 == 0)
93 return true;
94
95 return false;
96}
97
98/** How many days there are in the given month
99 *
100 * Return how many days there are in the given month of the given year.
101 * Note that year is only taken into account if month is February.
102 *
103 * @param year Year since 1900 (can be negative).
104 * @param mon Month of the year. 0 for January, 11 for December.
105 *
106 * @return Number of days in the specified month.
107 *
108 */
109static int days_in_month(time_t year, time_t mon)
110{
111 assert(mon >= 0);
112 assert(mon <= 11);
113
114 static int month_days[] = {
115 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
116 };
117
118 if (mon == 1) {
119 /* February */
120 year += 1900;
121 return is_leap_year(year) ? 29 : 28;
122 }
123
124 return month_days[mon];
125}
126
127/** Which day of that year it is.
128 *
129 * For specified year, month and day of month, return which day of that year
130 * it is.
131 *
132 * For example, given date 2011-01-03, the corresponding expression is:
133 * day_of_year(111, 0, 3) == 2
134 *
135 * @param year Year (year 1900 = 0, can be negative).
136 * @param mon Month (January = 0).
137 * @param mday Day of month (First day is 1).
138 *
139 * @return Day of year (First day is 0).
140 *
141 */
142static int day_of_year(time_t year, time_t mon, time_t mday)
143{
144 static int mdays[] = {
145 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
146 };
147
148 static int leap_mdays[] = {
149 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335
150 };
151
152 return (is_leap_year(year) ? leap_mdays[mon] : mdays[mon]) + mday - 1;
153}
154
155/** Integer division that rounds to negative infinity.
156 *
157 * Used by some functions in this module.
158 *
159 * @param op1 Dividend.
160 * @param op2 Divisor.
161 *
162 * @return Rounded quotient.
163 *
164 */
165static time_t floor_div(time_t op1, time_t op2)
166{
167 if ((op1 >= 0) || (op1 % op2 == 0))
168 return op1 / op2;
169
170 return op1 / op2 - 1;
171}
172
173/** Modulo that rounds to negative infinity.
174 *
175 * Used by some functions in this module.
176 *
177 * @param op1 Dividend.
178 * @param op2 Divisor.
179 *
180 * @return Remainder.
181 *
182 */
183static time_t floor_mod(time_t op1, time_t op2)
184{
185 time_t div = floor_div(op1, op2);
186
187 /*
188 * (a / b) * b + a % b == a
189 * Thus: a % b == a - (a / b) * b
190 */
191
192 time_t result = op1 - div * op2;
193
194 /* Some paranoid checking to ensure there is mistake here. */
195 assert(result >= 0);
196 assert(result < op2);
197 assert(div * op2 + result == op1);
198
199 return result;
200}
201
202/** Number of days since the Epoch.
203 *
204 * Epoch is 1970-01-01, which is also equal to day 0.
205 *
206 * @param year Year (year 1900 = 0, may be negative).
207 * @param mon Month (January = 0).
208 * @param mday Day of month (first day = 1).
209 *
210 * @return Number of days since the Epoch.
211 *
212 */
213static time_t days_since_epoch(time_t year, time_t mon, time_t mday)
214{
215 return (year - 70) * 365 + floor_div(year - 69, 4) -
216 floor_div(year - 1, 100) + floor_div(year + 299, 400) +
217 day_of_year(year, mon, mday);
218}
219
220/** Seconds since the Epoch.
221 *
222 * See also days_since_epoch().
223 *
224 * @param tm Normalized broken-down time.
225 *
226 * @return Number of seconds since the epoch, not counting leap seconds.
227 *
228 */
229static time_t secs_since_epoch(const struct tm *tm)
230{
231 return days_since_epoch(tm->tm_year, tm->tm_mon, tm->tm_mday) *
232 SECS_PER_DAY + tm->tm_hour * SECS_PER_HOUR +
233 tm->tm_min * SECS_PER_MIN + tm->tm_sec;
234}
235
236/** Which day of week the specified date is.
237 *
238 * @param year Year (year 1900 = 0).
239 * @param mon Month (January = 0).
240 * @param mday Day of month (first = 1).
241 *
242 * @return Day of week (Sunday = 0).
243 *
244 */
245static time_t day_of_week(time_t year, time_t mon, time_t mday)
246{
247 /* 1970-01-01 is Thursday */
248 return floor_mod(days_since_epoch(year, mon, mday) + 4, 7);
249}
250
251/** Normalize the broken-down time.
252 *
253 * Optionally add specified amount of seconds.
254 *
255 * @param tm Broken-down time to normalize.
256 * @param tv Timeval to add.
257 *
258 * @return 0 on success, -1 on overflow
259 *
260 */
261static int normalize_tm_tv(struct tm *tm, const struct timeval *tv)
262{
263 // TODO: DST correction
264
265 /* Set initial values. */
266 time_t usec = tm->tm_usec + tv->tv_usec;
267 time_t sec = tm->tm_sec + tv->tv_sec;
268 time_t min = tm->tm_min;
269 time_t hour = tm->tm_hour;
270 time_t day = tm->tm_mday - 1;
271 time_t mon = tm->tm_mon;
272 time_t year = tm->tm_year;
273
274 /* Adjust time. */
275 sec += floor_div(usec, USECS_PER_SEC);
276 usec = floor_mod(usec, USECS_PER_SEC);
277 min += floor_div(sec, SECS_PER_MIN);
278 sec = floor_mod(sec, SECS_PER_MIN);
279 hour += floor_div(min, MINS_PER_HOUR);
280 min = floor_mod(min, MINS_PER_HOUR);
281 day += floor_div(hour, HOURS_PER_DAY);
282 hour = floor_mod(hour, HOURS_PER_DAY);
283
284 /* Adjust month. */
285 year += floor_div(mon, 12);
286 mon = floor_mod(mon, 12);
287
288 /* Now the difficult part - days of month. */
289
290 /* First, deal with whole cycles of 400 years = 146097 days. */
291 year += floor_div(day, 146097) * 400;
292 day = floor_mod(day, 146097);
293
294 /* Then, go in one year steps. */
295 if (mon <= 1) {
296 /* January and February. */
297 while (day > 365) {
298 day -= is_leap_year(year) ? 366 : 365;
299 year++;
300 }
301 } else {
302 /* Rest of the year. */
303 while (day > 365) {
304 day -= is_leap_year(year + 1) ? 366 : 365;
305 year++;
306 }
307 }
308
309 /* Finally, finish it off month per month. */
310 while (day >= days_in_month(year, mon)) {
311 day -= days_in_month(year, mon);
312 mon++;
313
314 if (mon >= 12) {
315 mon -= 12;
316 year++;
317 }
318 }
319
320 /* Calculate the remaining two fields. */
321 tm->tm_yday = day_of_year(year, mon, day + 1);
322 tm->tm_wday = day_of_week(year, mon, day + 1);
323
324 /* And put the values back to the struct. */
325 tm->tm_usec = (int) usec;
326 tm->tm_sec = (int) sec;
327 tm->tm_min = (int) min;
328 tm->tm_hour = (int) hour;
329 tm->tm_mday = (int) day + 1;
330 tm->tm_mon = (int) mon;
331
332 /* Casts to work around POSIX brain-damage. */
333 if (year > ((int) INT_MAX) || year < ((int) INT_MIN)) {
334 tm->tm_year = (year < 0) ? ((int) INT_MIN) : ((int) INT_MAX);
335 return -1;
336 }
337
338 tm->tm_year = (int) year;
339 return 0;
340}
341
342static int normalize_tm_time(struct tm *tm, time_t time)
343{
344 struct timeval tv = {
345 .tv_sec = time,
346 .tv_usec = 0
347 };
348
349 return normalize_tm_tv(tm, &tv);
350}
351
352
353/** Which day the week-based year starts on.
354 *
355 * Relative to the first calendar day. E.g. if the year starts
356 * on December 31st, the return value is -1.
357 *
358 * @param Year since 1900.
359 *
360 * @return Offset of week-based year relative to calendar year.
361 *
362 */
363static int wbyear_offset(int year)
364{
365 int start_wday = day_of_week(year, 0, 1);
366
367 return floor_mod(4 - start_wday, 7) - 3;
368}
369
370/** Week-based year of the specified time.
371 *
372 * @param tm Normalized broken-down time.
373 *
374 * @return Week-based year.
375 *
376 */
377static int wbyear(const struct tm *tm)
378{
379 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
380
381 if (day < 0) {
382 /* Last week of previous year. */
383 return tm->tm_year - 1;
384 }
385
386 if (day > 364 + is_leap_year(tm->tm_year)) {
387 /* First week of next year. */
388 return tm->tm_year + 1;
389 }
390
391 /* All the other days are in the calendar year. */
392 return tm->tm_year;
393}
394
395/** Week number of the year (assuming weeks start on Sunday).
396 *
397 * The first Sunday of January is the first day of week 1;
398 * days in the new year before this are in week 0.
399 *
400 * @param tm Normalized broken-down time.
401 *
402 * @return The week number (0 - 53).
403 *
404 */
405static int sun_week_number(const struct tm *tm)
406{
407 int first_day = (7 - day_of_week(tm->tm_year, 0, 1)) % 7;
408
409 return (tm->tm_yday - first_day + 7) / 7;
410}
411
412/** Week number of the year (assuming weeks start on Monday).
413 *
414 * If the week containing January 1st has four or more days
415 * in the new year, then it is considered week 1. Otherwise,
416 * it is the last week of the previous year, and the next week
417 * is week 1. Both January 4th and the first Thursday
418 * of January are always in week 1.
419 *
420 * @param tm Normalized broken-down time.
421 *
422 * @return The week number (1 - 53).
423 *
424 */
425static int iso_week_number(const struct tm *tm)
426{
427 int day = tm->tm_yday - wbyear_offset(tm->tm_year);
428
429 if (day < 0) {
430 /* Last week of previous year. */
431 return 53;
432 }
433
434 if (day > 364 + is_leap_year(tm->tm_year)) {
435 /* First week of next year. */
436 return 1;
437 }
438
439 /* All the other days give correct answer. */
440 return (day / 7 + 1);
441}
442
443/** Week number of the year (assuming weeks start on Monday).
444 *
445 * The first Monday of January is the first day of week 1;
446 * days in the new year before this are in week 0.
447 *
448 * @param tm Normalized broken-down time.
449 *
450 * @return The week number (0 - 53).
451 *
452 */
453static int mon_week_number(const struct tm *tm)
454{
455 int first_day = (1 - day_of_week(tm->tm_year, 0, 1)) % 7;
456
457 return (tm->tm_yday - first_day + 7) / 7;
458}
459
460static void tv_normalize(struct timeval *tv)
461{
462 while (tv->tv_usec > USECS_PER_SEC) {
463 tv->tv_sec++;
464 tv->tv_usec -= USECS_PER_SEC;
465 }
466 while (tv->tv_usec < 0) {
467 tv->tv_sec--;
468 tv->tv_usec += USECS_PER_SEC;
469 }
470}
471
472/** Add microseconds to given timeval.
473 *
474 * @param tv Destination timeval.
475 * @param usecs Number of microseconds to add.
476 *
477 */
478void tv_add_diff(struct timeval *tv, suseconds_t usecs)
479{
480 tv->tv_sec += usecs / USECS_PER_SEC;
481 tv->tv_usec += usecs % USECS_PER_SEC;
482 tv_normalize(tv);
483}
484
485/** Add two timevals.
486 *
487 * @param tv1 First timeval.
488 * @param tv2 Second timeval.
489 */
490void tv_add(struct timeval *tv1, struct timeval *tv2)
491{
492 tv1->tv_sec += tv2->tv_sec;
493 tv1->tv_usec += tv2->tv_usec;
494 tv_normalize(tv1);
495}
496
497/** Subtract two timevals.
498 *
499 * @param tv1 First timeval.
500 * @param tv2 Second timeval.
501 *
502 * @return Difference between tv1 and tv2 (tv1 - tv2) in
503 * microseconds.
504 *
505 */
506suseconds_t tv_sub_diff(struct timeval *tv1, struct timeval *tv2)
507{
508 return (tv1->tv_usec - tv2->tv_usec) +
509 ((tv1->tv_sec - tv2->tv_sec) * USECS_PER_SEC);
510}
511
512/** Subtract two timevals.
513 *
514 * @param tv1 First timeval.
515 * @param tv2 Second timeval.
516 *
517 */
518void tv_sub(struct timeval *tv1, struct timeval *tv2)
519{
520 tv1->tv_sec -= tv2->tv_sec;
521 tv1->tv_usec -= tv2->tv_usec;
522 tv_normalize(tv1);
523}
524
525/** Decide if one timeval is greater than the other.
526 *
527 * @param t1 First timeval.
528 * @param t2 Second timeval.
529 *
530 * @return True if tv1 is greater than tv2.
531 * @return False otherwise.
532 *
533 */
534int tv_gt(struct timeval *tv1, struct timeval *tv2)
535{
536 if (tv1->tv_sec > tv2->tv_sec)
537 return true;
538
539 if ((tv1->tv_sec == tv2->tv_sec) && (tv1->tv_usec > tv2->tv_usec))
540 return true;
541
542 return false;
543}
544
545/** Decide if one timeval is greater than or equal to the other.
546 *
547 * @param tv1 First timeval.
548 * @param tv2 Second timeval.
549 *
550 * @return True if tv1 is greater than or equal to tv2.
551 * @return False otherwise.
552 *
553 */
554int tv_gteq(struct timeval *tv1, struct timeval *tv2)
555{
556 if (tv1->tv_sec > tv2->tv_sec)
557 return true;
558
559 if ((tv1->tv_sec == tv2->tv_sec) && (tv1->tv_usec >= tv2->tv_usec))
560 return true;
561
562 return false;
563}
564
565/** Get time of day.
566 *
567 * The time variables are memory mapped (read-only) from kernel which
568 * updates them periodically.
569 *
570 * As it is impossible to read 2 values atomically, we use a trick:
571 * First we read the seconds, then we read the microseconds, then we
572 * read the seconds again. If a second elapsed in the meantime, set
573 * the microseconds to zero.
574 *
575 * This assures that the values returned by two subsequent calls
576 * to gettimeofday() are monotonous.
577 *
578 */
579void gettimeofday(struct timeval *tv, struct timezone *tz)
580{
581 if (tz) {
582 tz->tz_minuteswest = 0;
583 tz->tz_dsttime = DST_NONE;
584 }
585
586 if (clock_conn == NULL) {
587 category_id_t cat_id;
588 int rc = loc_category_get_id("clock", &cat_id, IPC_FLAG_BLOCKING);
589 if (rc != EOK)
590 goto fallback;
591
592 service_id_t *svc_ids;
593 size_t svc_cnt;
594 rc = loc_category_get_svcs(cat_id, &svc_ids, &svc_cnt);
595 if (rc != EOK)
596 goto fallback;
597
598 if (svc_cnt == 0)
599 goto fallback;
600
601 char *svc_name;
602 rc = loc_service_get_name(svc_ids[0], &svc_name);
603 free(svc_ids);
604 if (rc != EOK)
605 goto fallback;
606
607 service_id_t svc_id;
608 rc = loc_service_get_id(svc_name, &svc_id, 0);
609 free(svc_name);
610 if (rc != EOK)
611 goto fallback;
612
613 clock_conn = loc_service_connect(svc_id, INTERFACE_DDF,
614 IPC_FLAG_BLOCKING);
615 if (!clock_conn)
616 goto fallback;
617 }
618
619 struct tm time;
620 int rc = clock_dev_time_get(clock_conn, &time);
621 if (rc != EOK)
622 goto fallback;
623
624 tv->tv_usec = time.tm_usec;
625 tv->tv_sec = mktime(&time);
626
627 return;
628
629fallback:
630 getuptime(tv);
631}
632
633void getuptime(struct timeval *tv)
634{
635 if (ktime == NULL) {
636 uintptr_t faddr;
637 int rc = sysinfo_get_value("clock.faddr", &faddr);
638 if (rc != EOK) {
639 errno = rc;
640 goto fallback;
641 }
642
643 void *addr = AS_AREA_ANY;
644 rc = physmem_map(faddr, 1, AS_AREA_READ | AS_AREA_CACHEABLE,
645 &addr);
646 if (rc != EOK) {
647 as_area_destroy(addr);
648 errno = rc;
649 goto fallback;
650 }
651
652 ktime = addr;
653 }
654
655 sysarg_t s2 = ktime->seconds2;
656
657 read_barrier();
658 tv->tv_usec = ktime->useconds;
659
660 read_barrier();
661 sysarg_t s1 = ktime->seconds1;
662
663 if (s1 != s2) {
664 tv->tv_sec = max(s1, s2);
665 tv->tv_usec = 0;
666 } else
667 tv->tv_sec = s1;
668
669 return;
670
671fallback:
672 tv->tv_sec = 0;
673 tv->tv_usec = 0;
674}
675
676time_t time(time_t *tloc)
677{
678 struct timeval tv;
679 gettimeofday(&tv, NULL);
680
681 if (tloc)
682 *tloc = tv.tv_sec;
683
684 return tv.tv_sec;
685}
686
687void udelay(useconds_t time)
688{
689 (void) __SYSCALL1(SYS_THREAD_UDELAY, (sysarg_t) time);
690}
691
692/** Get time from broken-down time.
693 *
694 * First normalize the provided broken-down time
695 * (moves all values to their proper bounds) and
696 * then try to calculate the appropriate time_t
697 * representation.
698 *
699 * @param tm Broken-down time.
700 *
701 * @return time_t representation of the time.
702 * @return Undefined value on overflow.
703 *
704 */
705time_t mktime(struct tm *tm)
706{
707 // TODO: take DST flag into account
708 // TODO: detect overflow
709
710 normalize_tm_time(tm, 0);
711 return secs_since_epoch(tm);
712}
713
714/*
715 * FIXME: This requires POSIX-correct snprintf.
716 * Otherwise it won't work with non-ASCII chars.
717 */
718#define APPEND(...) \
719 { \
720 consumed = snprintf(ptr, remaining, __VA_ARGS__); \
721 if (consumed >= remaining) \
722 return 0; \
723 \
724 ptr += consumed; \
725 remaining -= consumed; \
726 }
727
728#define RECURSE(fmt) \
729 { \
730 consumed = strftime(ptr, remaining, fmt, tm); \
731 if (consumed == 0) \
732 return 0; \
733 \
734 ptr += consumed; \
735 remaining -= consumed; \
736 }
737
738#define TO_12H(hour) \
739 (((hour) > 12) ? ((hour) - 12) : \
740 (((hour) == 0) ? 12 : (hour)))
741
742/** Convert time and date to a string.
743 *
744 * @param s Buffer to write string to.
745 * @param maxsize Size of the buffer.
746 * @param format Format of the output.
747 * @param tm Broken-down time to format.
748 *
749 * @return Number of bytes written.
750 *
751 */
752size_t strftime(char *restrict s, size_t maxsize,
753 const char *restrict format, const struct tm *restrict tm)
754{
755 assert(s != NULL);
756 assert(format != NULL);
757 assert(tm != NULL);
758
759 // TODO: use locale
760
761 static const char *wday_abbr[] = {
762 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
763 };
764
765 static const char *wday[] = {
766 "Sunday", "Monday", "Tuesday", "Wednesday",
767 "Thursday", "Friday", "Saturday"
768 };
769
770 static const char *mon_abbr[] = {
771 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
772 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
773 };
774
775 static const char *mon[] = {
776 "January", "February", "March", "April", "May", "June", "July",
777 "August", "September", "October", "November", "December"
778 };
779
780 if (maxsize < 1)
781 return 0;
782
783 char *ptr = s;
784 size_t consumed;
785 size_t remaining = maxsize;
786
787 while (*format != '\0') {
788 if (*format != '%') {
789 APPEND("%c", *format);
790 format++;
791 continue;
792 }
793
794 format++;
795 if ((*format == '0') || (*format == '+')) {
796 // TODO: padding
797 format++;
798 }
799
800 while (isdigit(*format)) {
801 // TODO: padding
802 format++;
803 }
804
805 if ((*format == 'O') || (*format == 'E')) {
806 // TODO: locale's alternative format
807 format++;
808 }
809
810 switch (*format) {
811 case 'a':
812 APPEND("%s", wday_abbr[tm->tm_wday]);
813 break;
814 case 'A':
815 APPEND("%s", wday[tm->tm_wday]);
816 break;
817 case 'b':
818 APPEND("%s", mon_abbr[tm->tm_mon]);
819 break;
820 case 'B':
821 APPEND("%s", mon[tm->tm_mon]);
822 break;
823 case 'c':
824 // TODO: locale-specific datetime format
825 RECURSE("%Y-%m-%d %H:%M:%S");
826 break;
827 case 'C':
828 APPEND("%02d", (1900 + tm->tm_year) / 100);
829 break;
830 case 'd':
831 APPEND("%02d", tm->tm_mday);
832 break;
833 case 'D':
834 RECURSE("%m/%d/%y");
835 break;
836 case 'e':
837 APPEND("%2d", tm->tm_mday);
838 break;
839 case 'F':
840 RECURSE("%+4Y-%m-%d");
841 break;
842 case 'g':
843 APPEND("%02d", wbyear(tm) % 100);
844 break;
845 case 'G':
846 APPEND("%d", wbyear(tm));
847 break;
848 case 'h':
849 RECURSE("%b");
850 break;
851 case 'H':
852 APPEND("%02d", tm->tm_hour);
853 break;
854 case 'I':
855 APPEND("%02d", TO_12H(tm->tm_hour));
856 break;
857 case 'j':
858 APPEND("%03d", tm->tm_yday);
859 break;
860 case 'k':
861 APPEND("%2d", tm->tm_hour);
862 break;
863 case 'l':
864 APPEND("%2d", TO_12H(tm->tm_hour));
865 break;
866 case 'm':
867 APPEND("%02d", tm->tm_mon);
868 break;
869 case 'M':
870 APPEND("%02d", tm->tm_min);
871 break;
872 case 'n':
873 APPEND("\n");
874 break;
875 case 'p':
876 APPEND("%s", tm->tm_hour < 12 ? "AM" : "PM");
877 break;
878 case 'P':
879 APPEND("%s", tm->tm_hour < 12 ? "am" : "PM");
880 break;
881 case 'r':
882 RECURSE("%I:%M:%S %p");
883 break;
884 case 'R':
885 RECURSE("%H:%M");
886 break;
887 case 's':
888 APPEND("%ld", secs_since_epoch(tm));
889 break;
890 case 'S':
891 APPEND("%02d", tm->tm_sec);
892 break;
893 case 't':
894 APPEND("\t");
895 break;
896 case 'T':
897 RECURSE("%H:%M:%S");
898 break;
899 case 'u':
900 APPEND("%d", (tm->tm_wday == 0) ? 7 : tm->tm_wday);
901 break;
902 case 'U':
903 APPEND("%02d", sun_week_number(tm));
904 break;
905 case 'V':
906 APPEND("%02d", iso_week_number(tm));
907 break;
908 case 'w':
909 APPEND("%d", tm->tm_wday);
910 break;
911 case 'W':
912 APPEND("%02d", mon_week_number(tm));
913 break;
914 case 'x':
915 // TODO: locale-specific date format
916 RECURSE("%Y-%m-%d");
917 break;
918 case 'X':
919 // TODO: locale-specific time format
920 RECURSE("%H:%M:%S");
921 break;
922 case 'y':
923 APPEND("%02d", tm->tm_year % 100);
924 break;
925 case 'Y':
926 APPEND("%d", 1900 + tm->tm_year);
927 break;
928 case 'z':
929 // TODO: timezone
930 break;
931 case 'Z':
932 // TODO: timezone
933 break;
934 case '%':
935 APPEND("%%");
936 break;
937 default:
938 /* Invalid specifier, print verbatim. */
939 while (*format != '%')
940 format--;
941
942 APPEND("%%");
943 break;
944 }
945
946 format++;
947 }
948
949 return maxsize - remaining;
950}
951
952/** Convert a time value to a broken-down UTC time/
953 *
954 * @param time Time to convert
955 * @param result Structure to store the result to
956 *
957 * @return EOK or a negative error code
958 *
959 */
960int time_utc2tm(const time_t time, struct tm *restrict result)
961{
962 assert(result != NULL);
963
964 /* Set result to epoch. */
965 result->tm_usec = 0;
966 result->tm_sec = 0;
967 result->tm_min = 0;
968 result->tm_hour = 0;
969 result->tm_mday = 1;
970 result->tm_mon = 0;
971 result->tm_year = 70; /* 1970 */
972
973 if (normalize_tm_time(result, time) == -1)
974 return EOVERFLOW;
975
976 return EOK;
977}
978
979/** Convert a time value to a NULL-terminated string.
980 *
981 * The format is "Wed Jun 30 21:49:08 1993\n" expressed in UTC.
982 *
983 * @param time Time to convert.
984 * @param buf Buffer to store the string to, must be at least
985 * ASCTIME_BUF_LEN bytes long.
986 *
987 * @return EOK or a negative error code.
988 *
989 */
990int time_utc2str(const time_t time, char *restrict buf)
991{
992 struct tm tm;
993 int ret = time_utc2tm(time, &tm);
994 if (ret != EOK)
995 return ret;
996
997 time_tm2str(&tm, buf);
998 return EOK;
999}
1000
1001/** Convert broken-down time to a NULL-terminated string.
1002 *
1003 * The format is "Sun Jan 1 00:00:00 1970\n". (Obsolete)
1004 *
1005 * @param timeptr Broken-down time structure.
1006 * @param buf Buffer to store string to, must be at least
1007 * ASCTIME_BUF_LEN bytes long.
1008 *
1009 */
1010void time_tm2str(const struct tm *restrict timeptr, char *restrict buf)
1011{
1012 assert(timeptr != NULL);
1013 assert(buf != NULL);
1014
1015 static const char *wday[] = {
1016 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"
1017 };
1018
1019 static const char *mon[] = {
1020 "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1021 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1022 };
1023
1024 snprintf(buf, ASCTIME_BUF_LEN, "%s %s %2d %02d:%02d:%02d %d\n",
1025 wday[timeptr->tm_wday],
1026 mon[timeptr->tm_mon],
1027 timeptr->tm_mday, timeptr->tm_hour,
1028 timeptr->tm_min, timeptr->tm_sec,
1029 1900 + timeptr->tm_year);
1030}
1031
1032/** Converts a time value to a broken-down local time.
1033 *
1034 * Time is expressed relative to the user's specified timezone.
1035 *
1036 * @param tv Timeval to convert.
1037 * @param result Structure to store the result to.
1038 *
1039 * @return EOK on success or a negative error code.
1040 *
1041 */
1042int time_tv2tm(const struct timeval *tv, struct tm *restrict result)
1043{
1044 // TODO: Deal with timezones.
1045 // Currently assumes system and all times are in UTC
1046
1047 /* Set result to epoch. */
1048 result->tm_usec = 0;
1049 result->tm_sec = 0;
1050 result->tm_min = 0;
1051 result->tm_hour = 0;
1052 result->tm_mday = 1;
1053 result->tm_mon = 0;
1054 result->tm_year = 70; /* 1970 */
1055
1056 if (normalize_tm_tv(result, tv) == -1)
1057 return EOVERFLOW;
1058
1059 return EOK;
1060}
1061
1062/** Converts a time value to a broken-down local time.
1063 *
1064 * Time is expressed relative to the user's specified timezone.
1065 *
1066 * @param timer Time to convert.
1067 * @param result Structure to store the result to.
1068 *
1069 * @return EOK on success or a negative error code.
1070 *
1071 */
1072int time_local2tm(const time_t time, struct tm *restrict result)
1073{
1074 struct timeval tv = {
1075 .tv_sec = time,
1076 .tv_usec = 0
1077 };
1078
1079 return time_tv2tm(&tv, result);
1080}
1081
1082/** Convert the calendar time to a NULL-terminated string.
1083 *
1084 * The format is "Wed Jun 30 21:49:08 1993\n" expressed relative to the
1085 * user's specified timezone.
1086 *
1087 * @param timer Time to convert.
1088 * @param buf Buffer to store the string to. Must be at least
1089 * ASCTIME_BUF_LEN bytes long.
1090 *
1091 * @return EOK on success or a negative error code.
1092 *
1093 */
1094int time_local2str(const time_t time, char *buf)
1095{
1096 struct tm loctime;
1097 int ret = time_local2tm(time, &loctime);
1098 if (ret != EOK)
1099 return ret;
1100
1101 time_tm2str(&loctime, buf);
1102 return EOK;
1103}
1104
1105/** Calculate the difference between two times, in seconds.
1106 *
1107 * @param time1 First time.
1108 * @param time0 Second time.
1109 *
1110 * @return Time difference in seconds.
1111 *
1112 */
1113double difftime(time_t time1, time_t time0)
1114{
1115 return (double) (time1 - time0);
1116}
1117
1118/** @}
1119 */
Note: See TracBrowser for help on using the repository browser.