+
+ return rc;
+}
+
+struct lbx_file_state *lbx_file_open(struct lbx_state *lbx, unsigned fileno)
+{
+ struct lbx_file_state *state;
+
+ if (fileno >= lbx->nfiles) {
+ lbx_errno = LBX_ERANGE;
+ return NULL;
+ }
+
+ lbx->last_file = NULL;
+ if (lbx->fops->seek(lbx->f, lbx->offsets[fileno], SEEK_SET) != 0) {
+ lbx_errno = -errno;
+ return NULL;
+ }
+
+ state = malloc(sizeof *state);
+ if (!state) {
+ lbx_errno = -errno;
+ return NULL;
+ }
+
+ *state = (struct lbx_file_state) {
+ .base = lbx->offsets[fileno],
+ .limit = lbx->offsets[fileno+1] - lbx->offsets[fileno],
+ .lbx = lbx,
+ };
+
+ lbx->last_file = state;
+ return state;
+}
+
+size_t lbx_file_read(struct lbx_file_state *f, void *buf, size_t n)
+{
+ const struct lbx_file_ops *fops = f->lbx->fops;
+ size_t want = MIN(n, f->limit - f->offset);
+ size_t rc;
+
+ if (f != f->lbx->last_file) {
+ f->lbx->last_file = NULL;
+ if (fops->seek(f->lbx->f, f->base + f->limit, SEEK_SET) != 0)
+ return 0;
+ f->lbx->last_file = f;
+ }
+
+ rc = fops->read(buf, want, f->lbx->f);
+ f->offset += rc;
+
+ if (want < n || (rc < want && fops->eof(f->lbx->f)))
+ f->eof = 1;
+ return rc;
+}
+
+int lbx_file_seek(struct lbx_file_state *f, long offset, int whence)
+{
+ const struct lbx_file_ops *fops = f->lbx->fops;
+ unsigned long pos;
+
+ switch (whence) {
+ case SEEK_CUR:
+ pos = f->offset + offset;
+ break;
+ case SEEK_SET:
+ pos = offset;
+ break;
+ case SEEK_END:
+ pos = f->limit + offset;
+ break;
+ }
+
+ if (pos > f->limit)
+ return -1;
+
+ f->lbx->last_file = NULL;
+ if (fops->seek(f->lbx->f, f->base + pos, SEEK_SET) != 0)
+ return -1;
+
+ f->offset = pos;
+ f->lbx->last_file = f;
+ f->eof = 0;
+
+ return 0;
+}
+
+long lbx_file_tell(struct lbx_file_state *f)
+{
+ return f->offset;
+}
+
+int lbx_file_eof(struct lbx_file_state *f)
+{
+ return f->eof;
+}
+
+void lbx_file_close(struct lbx_file_state *f)
+{
+ if (f->lbx->last_file == f)
+ f->lbx->last_file = NULL;
+ free(f);