source: mainline/uspace/lib/c/generic/time.c@ d73d992

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since d73d992 was 0a0dff8, checked in by Jiří Zárevúcky <jiri.zarevucky@…>, 7 years ago

Add const to time functions.

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