2 * Sherlock Library -- Mapping of File Parts
4 * (c) 2003 Martin Mares <mj@ucw.cz>
6 * This software may be freely distributed and used according to the terms
7 * of the GNU Lesser General Public License.
23 sh_off_t start_off, end_off;
29 #define PARTMAP_WINDOW 4096
31 #define PARTMAP_WINDOW 16777216
35 partmap_open(byte *name, int writeable)
37 struct partmap *p = xmalloc_zero(sizeof(struct partmap));
39 p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
41 die("open(%s): %m", name);
42 if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
43 die("lseek(%s): %m", name);
44 p->writeable = writeable;
49 partmap_size(struct partmap *p)
55 partmap_close(struct partmap *p)
58 munmap(p->start_map, p->end_off - p->start_off);
64 partmap_map(struct partmap *p, sh_off_t start, uns size)
66 if (!p->start_map || start < p->start_off || start+size > p->end_off)
69 munmap(p->start_map, p->end_off - p->start_off);
70 uns win = PARTMAP_WINDOW;
72 if (start+win > p->file_size)
73 win = p->file_size - start;
74 p->start_map = sh_mmap(NULL, win, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, start);
75 if (p->start_map == MAP_FAILED)
76 die("mmap failed at position %Ld: %m", (long long)start);
78 p->end_off = start+win;
80 return p->start_map + (start - p->start_off);
84 int main(int argc, char **argv)
86 struct partmap *p = partmap_open(argv[1], 0);
87 uns l = partmap_size(p);
90 putchar(*(char *)partmap_map(p, i, 1));