Pyrogenesis HEAD
Pyrogenesis, a RTS Engine
path.h
Go to the documentation of this file.
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
54namespace ERR
55{
58 const Status PATH_NOT_FOUND = -100302;
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 **/
68bool 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 **/
77const 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.
83class Path
84{
85public:
86 using String = std::wstring;
87
89 {
91 }
92
93 Path(const Path& p)
94 : path(p.path)
95 {
97 }
98
100 : path(std::move(p.path))
101 {
103 }
104
105 Path(const char* p)
106 : 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 {
111 }
112
113 Path(const wchar_t* p)
114 : path(p, p+wcslen(p))
115 {
117 }
118
119 Path(const std::string& s)
120 : path((const unsigned char*)s.c_str(), (const unsigned char*)s.c_str()+s.length())
121 {
123 }
124
125 Path(std::wstring s)
126 : path(std::move(s))
127 {
129 }
130
131 Path(const std::wstring_view& s)
132 : path(s)
133 {
135 }
136
137 Path& operator=(const Path& rhs)
138 {
139 path = rhs.path;
140 DetectSeparator(); // (warns if separators differ)
141 return *this;
142 }
143
145 {
146 path = std::move(rhs.path);
148 return *this;
149 }
150
151 bool empty() const
152 {
153 return path.empty();
154 }
155
156 /**
157 * @returns a STL version of the path.
158 */
159 std::filesystem::path fileSystemPath() const
160 {
161 return std::filesystem::path(path);
162 }
163
164 const String& string() const
165 {
166 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 std::string string8() const
176 {
177 Status err;
178#if !OS_WIN
179 // On Unix, assume paths consisting of 8-bit charactes saved in this wide string.
180 std::string spath(path.begin(), path.end());
181
182 // Return it if it's valid UTF-8
183 wstring_from_utf8(spath, &err);
184 if(err == INFO::OK)
185 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 return utf8_from_wstring(path, &err);
191 }
192
193 bool operator<(const Path& rhs) const
194 {
195 return path < rhs.path;
196 }
197
198 bool operator==(const Path& rhs) const
199 {
200 return path == rhs.path;
201 }
202
203 bool operator!=(const Path& rhs) const
204 {
205 return !operator==(rhs);
206 }
207
208 bool IsDirectory() const
209 {
210 if(empty()) // (ensure length()-1 is safe)
211 return true; // (the VFS root directory is represented as an empty string)
212 return path[path.length()-1] == separator;
213 }
214
215 Path Parent() const
216 {
217 const size_t idxSlash = path.find_last_of(separator);
218 if(idxSlash == String::npos)
219 return L"";
220 return path.substr(0, idxSlash);
221 }
222
224 {
225 const size_t idxSlash = path.find_last_of(separator);
226 if(idxSlash == String::npos)
227 return path;
228 return path.substr(idxSlash+1);
229 }
230
232 {
233 const Path filename = Filename();
234 const size_t idxDot = filename.string().find_last_of('.');
235 if(idxDot == String::npos)
236 return filename;
237 return filename.string().substr(0, idxDot);
238 }
239
240 std::wstring_view Extension() const
241 {
242 const std::wstring_view filename{path};
243 const size_t idxDot = filename.find_last_of('.');
244 if(idxDot == String::npos)
245 return {};
246 return filename.substr(idxDot);
247 }
248
249 Path ChangeExtension(Path extension) const
250 {
251 return Parent() / Path(Basename().string() + extension.string());
252 }
253
254 Path operator/(const Path& rhs) const
255 {
256 Path ret = *this;
257 if(ret.path.empty()) // (empty paths assume '/')
258 ret.separator = rhs.separator;
259 if(!ret.IsDirectory())
260 ret.path += ret.separator;
261
262 if(rhs.path.find((ret.separator == '/')? '\\' : '/') != String::npos)
263 {
265 rhs.PrintToDebugOutput();
267 }
268 ret.path += rhs.path;
269 return ret;
270 }
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 Path BeforeCommon(Path other) const
278 {
279 Path ret = *this;
280 if(ret.empty() || other.empty())
281 return L"";
282
283 // Convert the separator to allow for string comparison
284 if(other.separator != ret.separator)
285 std::replace(other.path.begin(), other.path.end(), other.separator, ret.separator);
286
287 const size_t idx = ret.path.rfind(other.path);
288 if(idx == String::npos)
289 return L"";
290
291 return path.substr(0, idx);
292 }
293
294 static Status Validate(String::value_type c);
295
296private:
298 {
299 debug_printf("Path %s, separator %c\n", string8().c_str(), (char)separator);
300 }
301
303 {
304 const size_t idxBackslash = path.find('\\');
305
306 if(path.find('/') != String::npos && idxBackslash != String::npos)
307 {
310 }
311
312 // (default to '/' for empty strings)
313 separator = (idxBackslash == String::npos)? '/' : '\\';
314 }
315
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
328static inline std::wostream& operator<<(std::wostream& s, const Path& path)
329{
330 s << path.string();
331 return s;
332}
333
334static 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
342namespace std
343{
344template<>
345struct hash<Path>
346{
347 std::size_t operator()(const Path& path) const
348 {
349 return m_StringHash(path.string());
350 }
351
352private:
353 std::hash<std::wstring> m_StringHash;
354};
355}
356
357#endif // #ifndef INCLUDED_PATH
Definition: path.h:84
Path(std::wstring s)
Definition: path.h:125
std::string string8() const
Return a UTF-8 version of the path, in a human-readable but potentially lossy form.
Definition: path.h:175
void PrintToDebugOutput() const
Definition: path.h:297
wchar_t separator
Definition: path.h:325
Path(const Path &p)
Definition: path.h:93
Path(const std::wstring_view &s)
Definition: path.h:131
Path & operator=(Path &&rhs)
Definition: path.h:144
void DetectSeparator()
Definition: path.h:302
bool IsDirectory() const
Definition: path.h:208
bool operator!=(const Path &rhs) const
Definition: path.h:203
Path ChangeExtension(Path extension) const
Definition: path.h:249
Path(const wchar_t *p)
Definition: path.h:113
bool empty() const
Definition: path.h:151
bool operator==(const Path &rhs) const
Definition: path.h:198
Path(const char *p)
Definition: path.h:105
Path(Path &&p)
Definition: path.h:99
std::filesystem::path fileSystemPath() const
Definition: path.h:159
std::wstring String
Definition: path.h:86
Path Filename() const
Definition: path.h:223
Path operator/(const Path &rhs) const
Definition: path.h:254
static Status Validate(String::value_type c)
Definition: path.cpp:102
Path BeforeCommon(Path other) const
Return the path before the common part of both paths.
Definition: path.h:277
Path Basename() const
Definition: path.h:231
Path & operator=(const Path &rhs)
Definition: path.h:137
bool operator<(const Path &rhs) const
Definition: path.h:193
String path
Definition: path.h:316
std::wstring_view Extension() const
Definition: path.h:240
const String & string() const
Definition: path.h:164
Path Parent() const
Definition: path.h:215
Path()
Definition: path.h:88
Path(const std::string &s)
Definition: path.h:119
void debug_printf(const char *fmt,...)
write a formatted string to the debug channel.
Definition: debug.cpp:71
#define DEBUG_WARN_ERR(status)
display the error dialog with text corresponding to the given error code.
Definition: debug.h:271
Definition: debug.h:340
const Status PATH_CHARACTER_ILLEGAL
Definition: path.h:56
const Status PATH_MIXED_SEPARATORS
Definition: path.h:59
const Status PATH_NOT_FOUND
Definition: path.h:58
const Status PATH_CHARACTER_UNSAFE
Definition: path.h:57
const Status OK
Definition: status.h:394
Definition: ShaderDefines.cpp:43
static std::wostream & operator<<(std::wostream &s, const Path &path)
Definition: path.h:328
bool path_is_subpath(const wchar_t *s1, const wchar_t *s2)
is s2 a subpath of s1, or vice versa? (equal counts as subpath)
Definition: path.cpp:54
static std::wistream & operator>>(std::wistream &s, Path &path)
Definition: path.h:334
const wchar_t * path_name_only(const wchar_t *path)
Get the path component of a path.
Definition: path.cpp:88
std::int64_t Status
Error handling system.
Definition: status.h:174
std::size_t operator()(const Path &path) const
Definition: path.h:347
std::hash< std::wstring > m_StringHash
Definition: path.h:353
std::string utf8_from_wstring(const std::wstring_view src, Status *err)
opposite of wstring_from_utf8
Definition: utf8.cpp:217
std::wstring wstring_from_utf8(const std::string_view src, Status *err)
convert UTF-8 to a wide string (UTF-16 or UCS-4, depending on the platform's wchar_t).
Definition: utf8.cpp:234