+sub read_cat_in_full ($$$) {
+ my ($self, $in, $left) = @_;
+ my $offset = 0;
+ my $buf = '';
+ while ($left > 0) {
+ my $r = read($in, $buf, $left, $offset);
+ defined($r) or fail($self, "read failed: $!");
+ $r == 0 and fail($self, 'exited unexpectedly');
+ $left -= $r;
+ $offset += $r;
+ }
+ my $r = read($in, my $lf, 1);
+ defined($r) or fail($self, "read failed: $!");
+ fail($self, 'newline missing after blob') if ($r != 1 || $lf ne "\n");
+ \$buf;
+}
+
+sub _cat_async_step ($$$) {
+ my ($self, $inflight, $in) = @_;
+ my $cb = shift @$inflight or die 'BUG: inflight empty';
+ local $/ = "\n";
+ my $head = $in->getline;
+ return eval { $cb->(undef) } if $head =~ / missing$/;
+
+ $head =~ /^([0-9a-f]{40}) (\S+) ([0-9]+)$/ or
+ fail($self, "Unexpected result from async git cat-file: $head");
+ my ($oid_hex, $type, $size) = ($1, $2, $3 + 0);
+ my $bref = read_cat_in_full($self, $in, $size);
+ eval { $cb->($bref, $oid_hex, $type, $size) };
+}
+
+sub cat_async_wait ($) {
+ my ($self) = @_;
+ my $inflight = delete $self->{inflight} or return;
+ my $in = $self->{in};
+ while (scalar(@$inflight)) {
+ _cat_async_step($self, $inflight, $in);
+ }
+}
+