Rewrite NTS Framework.
[sim/o1-interface.git] / ntsimulator / regxstring / gen_regex.cpp
1 /*************************************************************************\r
2 *\r
3 * Licensed under the Apache License, Version 2.0 (the "License");\r
4 * you may not use this file except in compliance with the License.\r
5 * You may obtain a copy of the License at\r
6 *\r
7 *     http://www.apache.org/licenses/LICENSE-2.0\r
8 *\r
9 * Unless required by applicable law or agreed to in writing, software\r
10 * distributed under the License is distributed on an "AS IS" BASIS,\r
11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
12 * See the License for the specific language governing permissions and\r
13 * limitations under the License.\r
14 ***************************************************************************/\r
15 \r
16 #include <string>\r
17 #include <cstdlib>\r
18 #include <iostream>\r
19 \r
20 #include "regxstring.h"\r
21 \r
22 using namespace std;\r
23 \r
24 static string trim(std::string str){\r
25     size_t i = 0,e = str.length();\r
26     for(;i < e && std::isspace(str[i]);++i);\r
27     size_t j = e;\r
28     for(;j > i && std::isspace(str[j - 1]);--j);\r
29     return (i < j ? str.substr(i,j - i) : "");\r
30 }\r
31 \r
32 static string pre_handle(const string & str)\r
33 {\r
34     string ret = trim(str);\r
35     if(!ret.empty()) {\r
36         if(ret[0] != '^') {\r
37             ret.insert(ret.begin(),'^');\r
38         }\r
39 \r
40         if(ret[ret.size() - 1] != '$') {\r
41             ret.push_back('$');\r
42         }\r
43     }\r
44     return ret;\r
45 }\r
46 \r
47 static void rand_init(void) {\r
48     unsigned int seed;\r
49     FILE* urandom = fopen("/dev/urandom", "r");\r
50     size_t ret = fread(&seed, sizeof(int), 1, urandom);\r
51     (void)ret;\r
52     fclose(urandom);\r
53     srand(seed);\r
54     srandom(seed);\r
55 }\r
56 \r
57 int main(int argc, const char ** argv)\r
58 {\r
59     CRegxString regxstr;\r
60     string regx = "";\r
61 \r
62     switch(argc) {\r
63         case 2:\r
64             rand_init();\r
65             regx = argv[1];\r
66             break;\r
67 \r
68         case 3:\r
69             int pseudo_seed = 0;\r
70             int i = 0;\r
71             while(argv[1][i]) {\r
72                 pseudo_seed *= 10;\r
73                 pseudo_seed += argv[1][i] - '0';\r
74                 i++;\r
75             }\r
76             srand(pseudo_seed);\r
77             srandom(pseudo_seed);\r
78             regx = argv[2];\r
79             break;\r
80     }\r
81 \r
82     regxstr.ParseRegx(pre_handle(regx).c_str());\r
83     cout << regxstr.RandString() << endl;\r
84     \r
85     return 0;\r
86 }\r