+int hreader_pread(struct hreader *h, void *buffer, size_t n, off_t offset) {
+ size_t bytes_read = 0;
+
+ while(bytes_read < n) {
+ // If the desired byte range is outside the file, fetch new contents
+ if(offset < h->buf_offset || offset >= h->buf_offset + (off_t)h->bytes) {
+ int r = hreader_fill(h, offset);
+ if(r < 0)
+ return -1; /* disaster! */
+ else if(r == 0)
+ break; /* end of file */
+ }
+ // Figure out how much we can read this time round
+ size_t left = h->bytes - (offset - h->buf_offset);
+ // Truncate the read if we don't want that much
+ if(left > (n - bytes_read))
+ left = n - bytes_read;
+ memcpy((char *)buffer + bytes_read,
+ h->buffer + (offset - h->buf_offset),
+ left);
+ offset += left;
+ bytes_read += left;