From 880c063d0411400cf71a25e20695a17927cac3e9 Mon Sep 17 00:00:00 2001 From: Florent Rougon Date: Fri, 27 Oct 2017 20:49:17 +0200 Subject: [PATCH] Remove useless readdir() calls in Dir::isEmpty() simgear::Dir::isEmpty() used to make up to 5 calls to readdir(), while 3 are enough to say whether the directory has entries other than '.' and '..'. Also add an automated test for this method. --- simgear/misc/sg_dir.cxx | 5 ++++- simgear/misc/sg_dir_test.cxx | 25 +++++++++++++++++++++++++ 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/simgear/misc/sg_dir.cxx b/simgear/misc/sg_dir.cxx index 79a6ff97..9430e1b2 100644 --- a/simgear/misc/sg_dir.cxx +++ b/simgear/misc/sg_dir.cxx @@ -296,7 +296,10 @@ bool Dir::isEmpty() const int n = 0; dirent* d; - while( (d = readdir(dp)) !=NULL && (n < 4) ) n++; + while (n < 3 && (d = readdir(dp)) != nullptr) { + n++; + } + closedir(dp); return (n == 2); // '.' and '..' always exist diff --git a/simgear/misc/sg_dir_test.cxx b/simgear/misc/sg_dir_test.cxx index 4c6526ae..dd6cbac8 100644 --- a/simgear/misc/sg_dir_test.cxx +++ b/simgear/misc/sg_dir_test.cxx @@ -2,6 +2,7 @@ #include +#include #include #include #include "sg_dir.hxx" @@ -34,11 +35,35 @@ void test_tempDir() d.remove(); } +void test_isEmpty() +{ + simgear::Dir d = simgear::Dir::tempDir("FlightGear"); + SG_VERIFY(!d.isNull() && d.exists() && d.isEmpty()); + SGPath f = d.file("some file"); + + { sg_ofstream file(f); } // create and close the file + SG_VERIFY(!d.isEmpty()); + + f.remove(); + SG_VERIFY(d.isEmpty()); + + simgear::Dir subDir{d.file("some subdir")}; + subDir.create(0777); + SG_VERIFY(!d.isEmpty()); + + subDir.remove(); + SG_VERIFY(d.isEmpty()); + + d.remove(); + SG_VERIFY(d.isEmpty()); // eek, but that's how it is +} + int main(int argc, char **argv) { test_isNull(); test_setRemoveOnDestroy(); test_tempDir(); + test_isEmpty(); return EXIT_SUCCESS; }