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 "scan_constant.h"
29 #include "scan_log.h"
30 #ifdef SANE_ENABLE
31 #include "sane/sane.h"
32 #include "sane/saneopts.h"
33 #endif
34
35 namespace OHOS::Scan {
36 class ScanUtil {
37 public:
38 #ifdef SANE_ENABLE
39 static ScanErrorCode ConvertErro(const SANE_Status status);
40 #endif
41 static bool ConvertToInt(const std::string& str, int32_t& value);
42 static bool ExtractIpAddresses(const std::string& str, std::string& ip);
43 static std::string ReplaceIpAddress(const std::string& deviceId, const std::string& newIp);
44 };
45 #ifdef SANE_ENABLE
ConvertErro(const SANE_Status status)46 inline ScanErrorCode ScanUtil::ConvertErro(const SANE_Status status)
47 {
48 return static_cast<ScanErrorCode> (status + E_SCAN_GOOD);
49 }
50 #endif
ConvertToInt(const std::string & str,int32_t & value)51 inline bool ScanUtil::ConvertToInt(const std::string& str, int32_t& value)
52 {
53 auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
54 return ec == std::errc{} && ptr == str.data() + str.size();
55 }
ExtractIpAddresses(const std::string & str,std::string & ip)56 inline bool ScanUtil::ExtractIpAddresses(const std::string& str, std::string& ip)
57 {
58 std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
59 std::smatch match;
60 if (std::regex_search(str, match, ipRegex)) {
61 ip = match[0];
62 return true;
63 } else {
64 return false;
65 }
66 }
ReplaceIpAddress(const std::string & deviceId,const std::string & newIp)67 inline std::string ScanUtil::ReplaceIpAddress(const std::string& deviceId, const std::string& newIp)
68 {
69 std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
70 return std::regex_replace(deviceId, ipRegex, newIp);
71 }
72 } // namespace OHOS::Scan
73
74 #endif // SCAN_UTIL_H
75