PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
virtual_path.h
1#pragma once
2
3#include <cstddef>
4#include <string>
5#include <string_view>
6
7namespace pixelbullet
8{
9class VirtualPath
10{
11public:
12 VirtualPath() = default;
13
14 explicit VirtualPath(std::string_view path)
15 : logical_path_(path)
16 {
17 }
18
19 explicit VirtualPath(const char* path)
20 : logical_path_(path ? path : "")
21 {
22 }
23
24 VirtualPath(const VirtualPath&) = default;
25 VirtualPath(VirtualPath&&) noexcept = default;
26
27 VirtualPath& operator=(const VirtualPath&) = default;
28 VirtualPath& operator=(VirtualPath&&) noexcept = default;
29
30 ~VirtualPath() = default;
31
32 [[nodiscard]] const char* c_str() const noexcept
33 {
34 return logical_path_.c_str();
35 }
36
37 [[nodiscard]] const std::string& logical_path() const noexcept
38 {
39 return logical_path_;
40 }
41
42 [[nodiscard]] bool empty() const noexcept
43 {
44 return logical_path_.empty();
45 }
46
47 [[nodiscard]] std::wstring to_wstring() const
48 {
49 return std::wstring(logical_path_.begin(), logical_path_.end());
50 }
51
52 [[nodiscard]] bool has_extension(std::string_view ext) const noexcept
53 {
54 return extension() == ext;
55 }
56
57 [[nodiscard]] std::string_view extension() const noexcept
58 {
59 const std::size_t last_forward_slash = logical_path_.rfind('/');
60 const std::size_t last_backslash = logical_path_.rfind('\\');
61 const std::size_t last_separator = last_forward_slash == std::string::npos ? last_backslash
62 : last_backslash == std::string::npos
63 ? last_forward_slash
64 : (last_forward_slash > last_backslash ? last_forward_slash : last_backslash);
65 const std::size_t segment_start = last_separator == std::string::npos ? 0u : last_separator + 1u;
66 const std::size_t dot_position = logical_path_.rfind('.');
67 if (dot_position != std::string::npos && dot_position >= segment_start)
68 {
69 return std::string_view(logical_path_).substr(dot_position);
70 }
71 return std::string_view{};
72 }
73
74private:
75 std::string logical_path_;
76};
77
78inline VirtualPath operator/(const VirtualPath& lhs, const std::string& rhs)
79{
80 std::string result = lhs.logical_path();
81 if (!result.empty() && result.back() != '/' && !rhs.empty() && rhs.front() != '/')
82 {
83 result += '/';
84 }
85 result += rhs;
86 return VirtualPath(result);
87}
88
89inline VirtualPath operator/(const VirtualPath& lhs, const char* rhs)
90{
91 return lhs / std::string(rhs);
92}
93
94inline bool operator==(const VirtualPath& lhs, const VirtualPath& rhs) noexcept
95{
96 return lhs.logical_path() == rhs.logical_path();
97}
98
99inline bool operator!=(const VirtualPath& lhs, const VirtualPath& rhs) noexcept
100{
101 return !(lhs == rhs);
102}
103
104inline VirtualPath operator""_vp(const char* str, std::size_t len)
105{
106 return VirtualPath(std::string_view(str, len));
107}
108} // namespace pixelbullet
Definition virtual_path.h:10