xref: /aosp_15_r20/external/private-join-and-compute/private_join_and_compute/util/file.cc (revision a6aa18fbfbf9cb5cd47356a9d1b057768998488c)
1 /*
2  * Copyright 2019 Google LLC.
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  *     https://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 // Common implementations.
17 
18 #include "private_join_and_compute/util/file.h"
19 
20 #include <sstream>
21 #include <string>
22 
23 namespace private_join_and_compute {
24 namespace internal {
25 namespace {
26 
IsAbsolutePath(absl::string_view path)27 bool IsAbsolutePath(absl::string_view path) {
28   return !path.empty() && path[0] == '/';
29 }
30 
EndsWithSlash(absl::string_view path)31 bool EndsWithSlash(absl::string_view path) {
32   return !path.empty() && path[path.size() - 1] == '/';
33 }
34 
35 }  // namespace
36 
JoinPathImpl(std::initializer_list<std::string> paths)37 std::string JoinPathImpl(std::initializer_list<std::string> paths) {
38   std::string joined_path;
39   int size = paths.size();
40 
41   int counter = 1;
42   for (auto it = paths.begin(); it != paths.end(); ++it, ++counter) {
43     std::string path = *it;
44     if (path.empty()) {
45       continue;
46     }
47 
48     if (it == paths.begin()) {
49       joined_path += path;
50       if (!EndsWithSlash(path)) {
51         joined_path += "/";
52       }
53       continue;
54     }
55 
56     if (EndsWithSlash(path)) {
57       if (IsAbsolutePath(path)) {
58         joined_path += path.substr(1, path.size() - 2);
59       } else {
60         joined_path += path.substr(0, path.size() - 1);
61       }
62     } else {
63       if (IsAbsolutePath(path)) {
64         joined_path += path.substr(1);
65       } else {
66         joined_path += path;
67       }
68     }
69     if (counter != size) {
70       joined_path += ".";
71     }
72   }
73   return joined_path;
74 }
75 
76 }  // namespace internal
77 }  // namespace private_join_and_compute
78