+/**
+ * Overlay
+ */
+static struct {
+ struct Source source;
+ struct Region *table;
+ size_t count;
+ size_t limit;
+} overlay;
+
+#define FRAG(m) (overlay.table+m)
+#define BEG(m) (FRAG(m)->pos)
+#define END(m) (FRAG(m)->pos + FRAG(m)->size)
+
+static ssize_t overlay_prior_fragment(off_t pos) {
+ size_t lo = 0, hi = overlay.count;
+ while ( lo < hi ) {
+ size_t m = ( lo + hi ) / 2;
+ if ( m == lo ) {
+ return BEG( m ) < pos? m : -1;
+ }
+ if ( BEG( m ) <= pos ) {
+ lo = m;
+ } else {
+ hi = m;
+ }
+ }
+ return -1;
+}
+
+static void overlay_save_count() {
+ lseek( overlay.source.fd, overlay.source.to, SEEK_SET );
+ size_t size = sizeof( overlay.count );
+ char *p = (char *) &overlay.count ;
+ while ( size > 0 ) {
+ size_t n = write( overlay.source.fd, p, size );
+ if ( n < 0 ) {
+ perror( overlay.source.filename );
+ exit( 1 );
+ }
+ size -= n;
+ p += n;
+ }
+}
+
+static void overlay_save_table(size_t lo,size_t hi) {
+ char *p = (char *) FRAG(lo);
+ size_t pos = overlay.source.to + sizeof( overlay.count ) +
+ lo * sizeof( struct Region );
+ size_t size = ( hi - lo ) * sizeof( struct Region );
+ if ( pos != lseek( overlay.source.fd, pos, SEEK_SET ) ) {
+ fprintf( stderr, "%s: seek error\n", overlay.source.filename );
+ exit( 1 );
+ }
+ while ( size > 0 ) {
+ size_t n = write( overlay.source.fd, p, size );
+ if ( n < 0 ) {
+ perror( overlay.source.filename );
+ exit( 1 );
+ }
+ size -= n;
+ p += n;
+ }
+}
+
+static void overlay_insert(size_t p,off_t pos,size_t size) {
+ size_t bytes;
+ if ( overlay.count >= overlay.limit ) {
+ overlay.limit = overlay.count + 10;
+ bytes = overlay.limit * sizeof( struct Region );
+ overlay.table = overlay.table?
+ realloc( overlay.table, bytes ) : malloc( bytes );
+ }
+ bytes = ( overlay.count++ - p ) * sizeof( struct Region );
+ if ( bytes ) {
+ memmove( FRAG( p+1 ), FRAG( p ), bytes );
+ }
+ FRAG( p )->pos = pos;
+ FRAG( p )->size = size;
+ overlay_save_count();
+}
+
+static void overlay_delete(size_t p) {
+ if ( p < --overlay.count ) {
+ size_t size = ( overlay.count - p ) * sizeof( struct Region );
+ memmove( FRAG(p), FRAG(p+1), size );
+ }
+ overlay_save_count();
+}
+
+static void overlay_mark(off_t pos,size_t size) {
+ ssize_t p = overlay_prior_fragment( pos );
+ if ( p >= 0 && pos <= END(p) ) {
+ // Merge new marks with fragment p
+ FRAG(p)->size = pos + size - BEG(p);
+ if ( p+1 < overlay.count && BEG(p+1) <= END(p) ) {
+ FRAG(p)->size = END(p+1) - BEG(p);
+ overlay_delete( p+1 );
+ overlay_save_table( p, overlay.count );
+ } else {
+ overlay_save_table( p, p+1 );
+ }
+ return;
+ }
+ p++; // index of subsequent fragment
+ if ( p < overlay.count && BEG(p) < pos + size ) {
+ // Merge new marks with pragment p+1
+ FRAG(p)->size = END(p) - pos;
+ FRAG(p)->pos = pos;
+ overlay_save_table( p, p+1 );
+ } else {
+ overlay_insert( p, pos, size);
+ overlay_save_table( p, overlay.count );
+ }
+}