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 if(!(in = clean_line(inbuf))) {
103 // first check the cache
104 std::map<std::string, std::string>::iterator it = cache.find(in);
105 if(it != cache.end()) {
108 // try matching with the available mappings
109 res = root.empty() ? std::string(in) : root + "/" + std::string(in);
111 int num = dmap.size();
112 for(int i=0; i<num; i++) {
113 //if(std::regex_search(in, dmap[i].first)) {
114 if(strstr(in, dmap[i].first.c_str())) {
115 res = root.empty() ? dmap[i].second : root + "/" + dmap[i].second;
116 cache[in] = res; // add it to the cache
122 // copy result in buf, truncating if necessary and return the size of the
123 // buffer required to hold it
125 int n = std::min(bsz - 1, (int)res.length());
126 memcpy(buf, res.c_str(), n);
127 buf[n] = 0; // make sure it's null-terminated even if it got truncated
129 return res.length() + 1;
132 int DataMap::path_size(const char *in) const
134 return lookup(in, 0, 0);
137 static char *clean_line(char *s)
139 while(*s && isspace(*s)) ++s;
143 if(!(end = strchr(s, '#'))) {
144 end = s + strlen(s) - 1;
146 while(end > s && isspace(*end)) --end;
147 if(s == end) return 0;
150 // app-specific: convert backslashes
153 if(*c == '\\') *c = '/';