2 This file is part of libmsppath
3 Copyright © 2006 Mikko Rasa, Mikkosoft Productions
4 Distributed under the LGPL
6 #include <msp/strutils.h>
15 bool is_windows_drive(const std::string &p)
17 return (p.size()==2 && ((p[0]>='A' && p[0]<='Z') || (p[0]>='a' && p[0]<='z')) && p[1]==':');
21 Returns the number of components in the path.
23 unsigned Path::size() const
25 if(!path.size()) return 0;
26 if(path.size()==1 && path[0]==DIRCHAR) return 1;
28 for(string::const_iterator i=path.begin(); i!=path.end(); ++i)
29 if(*i==DIRCHAR) ++count;
33 bool Path::is_absolute() const
36 if(is_windows_drive((*this)[0])) return true;
38 if(path[0]==DIRCHAR) return true;
42 Path Path::subpath(unsigned start, unsigned count) const
46 for(unsigned j=0; (j<start && i!=end()); ++j)
48 for(unsigned j=0; (j<count && i!=end()); ++j)
57 Attaches another path to the end of this one. An absolute path replaces the
58 existing data. ".." elements annihilate the last component and "." elements
61 Path &Path::operator/=(const Path &p)
67 for(iterator i=p.begin(); i!=p.end(); ++i)
71 unsigned slash=path.rfind(DIRCHAR);
73 if(is_windows_drive(path.substr(0,slash))) ++slash;
76 if(slash==string::npos)
83 if(path.size()>1 || (path.size()==1 && path[0]!=DIRCHAR))
93 Returns the path component at the specified index. Negative indices count from
96 string Path::operator[](int n) const
100 for(iterator i=begin(); i!=end(); ++i,--n)
105 for(iterator i=--end();; --i)
108 if(i==begin()) break;
115 bool Path::operator==(const Path &p) const
118 return !strcasecmp(path, p.path);
124 void Path::init(const std::string &p)
132 unsigned slash=p.find_first_of("/\\",start);
135 if(path.size() || absolute)
137 path+=p.substr(start,slash-start);
139 if(slash==string::npos)
145 Path::iterator::iterator(const Path &p):
149 if(path.path[0]==DIRCHAR)
152 else if(path.path[2]==DIRCHAR && is_windows_drive(path.path.substr(0,2)))
156 end=path.path.find(DIRCHAR);
159 Path::iterator &Path::iterator::operator++()
162 if(start>=path.path.size()) return *this;
163 if(path.path[start]==DIRCHAR) ++start;
164 end=path.path.find(DIRCHAR,start);
168 Path::iterator &Path::iterator::operator--()
171 if(end==0) return *this;
172 if(end>1 && end<path.path.size() && path.path[end]!=DIRCHAR) --end;
173 start=path.path.rfind(DIRCHAR,end-1);
174 if(start==string::npos)
181 string Path::iterator::operator*() const
183 if(start>=path.path.size()) return "";
184 if(start==end) return "";
185 return path.path.substr(start,end-start);