12 static char *clean_line(char *s);
25 void DataMap::set_path(const char *path)
27 root = std::string(path);
30 void DataMap::set_strip(bool s)
35 bool DataMap::load_map(const char *fname)
37 std::string path = root.empty() ? fname : root + std::string("/") + fname;
40 FILE *fp = fopen(fname, "r");
42 fprintf(stderr, "failed to open data map: %s\n", fname);
47 if(fread(buf, 1, 8, fp) < 8 || memcmp(buf, "DATAMAP0", 8) != 0) {
48 fprintf(stderr, "invalid datamap file: %s\n", fname);
57 while(fgets(buf, sizeof buf, fp)) {
59 line = clean_line(buf);
60 if(!line || !*line) continue;
62 char *colon = strchr(line, ':');
68 //std::pair<std::regex, std::string> pair;
69 //pair.first = std::regex(line);
70 std::pair<std::string, std::string> pair;
71 pair.first = std::string(line);
73 char *value = clean_line(colon + 1);
74 if(!value || !*value) {
77 pair.second = std::string(value);
82 printf("loaded datamap %s: %d mappings\n", fname, (int)dmap.size());
86 fprintf(stderr, "error while parsing %s, invalid line %d: %s\n", fname, nline, line);
92 void DataMap::map(const char *match, const char *path)
94 std::pair<std::string, std::string> mapping;
95 mapping.first = std::string(match);
96 mapping.second = std::string(path);
97 dmap.push_back(std::move(mapping));
100 int DataMap::lookup(const char *in, char *buf, int bsz) const
105 const char *ptr = strrchr(in, '/');
111 char *inbuf = (char*)alloca(strlen(in) + 1);
113 in = clean_line(inbuf);
115 // first check the cache
116 std::map<std::string, std::string>::iterator it = cache.find(in);
117 if(it != cache.end()) {
120 // try matching with the available mappings
121 res = root.empty() ? std::string(in) : root + "/" + std::string(in);
123 int num = dmap.size();
124 for(int i=0; i<num; i++) {
125 //if(std::regex_search(in, dmap[i].first)) {
126 if(strstr(in, dmap[i].first.c_str())) {
127 res = root.empty() ? dmap[i].second : root + "/" + dmap[i].second;
128 cache[in] = res; // add it to the cache
134 // copy result in buf, truncating if necessary and return the size of the
135 // buffer required to hold it
137 int n = std::min(bsz - 1, (int)res.length());
138 memcpy(buf, res.c_str(), n);
139 buf[n] = 0; // make sure it's null-terminated even if it got truncated
141 return res.length() + 1;
144 int DataMap::path_size(const char *in) const
146 return lookup(in, 0, 0);
149 static char *clean_line(char *s)
151 while(*s && isspace(*s)) ++s;
155 if(!(end = strchr(s, '#'))) {
156 end = s + strlen(s) - 1;
158 while(end > s && isspace(*end)) --end;
159 if(s == end) return 0;
162 // app-specific: convert backslashes
165 if(*c == '\\') *c = '/';