1 /*
2 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
3 * Licensed under the Apache License, Version 2.0 (the "License");
4 * you may not use this file except in compliance with the License.
5 * You may obtain a copy of the License at
6 *
7 * http://www.apache.org/licenses/LICENSE-2.0
8 *
9 * Unless required by applicable law or agreed to in writing, software
10 * distributed under the License is distributed on an "AS IS" BASIS,
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 * See the License for the specific language governing permissions and
13 * limitations under the License.
14 */
15
16 #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EVENT_HANDLER_UTILS_H
17 #define BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EVENT_HANDLER_UTILS_H
18
19 #include <cerrno>
20 #include <chrono>
21 #include <cstring>
22 #include <string>
23
24 #include "hilog/log.h"
25 #include "inner_event.h"
26
27 #ifdef _WIN32
28 #define strerror_r(err, buf, len) strerror_s((buf), (len), (err))
29 #endif
30
31 #define DEFINE_HILOG_LABEL(name) \
32 static constexpr OHOS::HiviewDFX::HiLogLabel LOG_LABEL = {LOG_CORE, LOG_DOMAIN, name}
33
34 #define HILOGE(...) OHOS::HiviewDFX::HiLog::Error(LOG_LABEL, ##__VA_ARGS__)
35 #define HILOGW(...) OHOS::HiviewDFX::HiLog::Warn(LOG_LABEL, ##__VA_ARGS__)
36 #define HILOGI(...) OHOS::HiviewDFX::HiLog::Info(LOG_LABEL, ##__VA_ARGS__)
37 #define HILOGD(...) OHOS::HiviewDFX::HiLog::Debug(LOG_LABEL, ##__VA_ARGS__)
38
39 namespace OHOS {
40 namespace AppExecFwk {
41 inline const int64_t NANOSECONDS_PER_ONE_MILLISECOND = 1000000;
42 inline const int64_t NANOSECONDS_PER_ONE_SECOND = 1000000000;
43 inline const int32_t INFINITE_TIMEOUT = -1;
44 inline const uint8_t MAX_ERRORMSG_LEN = 128;
45
46 // Help to convert time point into delay time from now.
TimePointToTimeOut(const InnerEvent::TimePoint & when)47 static inline int64_t TimePointToTimeOut(const InnerEvent::TimePoint &when)
48 {
49 InnerEvent::TimePoint now = InnerEvent::Clock::now();
50 if (when <= now) {
51 return 0;
52 }
53
54 auto duration = when - now;
55 return std::chrono::duration_cast<std::chrono::nanoseconds>(duration).count();
56 }
57
NanosecondsToTimeout(int64_t nanoseconds)58 static inline int32_t NanosecondsToTimeout(int64_t nanoseconds)
59 {
60 if (nanoseconds < 0) {
61 return INFINITE_TIMEOUT;
62 }
63
64 int64_t milliseconds = nanoseconds / NANOSECONDS_PER_ONE_MILLISECOND;
65 if ((nanoseconds % NANOSECONDS_PER_ONE_MILLISECOND) > 0) {
66 milliseconds += 1;
67 }
68
69 return (milliseconds > INT32_MAX) ? INT32_MAX : static_cast<int32_t>(milliseconds);
70 }
71
72 static inline void GetLastErr(char *errmsg, size_t size = MAX_ERRORMSG_LEN)
73 {
74 size = size > MAX_ERRORMSG_LEN ? MAX_ERRORMSG_LEN : size;
75 strerror_r(errno, errmsg, size);
76 }
77 } // namespace AppExecFwk
78 } // namespace OHOS
79
80 #endif // #ifndef BASE_EVENTHANDLER_FRAMEWORKS_EVENTHANDLER_INCLUDE_EVENT_HANDLER_UTILS_H
81