]> git.tdb.fi Git - libs/core.git/blob - source/strings/glob.cpp
Add some utility functions for joining strings
[libs/core.git] / source / strings / glob.cpp
1 #include "glob.h"
2
3 using namespace std;
4
5 namespace {
6
7 template<bool icase>
8 bool cmp(char c, char h);
9
10 template<>
11 bool cmp<true>(char c, char h)
12 { return tolower(c)==tolower(h); }
13
14 template<>
15 bool cmp<false>(char c, char h)
16 { return c==h; }
17
18 template<bool icase>
19 bool globmatch(string::const_iterator pat_i, const string::const_iterator &pat_e, string::const_iterator str_i, const string::const_iterator &str_e)
20 {
21         while(pat_i!=pat_e && str_i!=str_e)
22         {
23                 if(*pat_i=='?' || cmp<icase>(*str_i, *pat_i))
24                 {
25                         ++pat_i;
26                         ++str_i;
27                 }
28                 else if(*pat_i=='*')
29                 {
30                         ++pat_i;
31                         if(pat_i==pat_e)
32                                 return true;
33                         
34                         for(; str_i!=str_e; ++str_i)
35                                 if(cmp<icase>(*str_i, *pat_i) && globmatch<icase>(pat_i, pat_e, str_i, str_e))
36                                         return true;
37                         
38                         return false;
39                 }
40                 else
41                         return false;
42         }
43
44         return pat_i==pat_e && str_i==str_e;
45 }
46
47 }
48
49 namespace Msp {
50
51 bool globmatch(const string &pat, const string &str)
52 {
53         return ::globmatch<false>(pat.begin(), pat.end(), str.begin(), str.end());
54 }
55
56 bool globcasematch(const string &pat, const string &str)
57 {
58         return ::globmatch<true>(pat.begin(), pat.end(), str.begin(), str.end());
59 }
60
61 } // namespace Msp