2 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: GPL-2.0-only
8 #include <common/time.h>
9 #include <common/error.h>
10 #include <common/macros.h>
11 #include <common/error.h>
12 #include <common/compat/errno.h>
20 static bool utf8_output_supported
;
22 bool locale_supports_utf8(void)
24 return utf8_output_supported
;
27 int timespec_to_ms(struct timespec ts
, unsigned long *ms
)
29 unsigned long res
, remain_ms
;
31 if (ts
.tv_sec
> ULONG_MAX
/ MSEC_PER_SEC
) {
33 return -1; /* multiplication overflow */
35 res
= ts
.tv_sec
* MSEC_PER_SEC
;
36 remain_ms
= ULONG_MAX
- res
;
37 if (ts
.tv_nsec
/ NSEC_PER_MSEC
> remain_ms
) {
39 return -1; /* addition overflow */
41 res
+= ts
.tv_nsec
/ NSEC_PER_MSEC
;
46 struct timespec
timespec_abs_diff(struct timespec t1
, struct timespec t2
)
48 uint64_t ts1
= (uint64_t) t1
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
49 (uint64_t) t1
.tv_nsec
;
50 uint64_t ts2
= (uint64_t) t2
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
51 (uint64_t) t2
.tv_nsec
;
52 uint64_t diff
= max(ts1
, ts2
) - min(ts1
, ts2
);
55 res
.tv_sec
= diff
/ (uint64_t) NSEC_PER_SEC
;
56 res
.tv_nsec
= diff
% (uint64_t) NSEC_PER_SEC
;
61 void __attribute__((constructor
)) init_locale_utf8_support(void)
63 const char *program_locale
= setlocale(LC_ALL
, NULL
);
64 const char *lang
= getenv("LANG");
66 if (program_locale
&& strstr(program_locale
, "utf8")) {
67 utf8_output_supported
= true;
68 } else if (lang
&& strstr(lang
, "utf8")) {
69 utf8_output_supported
= true;
73 int time_to_iso8601_str(time_t time
, char *str
, size_t len
)
80 if (len
< ISO8601_STR_LEN
) {
81 ERR("Buffer too short to format ISO 8601 timestamp: %zu bytes provided when at least %zu are needed",
82 len
, ISO8601_STR_LEN
);
87 tm_result
= localtime_r(&time
, &tm_storage
);
90 PERROR("Failed to break down timestamp to tm structure");
94 strf_ret
= strftime(str
, len
, "%Y%m%dT%H%M%S%z", tm_result
);
97 ERR("Failed to format timestamp as local time");
104 int time_to_datetime_str(time_t time
, char *str
, size_t len
)
107 struct tm
*tm_result
;
108 struct tm tm_storage
;
111 if (len
< DATETIME_STR_LEN
) {
112 ERR("Buffer too short to format to datetime: %zu bytes provided when at least %zu are needed",
113 len
, DATETIME_STR_LEN
);
118 tm_result
= localtime_r(&time
, &tm_storage
);
121 PERROR("Failed to break down timestamp to tm structure");
125 strf_ret
= strftime(str
, len
, "%Y%m%d-%H%M%S", tm_result
);
128 ERR("Failed to format timestamp as local time");
This page took 0.034749 seconds and 5 git commands to generate.