From 96ef0ffaea30a11c2975e49aefe6081ee9f2fc06 Mon Sep 17 00:00:00 2001 From: Bill Currie Date: Fri, 9 Sep 2011 17:33:29 +0900 Subject: [PATCH] Rewrite QFS_FileExtension() to be more correct. --- libs/util/quakefs.c | 16 ++++++++++++---- libs/util/test/test-qfs.c | 29 ++++++++++++++++++++++++++++- 2 files changed, 40 insertions(+), 5 deletions(-) diff --git a/libs/util/quakefs.c b/libs/util/quakefs.c index d5070bb4b..fb780d228 100644 --- a/libs/util/quakefs.c +++ b/libs/util/quakefs.c @@ -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 diff --git a/libs/util/test/test-qfs.c b/libs/util/test/test-qfs.c index 8d475a8a8..3dc81bd89 100644 --- a/libs/util/test/test-qfs.c +++ b/libs/util/test/test-qfs.c @@ -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; }