• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 };
ConvertErro(const SaneStatus status)40 inline ScanErrorCode ScanUtil::ConvertErro(const SaneStatus status)
41 {
42     if (status < SANE_STATUS_NO_PERMISSION) {
43         return static_cast<ScanErrorCode> (status + E_SCAN_GOOD);
44     } else {
45         return static_cast<ScanErrorCode> (status);
46     }
47 }
ConvertToInt(const std::string & str,int32_t & value)48 inline bool ScanUtil::ConvertToInt(const std::string& str, int32_t& value)
49 {
50     auto [ptr, ec] = std::from_chars(str.data(), str.data() + str.size(), value);
51     return ec == std::errc{} && ptr == str.data() + str.size();
52 }
ExtractIpAddresses(const std::string & str,std::string & ip)53 inline bool ScanUtil::ExtractIpAddresses(const std::string& str, std::string& ip)
54 {
55     std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
56     std::smatch match;
57     if (std::regex_search(str, match, ipRegex)) {
58         ip = match[0];
59         return true;
60     } else {
61         return false;
62     }
63 }
ReplaceIpAddress(const std::string & deviceId,const std::string & newIp)64 inline std::string ScanUtil::ReplaceIpAddress(const std::string& deviceId, const std::string& newIp)
65 {
66     std::regex ipRegex(R"((\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b))");
67     return std::regex_replace(deviceId, ipRegex, newIp);
68 }
69 } // namespace OHOS::Scan
70 
71 #endif // SCAN_UTIL_H
72