Geant4 Cross Reference |
1 // Copyright (C) 2010, Guy Barrand. All rights reserved. 2 // See the file tools.license for terms. 3 4 #ifndef tools_smatch 5 #define tools_smatch 6 7 #include "words" 8 #include <cstring> 9 10 namespace tools { 11 12 inline bool match(const std::string& a_string,const std::string& a_pattern,bool a_check_for_wilds = true){ 13 std::string::size_type lpattern = a_pattern.length(); 14 std::string::size_type lstring = a_string.length(); 15 if ((lpattern==0)&&(lstring==0)) return true; 16 if ((lpattern==0)&&(lstring!=0)) return true; 17 if ((lpattern!=0)&&(lstring==0)) return false; 18 19 if((lpattern==1)&&(a_pattern[0]=='*')) return true; 20 21 if(a_check_for_wilds) { 22 bool some_star = false; 23 for(std::string::size_type count=0;count<lpattern;count++) { 24 if(a_pattern[count]=='*') {some_star = true;break;} 25 } 26 if(!some_star) { // no wildcard : 27 return (a_pattern==a_string ? true : false ); 28 } 29 } 30 31 // complex pattern : 32 //std::string::size_type* wps = new std::string::size_type[2*lpattern]; 33 if((2*lpattern)>1024) return false; //throw 34 std::string::size_type wps[1024]; //OPTIMIZATION : we gain a lot with that. 35 36 unsigned int wn; 37 std::string::size_type* wls = wps+lpattern; 38 words(a_pattern,"*",false,wn,wps,wls); 39 if(!wn) { 40 //delete [] wps; 41 return true; // only wildcards : 42 } 43 44 // tricky case : 45 char* token = (char*)a_string.c_str(); 46 {for(unsigned int count=0;count<wn;count++) { 47 size_t lword = wls[count]; 48 if(!lword) continue;//should never happen ! 49 //WARNING : ws_pos does not have a null char at ws_pos+lword ! 50 char* ws_pos = (char*)(a_pattern.c_str()+wps[count]); 51 if(count==0) { 52 if(a_pattern[0]!='*') { 53 // Begin of pattern (ws[0]) and a_string must match : 54 if(::strncmp(token,ws_pos,lword)) { 55 //delete [] wps; 56 return false; 57 } 58 token = token + lword; 59 continue; 60 } 61 } 62 char old_char = *(ws_pos+lword); 63 *(ws_pos+lword) = 0; 64 char* pos = ::strstr(token,ws_pos); 65 *(ws_pos+lword) = old_char; 66 if(!pos) { 67 //delete [] wps; 68 return false; 69 } 70 if((count==(wn-1)) && (a_pattern[lpattern-1]!='*') ) { // Last word. 71 // Compare last word and end of a_string. 72 if(::strncmp(a_string.c_str()+lstring-lword,ws_pos,lword)) { 73 //delete [] wps; 74 return false; 75 } 76 break; 77 } else { 78 token = pos + lword; 79 } 80 }} 81 82 //delete [] wps; 83 return true; 84 } 85 86 //for tools/app/find.cpp : 87 inline bool match2(const std::string& a_string,const std::string& a_pattern){ 88 return match(a_string,a_pattern,true); 89 } 90 91 inline void filter(std::vector<std::string>& a_v, 92 const std::string& a_pattern, 93 bool a_check_for_wilds = true){ 94 std::vector<std::string>::iterator it; 95 for(it=a_v.begin();it!=a_v.end();) { 96 if(match(*it,a_pattern,a_check_for_wilds)) { 97 it++; 98 } else { 99 it = a_v.erase(it); 100 } 101 } 102 } 103 104 } 105 106 #endif