1 /*
2  * Copyright (c) 2024 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 #include "res_sched_exe_common_utils.h"
17 
18 #include <chrono>
19 
20 #include "res_sched_exe_log.h"
21 
22 namespace OHOS {
23 namespace ResourceSchedule {
GetCurrentTimestampMs()24 uint64_t ResSchedExeCommonUtils::GetCurrentTimestampMs()
25 {
26     std::chrono::milliseconds ms = std::chrono::duration_cast<std::chrono::milliseconds>(
27         std::chrono::system_clock::now().time_since_epoch()
28     );
29     return static_cast<uint64_t>(ms.count());
30 }
31 
GetCurrentTimestampUs()32 uint64_t ResSchedExeCommonUtils::GetCurrentTimestampUs()
33 {
34     std::chrono::microseconds ms = std::chrono::duration_cast<std::chrono::microseconds>(
35         std::chrono::system_clock::now().time_since_epoch()
36     );
37     return static_cast<uint64_t>(ms.count());
38 }
39 
StringToJson(const std::string & str,nlohmann::json & payload)40 void ResSchedExeCommonUtils::StringToJson(const std::string& str, nlohmann::json& payload)
41 {
42     if (str.empty()) {
43         return;
44     }
45 
46     auto jsonObj = nlohmann::json::parse(str, nullptr, false);
47     if (jsonObj.is_discarded()) {
48         RSSEXE_LOGE("parse string to json failed.");
49         RSSEXE_LOGD("string: %{private}s.", str.c_str());
50         return;
51     }
52     if (!jsonObj.is_object()) {
53         RSSEXE_LOGE("convert string result is not a jsonobj.");
54         RSSEXE_LOGD("string: %{private}s.", str.c_str());
55         return;
56     }
57 
58     for (auto& [key, value] : jsonObj.items()) {
59         payload[key] = value;
60     }
61 }
62 } // namespace ResourceSchedule
63 } // namespace OHOS
64