From 8a1e778874350ed9dcd5a6c1a85d2714be2cd97c Mon Sep 17 00:00:00 2001 From: Elizabeth Mattijsen Date: Tue, 12 Apr 2022 16:20:59 +0200 Subject: [PATCH] Add an IO::Path.dir-with-entries method Checking whether a directory has entries in it, can be checked by doing e.g. an "if .dir.head {". However, this will leak resources as the iterator that runs "dir" will never be finished, and thus the underlying directory handle will also never be closed. Alternately, doing an "if dir.elems {" *would* close the underlying directory handle, but possibly after doing a lot of work if the directory in question actually contains *many* entries. This method will return a Bool that will indicate whether the IO::Path has any entries in it (:test to give a tester, default to "none(<. ..>)"). It will stop as soon as it finds a matching entry, close the directory handle, and return. --- src/core.c/IO/Path.pm6 | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/src/core.c/IO/Path.pm6 b/src/core.c/IO/Path.pm6 index f9a62de2b63..b6e0c6cabdf 100644 --- a/src/core.c/IO/Path.pm6 +++ b/src/core.c/IO/Path.pm6 @@ -842,6 +842,28 @@ my class IO::Path is Cool does IO { } } + proto method dir-with-entries(|) {*} + multi method dir-with-entries(IO::Path:D: --> Bool:D) { + my $handle := nqp::opendir(self.absolute); + nqp::while( + (my str $entry = nqp::nextfiledir($handle)) + && (nqp::iseq_s($entry,'.') || nqp::iseq_s($entry,'..')), + nqp::null() + ); + nqp::closedir($handle); + nqp::hllbool(nqp::chars($entry)) + } + multi method dir-with-entries(IO::Path:D: :$test! --> Bool:D) { + my $handle := nqp::opendir(self.absolute); + nqp::while( + (my str $entry = nqp::nextfiledir($handle)) + && !$test.ACCEPTS($entry), + nqp::null() + ); + nqp::closedir($handle); + nqp::hllbool(nqp::chars($entry)) + } + method CHECKSUM(IO::Path:D: --> Str:D) is implementation-detail { my \slurped := self.slurp(:enc); nqp::istype(slurped,Failure)