12 static char *clean_line(char *s);
20 void DataMap::set_path(const char *path)
22 root = std::string(path);
25 bool DataMap::load_map(const char *fname)
27 std::string path = root.empty() ? fname : root + std::string("/") + fname;
30 FILE *fp = fopen(fname, "r");
32 fprintf(stderr, "failed to open data map: %s\n", fname);
37 if(fread(buf, 1, 8, fp) < 8 || memcmp(buf, "DATAMAP0", 8) != 0) {
38 fprintf(stderr, "invalid datamap file: %s\n", fname);
47 while(fgets(buf, sizeof buf, fp)) {
49 line = clean_line(buf);
50 if(!line || !*line) continue;
52 char *colon = strchr(line, ':');
58 //std::pair<std::regex, std::string> pair;
59 //pair.first = std::regex(line);
60 std::pair<std::string, std::string> pair;
61 pair.first = std::string(line);
63 char *value = clean_line(colon + 1);
64 if(!value || !*value) {
67 pair.second = std::string(value);
72 printf("loaded datamap %s: %d mappings\n", fname, (int)dmap.size());
76 fprintf(stderr, "error while parsing %s, invalid line %d: %s\n", fname, nline, line);
82 void DataMap::map(const char *match, const char *path)
84 std::pair<std::string, std::string> mapping;
85 mapping.first = std::string(match);
86 mapping.second = std::string(path);
87 dmap.push_back(std::move(mapping));
90 int DataMap::lookup(const char *in, char *buf, int bsz) const
94 char *inbuf = (char*)alloca(strlen(in) + 1);
96 in = clean_line(inbuf);
98 // first check the cache
99 std::map<std::string, std::string>::iterator it = cache.find(in);
100 if(it != cache.end()) {
103 // try matching with the available mappings
104 res = root.empty() ? std::string(in) : root + "/" + std::string(in);
106 int num = dmap.size();
107 for(int i=0; i<num; i++) {
108 //if(std::regex_search(in, dmap[i].first)) {
109 if(strstr(in, dmap[i].first.c_str())) {
110 res = root.empty() ? dmap[i].second : root + "/" + dmap[i].second;
111 cache[in] = res; // add it to the cache
117 // copy result in buf, truncating if necessary and return the size of the
118 // buffer required to hold it
120 int n = std::min(bsz - 1, (int)res.length());
121 memcpy(buf, res.c_str(), n);
122 buf[n] = 0; // make sure it's null-terminated even if it got truncated
124 return res.length() + 1;
127 int DataMap::path_size(const char *in) const
129 return lookup(in, 0, 0);
132 static char *clean_line(char *s)
134 while(*s && isspace(*s)) ++s;
138 if(!(end = strchr(s, '#'))) {
139 end = s + strlen(s) - 1;
141 while(end > s && isspace(*end)) --end;
142 if(s == end) return 0;
145 // app-specific: convert backslashes
148 if(*c == '\\') *c = '/';