16 static char *clean_line(char *s);
18 //static std::vector<std::pair<std::regex, std::string>> dmap;
19 static std::vector<std::pair<std::string, std::string>> dmap;
20 static std::map<std::string, std::string> cache;
21 static std::string root;
29 void datamap_set_path(const char *path)
31 root = std::string(path);
34 bool datamap_load_map(const char *fname)
36 std::string path = root.empty() ? fname : root + std::string("/") + fname;
39 FILE *fp = fopen(fname, "r");
41 fprintf(stderr, "failed to open data map: %s\n", fname);
46 if(fread(buf, 1, 8, fp) < 8 || memcmp(buf, "DATAMAP0", 8) != 0) {
47 fprintf(stderr, "invalid datamap file: %s\n", fname);
56 while(fgets(buf, sizeof buf, fp)) {
58 line = clean_line(buf);
59 if(!line || !*line) continue;
61 char *colon = strchr(line, ':');
67 //std::pair<std::regex, std::string> pair;
68 //pair.first = std::regex(line);
69 std::pair<std::string, std::string> pair;
70 pair.first = std::string(line);
72 char *value = clean_line(colon + 1);
73 if(!value || !*value) {
76 pair.second = std::string(value);
81 printf("loaded datamap %s: %d mappings\n", fname, (int)dmap.size());
85 fprintf(stderr, "error while parsing %s, invalid line %d: %s\n", fname, nline, line);
91 void datamap_map(const char *re, const char *path)
93 //std::pair<std::regex, std::string> mapping;
94 //mapping.first = std::regex(re);
95 std::pair<std::string, std::string> mapping;
96 mapping.first = std::string(re);
97 mapping.second = std::string(path);
98 dmap.push_back(std::move(mapping));
101 int datamap_lookup(const char *in, char *buf, int bsz)
105 char *inbuf = (char*)alloca(strlen(in) + 1);
107 in = clean_line(inbuf);
109 // first check the cache
110 std::map<std::string, std::string>::iterator it = cache.find(in);
111 if(it != cache.end()) {
114 // try matching with the available mappings
115 res = std::string(in);
117 int num = dmap.size();
118 for(int i=0; i<num; i++) {
119 //if(std::regex_search(in, dmap[i].first)) {
120 if(strstr(in, dmap[i].first.c_str())) {
121 res = root.empty() ? dmap[i].second : root + "/" + dmap[i].second;
122 cache[in] = res; // add it to the cache
128 // copy result in buf, truncating if necessary and return the size of the
129 // buffer required to hold it
131 int n = std::min(bsz - 1, (int)res.length());
132 memcpy(buf, res.c_str(), n);
133 buf[bsz - 1] = 0; // make sure it's null-terminated even if it got truncated
135 return res.length() + 1;
138 int datamap_path_size(const char *in)
140 return datamap_lookup(in, 0, 0);
143 static char *clean_line(char *s)
145 while(*s && isspace(*s)) ++s;
149 if(!(end = strchr(s, '#'))) {
150 end = s + strlen(s) - 1;
152 while(end > s && isspace(*end)) --end;
153 if(s == end) return 0;
156 // app-specific: convert backslashes
159 if(*c == '\\') *c = '/';