]> git.tdb.fi Git - libs/core.git/blob - source/fs/path.h
749578a8797cf519695d0e9b321819987aa76521
[libs/core.git] / source / fs / path.h
1 #ifndef MSP_FS_PATH_H_
2 #define MSP_FS_PATH_H_
3
4 #include <ostream>
5 #include <string>
6
7 namespace Msp {
8 namespace FS {
9
10 enum
11 {
12 #ifdef WIN32
13         DIRSEP = '\\'
14 #else
15         DIRSEP = '/'
16 #endif
17 };
18
19 /**
20 Stores a filesystem path.  Paths are always stored in a normalized form; there
21 are never any "." or ".." components in the middle of the path, and relative
22 paths always begin with a single "." component or a sequence ".." components.
23 */
24 class Path
25 {
26 public:
27         class Iterator
28         {
29                 friend class Path;
30
31         private:
32                 const Path &path;
33                 std::string::size_type start,end;
34
35                 Iterator(const Path &);
36         public:
37                 Iterator    &operator++();
38                 Iterator    &operator--();
39                 std::string operator*() const;
40                 bool        operator==(const Iterator &i) const { return (start==i.start && end==i.end); }
41                 bool        operator!=(const Iterator &i) const { return !(*this==i); }
42         };
43
44 private:
45         std::string path;
46
47 public:
48         Path();
49         Path(const std::string &);
50         Path(const char *);
51
52         const std::string &str() const { return path; }
53
54         /// Returns the number of components in the path.
55         unsigned    size() const;
56
57         bool        empty() const { return path.empty(); }
58
59         /// Determines whether the path starts from the root directory
60         bool is_absolute() const;
61
62         /// Extracts a range of components from the path.
63         Path subpath(unsigned start, unsigned count = static_cast<unsigned>(-1)) const;
64
65         /// Concatenates this path with another one, with usual filesystem semantics
66         Path operator/(const Path &p) const;
67         Path &operator/=(const Path &);
68
69         /**
70         Extracts a single component from the path.  Negative indices count from the
71         end of the path.
72         */
73         std::string operator[](int) const;
74
75         bool        operator==(const Path &) const;
76         Iterator    begin() const;
77         Iterator    end() const;
78 private:
79         void init(const std::string &);
80         void add_component(const std::string &);
81 };
82
83 inline std::ostream &operator<<(std::ostream &o, const Path &p) { o<<p.str(); return o; }
84
85 } // namespace FS
86 } // namespace Msp
87
88 #endif