2 * Copyright (C) 2013 Jérémie Galarneau <jeremie.galarneau@efficios.com>
4 * SPDX-License-Identifier: LGPL-2.1-only
8 #include <common/time.hpp>
9 #include <common/error.hpp>
10 #include <common/macros.hpp>
11 #include <common/error.hpp>
12 #include <common/compat/errno.hpp>
21 static bool utf8_output_supported
;
23 bool locale_supports_utf8(void)
25 return utf8_output_supported
;
28 int timespec_to_ms(struct timespec ts
, unsigned long *ms
)
30 unsigned long res
, remain_ms
;
32 if (ts
.tv_sec
> ULONG_MAX
/ MSEC_PER_SEC
) {
34 return -1; /* multiplication overflow */
36 res
= ts
.tv_sec
* MSEC_PER_SEC
;
37 remain_ms
= ULONG_MAX
- res
;
38 if (ts
.tv_nsec
/ NSEC_PER_MSEC
> remain_ms
) {
40 return -1; /* addition overflow */
42 res
+= ts
.tv_nsec
/ NSEC_PER_MSEC
;
47 struct timespec
timespec_abs_diff(struct timespec t1
, struct timespec t2
)
49 uint64_t ts1
= (uint64_t) t1
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
50 (uint64_t) t1
.tv_nsec
;
51 uint64_t ts2
= (uint64_t) t2
.tv_sec
* (uint64_t) NSEC_PER_SEC
+
52 (uint64_t) t2
.tv_nsec
;
53 uint64_t diff
= std::max(ts1
, ts2
) - std::min(ts1
, ts2
);
56 res
.tv_sec
= diff
/ (uint64_t) NSEC_PER_SEC
;
57 res
.tv_nsec
= diff
% (uint64_t) NSEC_PER_SEC
;
62 void __attribute__((constructor
)) init_locale_utf8_support(void)
64 const char *program_locale
= setlocale(LC_ALL
, NULL
);
65 const char *lang
= getenv("LANG");
67 if (program_locale
&& strstr(program_locale
, "utf8")) {
68 utf8_output_supported
= true;
69 } else if (lang
&& strstr(lang
, "utf8")) {
70 utf8_output_supported
= true;
74 int time_to_iso8601_str(time_t time
, char *str
, size_t len
)
81 if (len
< ISO8601_STR_LEN
) {
82 ERR("Buffer too short to format ISO 8601 timestamp: %zu bytes provided when at least %zu are needed",
83 len
, ISO8601_STR_LEN
);
88 tm_result
= localtime_r(&time
, &tm_storage
);
91 PERROR("Failed to break down timestamp to tm structure");
95 strf_ret
= strftime(str
, len
, "%Y%m%dT%H%M%S%z", tm_result
);
98 ERR("Failed to format timestamp as local time");
105 int time_to_datetime_str(time_t time
, char *str
, size_t len
)
108 struct tm
*tm_result
;
109 struct tm tm_storage
;
112 if (len
< DATETIME_STR_LEN
) {
113 ERR("Buffer too short to format to datetime: %zu bytes provided when at least %zu are needed",
114 len
, DATETIME_STR_LEN
);
119 tm_result
= localtime_r(&time
, &tm_storage
);
122 PERROR("Failed to break down timestamp to tm structure");
126 strf_ret
= strftime(str
, len
, "%Y%m%d-%H%M%S", tm_result
);
129 ERR("Failed to format timestamp as local time");
This page took 0.032067 seconds and 4 git commands to generate.