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

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

Get rid of sys/time.h

This commit moves the POSIX-like time functionality from libc's
sys/time.h to libposix and introduces C11-like or HelenOS-specific
interfaces to libc.

Specifically, use of sys/time.h, struct timeval, suseconds_t and
gettimeofday is replaced by time.h (C11), struct timespec (C11), usec_t
(HelenOS) and getuptime / getrealtime (HelenOS).

Also attempt to fix the implementation of clock() to return microseconds
(clocks) rather than processor cycles and move it to libc.

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