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>
20 static bool utf8_output_supported
;
23 bool locale_supports_utf8(void)
25 return utf8_output_supported
;
29 int timespec_to_ms(struct timespec ts
, unsigned long *ms
)
31 unsigned long res
, remain_ms
;
33 if (ts
.tv_sec
> ULONG_MAX
/ MSEC_PER_SEC
) {
35 return -1; /* multiplication overflow */
37 res
= ts
.tv_sec
* MSEC_PER_SEC
;
38 remain_ms
= ULONG_MAX
- res
;
39 if (ts
.tv_nsec
/ NSEC_PER_MSEC
> remain_ms
) {
41 return -1; /* addition overflow */
43 res
+= ts
.tv_nsec
/ NSEC_PER_MSEC
;
49 struct timespec
timespec_abs_diff(struct timespec t1
, struct timespec t2
)
51 uint64_t ts1
= (uint64_t) t1
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
52 (uint64_t) t1
.tv_nsec
;
53 uint64_t ts2
= (uint64_t) t2
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
54 (uint64_t) t2
.tv_nsec
;
55 uint64_t diff
= max(ts1
, ts2
) - min(ts1
, ts2
);
58 res
.tv_sec
= diff
/ (uint64_t) NSEC_PER_SEC
;
59 res
.tv_nsec
= diff
% (uint64_t) NSEC_PER_SEC
;
64 void __attribute__((constructor
)) init_locale_utf8_support(void)
66 const char *program_locale
= setlocale(LC_ALL
, NULL
);
67 const char *lang
= getenv("LANG");
69 if (program_locale
&& strstr(program_locale
, "utf8")) {
70 utf8_output_supported
= true;
71 } else if (lang
&& strstr(lang
, "utf8")) {
72 utf8_output_supported
= true;
77 int time_to_iso8601_str(time_t time
, char *str
, size_t len
)
84 if (len
< ISO8601_STR_LEN
) {
85 ERR("Buffer too short to format ISO 8601 timestamp: %zu bytes provided when at least %zu are needed",
86 len
, ISO8601_STR_LEN
);
91 tm_result
= localtime_r(&time
, &tm_storage
);
94 PERROR("Failed to break down timestamp to tm structure");
98 strf_ret
= strftime(str
, len
, "%Y%m%dT%H%M%S%z", tm_result
);
101 ERR("Failed to format timestamp as local time");
109 int time_to_datetime_str(time_t time
, char *str
, size_t len
)
112 struct tm
*tm_result
;
113 struct tm tm_storage
;
116 if (len
< DATETIME_STR_LEN
) {
117 ERR("Buffer too short to format to datetime: %zu bytes provided when at least %zu are needed",
118 len
, DATETIME_STR_LEN
);
123 tm_result
= localtime_r(&time
, &tm_storage
);
126 PERROR("Failed to break down timestamp to tm structure");
130 strf_ret
= strftime(str
, len
, "%Y%m%d-%H%M%S", tm_result
);
133 ERR("Failed to format timestamp as local time");
This page took 0.032106 seconds and 5 git commands to generate.