Skip to content

Commit

Permalink
Add an IO::Path.dir-with-entries method
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
lizmat committed Apr 12, 2022
1 parent b2a8bfc commit 8a1e778
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions src/core.c/IO/Path.pm6
Expand Up @@ -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<iso-8859-1>);
nqp::istype(slurped,Failure)
Expand Down

0 comments on commit 8a1e778

Please sign in to comment.