1/*
2 * SPDX-License-Identifier: Apache-2.0
3 */
4
5// Copyright (c) ONNX Project Contributors.
6// Licensed under the MIT license.
7
8#include "onnx/common/path.h"
9
10namespace ONNX_NAMESPACE {
11#ifdef _WIN32
12#else
13
14std::string path_join(const std::string& origin, const std::string& append) {
15 if (origin.find_last_of(k_preferred_path_separator) != origin.length() - 1) {
16 return origin + k_preferred_path_separator + append;
17 }
18 return origin + append;
19}
20
21std::string clean_relative_path(const std::string& path) {
22 if (path.empty()) {
23 return ".";
24 }
25
26 std::string out;
27
28 size_t n = path.size();
29
30 size_t r = 0;
31 size_t dotdot = 0;
32
33 while (r < n) {
34 if (path[r] == k_preferred_path_separator) {
35 r++;
36 continue;
37 }
38
39 if (path[r] == '.' && (r + 1 == n || path[r + 1] == k_preferred_path_separator)) {
40 r++;
41 continue;
42 }
43
44 if (path[r] == '.' && path[r + 1] == '.' && (r + 2 == n || path[r + 2] == k_preferred_path_separator)) {
45 r += 2;
46
47 if (out.size() > dotdot) {
48 while (out.size() > dotdot && out.back() != k_preferred_path_separator) {
49 out.pop_back();
50 }
51 if (!out.empty())
52 out.pop_back();
53 } else {
54 if (!out.empty()) {
55 out.push_back(k_preferred_path_separator);
56 }
57
58 out.push_back('.');
59 out.push_back('.');
60 dotdot = out.size();
61 }
62
63 continue;
64 }
65
66 if (!out.empty() && out.back() != k_preferred_path_separator) {
67 out.push_back(k_preferred_path_separator);
68 }
69
70 for (; r < n && path[r] != k_preferred_path_separator; r++) {
71 out.push_back(path[r]);
72 }
73 }
74
75 if (out.empty()) {
76 out.push_back('.');
77 }
78
79 return out;
80}
81#endif
82
83} // namespace ONNX_NAMESPACE
84