Skip to content

Instantly share code, notes, and snippets.

@zoffixznet
Created April 12, 2017 16:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zoffixznet/310c12ca64d01e59e3f7d8bc3ff68787 to your computer and use it in GitHub Desktop.
Save zoffixznet/310c12ca64d01e59e3f7d8bc3ff68787 to your computer and use it in GitHub Desktop.
diff --git a/src/core/IO/Handle.pm b/src/core/IO/Handle.pm
index 3b284a2..981be2d 100644
--- a/src/core/IO/Handle.pm
+++ b/src/core/IO/Handle.pm
@@ -808,6 +808,33 @@ my class IO::Handle {
nqp::p6box_s(nqp::readallfh($!PIO));
}
+ method slurp(IO::Handle:D: :$close) {
+ # In binary mode, we figure out the size with tell/seek to end/tell.
+ # Some handles can't be .seeked, so we try a seek
+ # Note that we cannot just use filesize here, since the file position
+ # may have been adjusted by other reads or prior explicit .seek
+ my $res;
+ nqp::if(
+ nqp::iseq_s($!encoding, 'bin'),
+ nqp::stmts(
+ (my int $seek = nqp::tellfh($!PIO)), # current file position
+ (
+ my int $size = nqp::sub_i(
+ nqp::stmts(
+ nqp::seekfh($!PIO,0,2), # seek to end
+ nqp::tellfh($!PIO),
+ ), $seek
+ ) || 1 # read of 0 is an error, but OK to ask too much, so use 1
+ ),
+ nqp::seekfh($!PIO, $seek, 0), # seek to orig pos handle was at
+ ($res := nqp::readfh($!PIO, buf8.new, $size)),
+ ),
+ ($res := nqp::p6box_s(nqp::readallfh($!PIO))),
+ );
+ self.close if $close;
+ $res
+ }
+
proto method spurt(|) { * }
multi method spurt(IO::Handle:D: Blob $data, :$close) {
LEAVE self.close if $close;
diff --git a/src/core/IO/Pipe.pm b/src/core/IO/Pipe.pm
index 60e0907..2cf6924 100644
--- a/src/core/IO/Pipe.pm
+++ b/src/core/IO/Pipe.pm
@@ -6,6 +6,24 @@ my class IO::Pipe is IO::Handle {
nqp::bindattr(nqp::decont(self), IO::Handle, '$!PIO', Mu);
$!proc;
}
+
+ method slurp(IO::Handle:D: :$close) {
+ my $PIO := nqp::getattr(self, IO::Handle, '$!PIO');
+ my $res;
+ nqp::if(
+ nqp::iseq_s($.encoding, 'bin'),
+ nqp::stmts(
+ ($res := buf8.new),
+ nqp::while(
+ nqp::elems(my $buf := nqp::readfh($PIO, buf8.new, 0x100000)),
+ $res.append($buf)
+ )
+ ),
+ ($res := nqp::p6box_s(nqp::readallfh($PIO))),
+ );
+ self.close if $close;
+ $res
+ }
}
# vim: ft=perl6 expandtab sw=4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment