Line data Source code
1 : /* Copyright (C) 2025 Wildfire Games.
2 : *
3 : * Permission is hereby granted, free of charge, to any person obtaining
4 : * a copy of this software and associated documentation files (the
5 : * "Software"), to deal in the Software without restriction, including
6 : * without limitation the rights to use, copy, modify, merge, publish,
7 : * distribute, sublicense, and/or sell copies of the Software, and to
8 : * permit persons to whom the Software is furnished to do so, subject to
9 : * the following conditions:
10 : *
11 : * The above copyright notice and this permission notice shall be included
12 : * in all copies or substantial portions of the Software.
13 : *
14 : * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15 : * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 : * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17 : * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18 : * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19 : * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20 : * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 : */
22 :
23 : /*
24 : * Path string class, similar to boost::filesystem::basic_path.
25 : */
26 :
27 : // notes:
28 : // - this module is independent of lib/file so that it can be used from
29 : // other code without pulling in the entire file manager.
30 : // - there is no restriction on buffer lengths except the underlying OS.
31 : // input buffers must not exceed PATH_MAX chars, while outputs
32 : // must hold at least that much.
33 : // - unless otherwise mentioned, all functions are intended to work with
34 : // native and VFS paths.
35 : // when reading, both '/' and SYS_DIR_SEP are accepted; '/' is written.
36 :
37 : #ifndef INCLUDED_PATH
38 : #define INCLUDED_PATH
39 :
40 : #include "lib/debug.h"
41 : #include "lib/status.h"
42 : #include "lib/sysdep/os.h"
43 : #include "lib/utf8.h"
44 :
45 : #include <algorithm>
46 : #include <cstring>
47 : #include <cwchar>
48 : #include <filesystem>
49 : #include <istream>
50 : #include <string>
51 : #include <string_view>
52 : #include <utility>
53 :
54 : namespace ERR
55 : {
56 : const Status PATH_CHARACTER_ILLEGAL = -100300;
57 : const Status PATH_CHARACTER_UNSAFE = -100301;
58 : const Status PATH_NOT_FOUND = -100302;
59 : const Status PATH_MIXED_SEPARATORS = -100303;
60 : }
61 :
62 : /**
63 : * is s2 a subpath of s1, or vice versa? (equal counts as subpath)
64 : *
65 : * @param s1, s2 comparand strings
66 : * @return bool
67 : **/
68 : bool path_is_subpath(const wchar_t* s1, const wchar_t* s2);
69 :
70 : /**
71 : * Get the path component of a path.
72 : * Skips over all characters up to the last dir separator, if any.
73 : *
74 : * @param path Input path.
75 : * @return pointer to path component within \<path\>.
76 : **/
77 : const wchar_t* path_name_only(const wchar_t* path);
78 :
79 :
80 : // NB: there is a need for 'generic' paths (e.g. for Trace entry / archive pathnames).
81 : // converting between specialized variants via c_str would be inefficient, and the
82 : // Os/VfsPath types are hopefully sufficient to avoid errors.
83 2042936 : class Path
84 : {
85 : public:
86 : using String = std::wstring;
87 :
88 45123 : Path()
89 45123 : {
90 45123 : DetectSeparator();
91 45123 : }
92 :
93 289025 : Path(const Path& p)
94 289025 : : path(p.path)
95 : {
96 289025 : DetectSeparator();
97 289025 : }
98 :
99 19813 : Path(Path&& p)
100 19813 : : path(std::move(p.path))
101 : {
102 19813 : DetectSeparator();
103 19813 : }
104 :
105 12960 : Path(const char* p)
106 12960 : : path((const unsigned char*)p, (const unsigned char*)p+strlen(p))
107 : // interpret bytes as unsigned; makes no difference for ASCII,
108 : // and ensures OsPath on Unix will only contain values 0 <= c < 0x100
109 : {
110 12960 : DetectSeparator();
111 12960 : }
112 :
113 67386 : Path(const wchar_t* p)
114 67386 : : path(p, p+wcslen(p))
115 : {
116 67386 : DetectSeparator();
117 67386 : }
118 :
119 2535 : Path(const std::string& s)
120 2535 : : path((const unsigned char*)s.c_str(), (const unsigned char*)s.c_str()+s.length())
121 : {
122 2535 : DetectSeparator();
123 2535 : }
124 :
125 855712 : Path(std::wstring s)
126 855712 : : path(std::move(s))
127 : {
128 855712 : DetectSeparator();
129 855712 : }
130 :
131 9 : Path(const std::wstring_view& s)
132 9 : : path(s)
133 : {
134 9 : DetectSeparator();
135 9 : }
136 :
137 25139 : Path& operator=(const Path& rhs)
138 : {
139 25139 : path = rhs.path;
140 25139 : DetectSeparator(); // (warns if separators differ)
141 25139 : return *this;
142 : }
143 :
144 35664 : Path& operator=(Path&& rhs)
145 : {
146 35664 : path = std::move(rhs.path);
147 35664 : DetectSeparator();
148 35664 : return *this;
149 : }
150 :
151 178157 : bool empty() const
152 : {
153 239226 : return path.empty();
154 : }
155 :
156 : /**
157 : * @returns a STL version of the path.
158 : */
159 385 : std::filesystem::path fileSystemPath() const
160 : {
161 385 : return std::filesystem::path(path);
162 : }
163 :
164 417426 : const String& string() const
165 : {
166 733462 : return path;
167 : }
168 :
169 : /**
170 : * Return a UTF-8 version of the path, in a human-readable but potentially
171 : * lossy form. It is *not* safe to take this string and construct a new
172 : * Path object from it (it may fail for some non-ASCII paths) - it should
173 : * only be used for displaying paths to users.
174 : */
175 8279 : std::string string8() const
176 : {
177 8279 : Status err;
178 : #if !OS_WIN
179 : // On Unix, assume paths consisting of 8-bit charactes saved in this wide string.
180 8279 : std::string spath(path.begin(), path.end());
181 :
182 : // Return it if it's valid UTF-8
183 8279 : wstring_from_utf8(spath, &err);
184 8279 : if(err == INFO::OK)
185 8279 : return spath;
186 :
187 : // Otherwise assume ISO-8859-1 and let utf8_from_wstring treat each character as a Unicode code point.
188 : #endif
189 : // On Windows, paths are UTF-16 strings. We don't support non-BMP characters so we can assume it's simply a wstring.
190 0 : return utf8_from_wstring(path, &err);
191 8279 : }
192 :
193 1779855 : bool operator<(const Path& rhs) const
194 : {
195 1779830 : return path < rhs.path;
196 : }
197 :
198 4568 : bool operator==(const Path& rhs) const
199 : {
200 3411 : return path == rhs.path;
201 : }
202 :
203 1164 : bool operator!=(const Path& rhs) const
204 : {
205 1164 : return !operator==(rhs);
206 : }
207 :
208 221963 : bool IsDirectory() const
209 : {
210 221963 : if(empty()) // (ensure length()-1 is safe)
211 : return true; // (the VFS root directory is represented as an empty string)
212 221880 : return path[path.length()-1] == separator;
213 : }
214 :
215 29753 : Path Parent() const
216 : {
217 29753 : const size_t idxSlash = path.find_last_of(separator);
218 29753 : if(idxSlash == String::npos)
219 66 : return L"";
220 59374 : return path.substr(0, idxSlash);
221 : }
222 :
223 31073 : Path Filename() const
224 : {
225 31073 : const size_t idxSlash = path.find_last_of(separator);
226 31073 : if(idxSlash == String::npos)
227 160 : return path;
228 61986 : return path.substr(idxSlash+1);
229 : }
230 :
231 19954 : Path Basename() const
232 : {
233 19954 : const Path filename = Filename();
234 19954 : const size_t idxDot = filename.string().find_last_of('.');
235 19954 : if(idxDot == String::npos)
236 22 : return filename;
237 39864 : return filename.string().substr(0, idxDot);
238 19954 : }
239 :
240 41785 : std::wstring_view Extension() const
241 : {
242 41785 : const std::wstring_view filename{path};
243 41785 : const size_t idxDot = filename.find_last_of('.');
244 41785 : if(idxDot == String::npos)
245 0 : return {};
246 41785 : return filename.substr(idxDot);
247 : }
248 :
249 19945 : Path ChangeExtension(Path extension) const
250 : {
251 79748 : return Parent() / Path(Basename().string() + extension.string());
252 : }
253 :
254 144838 : Path operator/(const Path& rhs) const
255 : {
256 144838 : Path ret = *this;
257 144838 : if(ret.path.empty()) // (empty paths assume '/')
258 83 : ret.separator = rhs.separator;
259 144838 : if(!ret.IsDirectory())
260 68081 : ret.path += ret.separator;
261 :
262 144838 : if(rhs.path.find((ret.separator == '/')? '\\' : '/') != String::npos)
263 : {
264 0 : PrintToDebugOutput();
265 0 : rhs.PrintToDebugOutput();
266 0 : DEBUG_WARN_ERR(ERR::PATH_MIXED_SEPARATORS);
267 : }
268 144838 : ret.path += rhs.path;
269 144838 : return ret;
270 0 : }
271 :
272 : /**
273 : * Return the path before the common part of both paths
274 : * @param other Indicates the start of the path which should be removed
275 : * @note other should be a VfsPath, while this should be an OsPath
276 : */
277 8877 : Path BeforeCommon(Path other) const
278 : {
279 8877 : Path ret = *this;
280 8877 : if(ret.empty() || other.empty())
281 0 : return L"";
282 :
283 : // Convert the separator to allow for string comparison
284 8877 : if(other.separator != ret.separator)
285 0 : std::replace(other.path.begin(), other.path.end(), other.separator, ret.separator);
286 :
287 8877 : const size_t idx = ret.path.rfind(other.path);
288 8877 : if(idx == String::npos)
289 0 : return L"";
290 :
291 17754 : return path.substr(0, idx);
292 8877 : }
293 :
294 : static Status Validate(String::value_type c);
295 :
296 : private:
297 0 : void PrintToDebugOutput() const
298 : {
299 0 : debug_printf("Path %s, separator %c\n", string8().c_str(), (char)separator);
300 0 : }
301 :
302 1353500 : void DetectSeparator()
303 : {
304 1353500 : const size_t idxBackslash = path.find('\\');
305 :
306 1353500 : if(path.find('/') != String::npos && idxBackslash != String::npos)
307 : {
308 0 : PrintToDebugOutput();
309 0 : DEBUG_WARN_ERR(ERR::PATH_MIXED_SEPARATORS);
310 : }
311 :
312 : // (default to '/' for empty strings)
313 1353500 : separator = (idxBackslash == String::npos)? '/' : '\\';
314 1353500 : }
315 :
316 : String path;
317 :
318 : // note: ideally, path strings would only contain '/' or even SYS_DIR_SEP.
319 : // however, Windows-specific code (e.g. the sound driver detection)
320 : // uses these routines with '\\' strings. the boost::filesystem approach of
321 : // converting them all to '/' and then back via external_file_string is
322 : // annoying and inefficient. we allow either type of separators,
323 : // appending whichever was first encountered. when modifying the path,
324 : // we ensure the same separator is used.
325 : wchar_t separator = L'/';
326 : };
327 :
328 : static inline std::wostream& operator<<(std::wostream& s, const Path& path)
329 : {
330 : s << path.string();
331 : return s;
332 : }
333 :
334 : static inline std::wistream& operator>>(std::wistream& s, Path& path)
335 : {
336 : Path::String string;
337 : s >> string;
338 : path = Path(string);
339 : return s;
340 : }
341 :
342 : namespace std
343 : {
344 : template<>
345 : struct hash<Path>
346 : {
347 800 : std::size_t operator()(const Path& path) const
348 : {
349 800 : return m_StringHash(path.string());
350 : }
351 :
352 : private:
353 : std::hash<std::wstring> m_StringHash;
354 : };
355 : }
356 :
357 : #endif // #ifndef INCLUDED_PATH
|