PixelBullet  0.0.1
A C++ game engine
Loading...
Searching...
No Matches
path.h
1#pragma once
2
3#include <algorithm>
4#include <filesystem>
5#include <vector>
6
7namespace pixelbullet::filesystem
8{
9[[nodiscard]] inline std::filesystem::path normalized_path(const std::filesystem::path& path)
10{
11 std::filesystem::path normalized = path.lexically_normal();
12 while (!normalized.empty() && !normalized.has_filename())
13 {
14 const std::filesystem::path parent = normalized.parent_path();
15 if (parent.empty() || parent == normalized)
16 {
17 break;
18 }
19 normalized = parent;
20 }
21 return normalized;
22}
23
24[[nodiscard]] inline bool paths_equal(const std::filesystem::path& lhs, const std::filesystem::path& rhs)
25{
26 return normalized_path(lhs) == normalized_path(rhs);
27}
28
29[[nodiscard]] inline bool path_is_within(const std::filesystem::path& path, const std::filesystem::path& directory)
30{
31 if (path.empty() || directory.empty())
32 {
33 return false;
34 }
35
36 const std::filesystem::path normalized_target = normalized_path(path);
37 const std::filesystem::path normalized_directory = normalized_path(directory);
38 auto target_it = normalized_target.begin();
39 for (auto directory_it = normalized_directory.begin(); directory_it != normalized_directory.end(); ++directory_it, ++target_it)
40 {
41 if (target_it == normalized_target.end() || *target_it != *directory_it)
42 {
43 return false;
44 }
45 }
46
47 return true;
48}
49
50inline void normalize_sort_unique_paths(std::vector<std::filesystem::path>& paths)
51{
52 for (std::filesystem::path& path : paths)
53 {
54 path = normalized_path(path);
55 }
56
57 std::sort(paths.begin(), paths.end());
58 paths.erase(std::unique(paths.begin(), paths.end()), paths.end());
59}
60} // namespace pixelbullet::filesystem