1 /*
2  * Copyright (c) 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 #include "flashd_utils.h"
17 
18 #include <unistd.h>
19 
20 #include "securec.h"
21 
22 namespace Flashd {
GetPathRoot(const std::string & path)23 std::string GetPathRoot(const std::string &path)
24 {
25     auto pos = path.find_first_of('/', 1);
26     return path.substr(0, pos);
27 }
28 
GetFileName(const std::string & path)29 std::string GetFileName(const std::string &path)
30 {
31     auto pos = path.find_last_of('/');
32     if (pos == std::string::npos) {
33         pos = path.find_last_of('\\');
34         if (pos == std::string::npos) {
35             return "";
36         }
37     }
38     return path.substr(pos + 1);
39 }
40 
Split(const std::string & src,const std::vector<std::string> & filter)41 std::vector<std::string> Split(const std::string &src, const std::vector<std::string> &filter)
42 {
43     std::vector<std::string> result;
44     if (src.empty()) {
45         return result;
46     }
47 
48     const auto len = src.size() + 1;
49     auto buffer = std::vector<char>(len, 0);
50     buffer.assign(src.begin(), src.end());
51 
52     const char delimit[] = " ";
53     char *nextToken = nullptr;
54     auto token = strtok_s(buffer.data(), delimit, &nextToken);
55     while (token != nullptr) {
56         if (find(filter.cbegin(), filter.cend(), token) == filter.cend()) {
57             result.push_back(token);
58         }
59         token = strtok_s(nullptr, delimit, &nextToken);
60     }
61     return result;
62 }
63 
SafeCloseFile(int & fd)64 void SafeCloseFile(int &fd)
65 {
66     if (fd >= 0) {
67         close(fd);
68         fd = -1;
69     }
70 }
71 } // namespace Flashd