### ----------------------------------------------------
### -- Pakku
### -- Licenses: Artistic-2.0
### -- Authors: Haytham Elganiny
### -- File: lib/Pakku/HTTP.rakumod
### ----------------------------------------------------
### -- Chunk 2 of 2
buf: 0, $_ + 4;

          my ( $marker, @header-lines ) = $head.decode('latin1').lines;
          die "Invalid multipart boundary marker: $marker"
            unless $marker eq "--$boundary";

          my %headers = self.read-header-lines: @header-lines;
          with %headers<content-range> {
            die "Invalid Content-Range header: $_"
              unless /
                ^ 'bytes '
                $<start> = \d+ '-' $<end> = \d*
                '/'
                $<total> = \d+
                $
              /;
          }

          # Start and end are zero-based, but total is one-based
          my $length = ( $<end> // ( $<total> - 1 ) ) - +$<start> + 1;

          # We make a distinction between the bytes in the current
          # part and the bytes in the rest of the response body that
          # belong to possible other parts
          my $part = $body.subbuf: $head.bytes, $length;
          $body .= subbuf: $head.bytes + $part.bytes;

          my $read-bytes = $part.bytes;

          # It's possible for the current part to be greater than
          # the size of the current response chunk we have. If so,
          # we need to continue reading until we have the entire
          # part
          loop {
            callback( $part, %headers );
            last if $read-bytes >= $length;

            my $read = $!handle.read: BUFFER-SIZE;
            die "Did not receive full byte range"
              if !$read && $read-bytes < $length;

            $read-bytes += $read.bytes;

            # Including the bytes we have just read, we have more
            # than the full part, so we save the rest in $body for
            # further processing.
            if $read-bytes > $length {
              my $want = $read-bytes - $length;
              $part = $read.subbuf: 0, *-$want - 1;
              $body = $read.subbuf:  *-$want;
            }
            else {
              $part = $read;
            }
          }

          # Discard the CRLF preceding the next separator
          $body .= subbuf: 2;
        }
        else {
          # We have not read the header yet, need more
          my $read = $!handle.read: BUFFER-SIZE or last;
          $body ~= $read;
        }

        with $end-of-stream {
          last if $body.subbuf( 0, .bytes ) eq $_;
        }
      }

      return;
    }
  }
}



