#include <errno.h>
#include <assert.h>
+#include <sys/stat.h>
+#include <sys/mman.h>
+
#include "byteorder.h"
#include "lbx.h"
return _lbx_fextract(lbx, base, len, of);
}
+void *lbx_mmap(struct lbx_state *lbx, size_t index, size_t *len)
+{
+ unsigned char *mapping;
+ struct stat statbuf;
+ size_t base;
+
+ if (index >= lbx->nfiles) {
+ lbx_errno = LBX_ERANGE;
+ return NULL;
+ }
+
+ base = lbx->offsets[index];
+ *len = lbx->offsets[index+1] - lbx->offsets[index];
+
+ if (lbx->mem)
+ return lbx->mem + base;
+
+ if (fstat(fileno(lbx->f), &statbuf) == -1) {
+ lbx_errno = -errno;
+ return NULL;
+ }
+
+ mapping = mmap(NULL, statbuf.st_size, PROT_READ, 0, fileno(lbx->f), 0);
+ if (mapping == MAP_FAILED) {
+ lbx_errno = -errno;
+ return NULL;
+ }
+
+ lbx->mem = mapping;
+ lbx->memsize = statbuf.st_size;
+ return mapping + base;
+}
+
void lbx_close(struct lbx_state *lbx)
{
if (!lbx) return;
- if (lbx->f)
+ if (lbx->f) {
fclose(lbx->f);
+ if (lbx->mem) {
+ munmap(lbx->mem, lbx->memsize);
+ }
+ }
+
free(lbx);
}
/* File operations */
int lbx_stat(LBX *, size_t, struct lbx_statbuf *);
size_t lbx_extract(LBX *, size_t, FILE *);
+void *lbx_mmap(LBX *, size_t, size_t *);
/* Misc operations */
const char *lbx_strerror(void);