Rewrite QFS_FileExtension() to be more correct.

This commit is contained in:
Bill Currie 2011-09-09 17:33:29 +09:00
parent 08fa6be9f4
commit 96ef0ffaea
2 changed files with 40 additions and 5 deletions

View file

@ -1337,12 +1337,20 @@ QFS_StripExtension (const char *in, char *out)
VISIBLE const char *
QFS_FileExtension (const char *in)
{
char *tmp;
const char *tmp;
const char *end = in + strlen (in);
if ((tmp = strrchr (in, '.')))
return tmp;
for (tmp = end; tmp != in; tmp--) {
if (tmp[-1] == '/')
return end;
if (tmp[-1] == '.') {
if (tmp - 1 == in || tmp[-2] == '/')
return end;
return tmp - 1;
}
}
return in;
return end;
}
VISIBLE void

View file

@ -30,6 +30,22 @@ struct {
};
#define num_path_tests (sizeof (path_tests) / sizeof (path_tests[0]))
struct {
const char *path;
int expect_offset;
} ext_tests[] = {
{"foo", 3},
{"foo.a", 3},
{"foo.a.b", 5},
{".foo", 4},
{"bar/foo", 7},
{"bar/foo.a", 7},
{"bar/foo.a.b", 9},
{"bar/.foo", 8},
{"bar.a/foo", 9},
};
#define num_ext_tests (sizeof (ext_tests) / sizeof (ext_tests[0]))
int
main (int argc, const char **argv)
{
@ -37,12 +53,23 @@ main (int argc, const char **argv)
int res = 0;
for (i = 0; i < num_path_tests; i++) {
char *cpath = QFS_CompressPath (path_tests[i].path);
const char *cpath = QFS_CompressPath (path_tests[i].path);
if (strcmp (cpath, path_tests[i].expect)) {
fprintf (stderr, "FAIL: (%zd) \"%s\" -> \"%s\", got \"%s\"\n", i,
path_tests[i].path, path_tests[i].expect, cpath);
res = 1;
}
}
for (i = 0; i < num_ext_tests; i++) {
const char *ext = QFS_FileExtension (ext_tests[i].path);
if (ext - ext_tests[i].path != ext_tests[i].expect_offset) {
fprintf (stderr, "FAIL: (%zd) \"%s\" -> %d (%s), got %d (%s)\n", i,
ext_tests[i].path, ext_tests[i].expect_offset,
ext_tests[i].path + ext_tests[i].expect_offset,
ext - ext_tests[i].path, ext);
res = 1;
}
}
return res;
}