2 * Sherlock Library -- Mapping of File Parts
4 * (c) 2003 Martin Mares <mj@ucw.cz>
5 * (c) 2003 Robert Spalek <robert@ucw.cz>
7 * This software may be freely distributed and used according to the terms
8 * of the GNU Lesser General Public License.
25 sh_off_t start_off, end_off;
31 #define PARTMAP_WINDOW 4096
33 #define PARTMAP_WINDOW 16777216
37 partmap_open(byte *name, int writeable)
39 struct partmap *p = xmalloc_zero(sizeof(struct partmap));
41 p->fd = sh_open(name, writeable ? O_RDWR : O_RDONLY);
43 die("open(%s): %m", name);
44 if ((p->file_size = sh_seek(p->fd, 0, SEEK_END)) < 0)
45 die("lseek(%s): %m", name);
46 p->writeable = writeable;
51 partmap_size(struct partmap *p)
57 partmap_close(struct partmap *p)
60 munmap(p->start_map, p->end_off - p->start_off);
66 partmap_map(struct partmap *p, sh_off_t start, uns size)
68 if (!p->start_map || start < p->start_off || start+size > p->end_off)
71 munmap(p->start_map, p->end_off - p->start_off);
72 uns win = PARTMAP_WINDOW;
74 sh_off_t end = start + size;
75 start = start/PAGE_SIZE * PAGE_SIZE;
76 if (start+win > p->file_size)
77 win = p->file_size - start;
79 die("cannot mmap, the window is too small");
80 p->start_map = sh_mmap(NULL, win, p->writeable ? (PROT_READ | PROT_WRITE) : PROT_READ, MAP_SHARED, p->fd, start);
81 if (p->start_map == MAP_FAILED)
82 die("mmap failed at position %Ld: %m", (long long)start);
84 p->end_off = start+win;
86 return p->start_map + (start - p->start_off);
90 int main(int argc, char **argv)
92 struct partmap *p = partmap_open(argv[1], 0);
93 uns l = partmap_size(p);
96 putchar(*(char *)partmap_map(p, i, 1));