1 /*
2 * Copyright (c) 2023 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 SCAN_UTIL_H
17 #define SCAN_UTIL_H
18
19 #include <algorithm>
20 #include <charconv>
21 #include <iostream>
22 #include <sstream>
23 #include <list>
24 #include <vector>
25 #include <iomanip>
26 #include <regex>
27 #include <string>
28 #include "sane_info.h"
29 #include "scan_constant.h"
30 #include "scan_log.h"
31
32 namespace OHOS::Scan {
33 class ScanUtil {
34 public:
35 static ScanErrorCode ConvertErro(const SaneStatus status);
36 static bool ConvertToInt(const std::string& str, int32_t& value);
37 static bool ExtractIpAddresses(const std::string& str, std::string& ip);
38 static std::string ReplaceIpAddress(const std::string& deviceId, const std::string& newIp);
39 };
ConvertToInt(const std::string & str,int32_t & value)40 inline bool ScanUtil::ConvertToInt(const std::string& str, int32_t& value)
41 {
42 auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
43 return ec == std::errc{} && ptr == str.data() + str.size();
44 }
ExtractIpAddresses(const std::string & str,std::string & ip)45 inline bool ScanUtil::ExtractIpAddresses(const std::string& str, std::string& ip)
46 {
47 std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
48 std::smatch match;
49 if (std::regex_search(str, match, ipRegex)) {
50 ip = match[0];
51 return true;
52 } else {
53 return false;
54 }
55 }
ReplaceIpAddress(const std::string & deviceId,const std::string & newIp)56 inline std::string ScanUtil::ReplaceIpAddress(const std::string& deviceId, const std::string& newIp)
57 {
58 std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
59 return std::regex_replace(deviceId, ipRegex, newIp);
60 }
61 } // namespace OHOS::Scan
62
63 #endif // SCAN_UTIL_H
64