merged closer to working, still fails on filling a separate, large block
[idzebra-moved-to-github.git] / isamc / merge-d.c
1 /*
2  * Copyright (c) 1996-1998, Index Data.
3  * See the file LICENSE for details.
4  * Heikki Levanto
5  *
6  * $Id: merge-d.c,v 1.5 1999-07-23 13:58:52 heikki Exp $
7  *
8  * todo
9  *  - merge when needed
10  *  - single-entry optimizing
11  *  - study and optimize block sizes (later)
12  *
13  * bugs
14  *  not yet ready
15  *
16  * caveat
17  *  There is aconfusion about the block addresses. cat or type is the category,
18  *  pos or block is the block number. pp structures keep these two separate,
19  *  and combine when saving the pp. The next pointer in the pp structure is
20  *  also a combined address, but needs to be combined every time it is needed,
21  *  and separated when the partss are needed... This is done with the isamd_
22  *  _block, _type, and _addr macros. The _addr takes block and type as args,
23  *  in that order. This conflicts with the order these are often mentioned in 
24  *  the debug log calls, and other places, leading to small mistakes here
25  *  and there. 
26  */
27
28 #include <stdlib.h>
29 #include <assert.h>
30 #include <string.h>
31 #include <stdio.h>
32 #include <log.h>
33 #include "../index/index.h"
34 #include "isamd-p.h"
35
36
37 struct ISAMD_DIFF_s {
38   int diffidx;
39   int maxidx;
40   struct it_key key;
41   void *decodeData;
42   int mode;
43 };
44
45
46
47 static char *hexdump(unsigned char *p, int len, char *buff) {
48   static char localbuff[128];
49   char bytebuff[8];
50   if (!buff) buff=localbuff;
51   *buff='\0';
52   while (len--) {
53     sprintf(bytebuff,"%02x",*p);
54     p++;
55     strcat(buff,bytebuff);
56     if (len) strcat(buff,",");
57   }
58   return buff;
59 }
60
61
62 static int separateDiffBlock(ISAMD_PP pp)
63 {
64   if (pp->next) 
65      return 1;  /* multi-block chains always have a separate diff block */
66   return ( pp->size + 2*sizeof(int) > pp->is->method->filecat[pp->cat].bsize);
67   /* make sure there is at least room for the length and one diff. if not, */
68   /* it goes to a separate block */
69   
70   /* todo: Make the limit adjustable in the filecat table ! */
71 }
72
73
74 /**************************************************************
75  * Reading 
76  **************************************************************/
77
78 static void getDiffInfo(ISAMD_PP pp, int diffidx)
79 { /* builds the diff info structures from a diffblock */
80    int maxinfos = pp->is->method->filecat[pp->cat].bsize / 5 +1;
81     /* Each diff takes at least 5 bytes. Probably more, but this is safe */
82    int i=1;  /* [0] is used for the main data */
83    int diffsz= maxinfos * sizeof(struct ISAMD_DIFF_s);
84
85    pp->diffinfo = xmalloc( diffsz );
86    memset(pp->diffinfo,'\0',diffsz);
87    if (pp->is->method->debug > 4)
88      logf(LOG_LOG,"isamd_getDiffInfo: %d (%d:%d), ix=%d mx=%d",
89          isamd_addr(pp->pos, pp->cat), pp->cat, pp->pos, diffidx,maxinfos);
90    assert(pp->diffbuf);
91
92    while (i<maxinfos) 
93    {  
94       if ( diffidx+sizeof(int) > pp->is->method->filecat[pp->cat].bsize )
95       {
96          if (pp->is->method->debug > 4)
97            logf(LOG_LOG,"isamd_getDiffInfo:Near end (no room for len) at ix=%d n=%d",
98                diffidx, i);
99          return; /* whole block done */
100       }
101       memcpy( &pp->diffinfo[i].maxidx, &pp->diffbuf[diffidx], sizeof(int) );
102
103       if (pp->is->method->debug > 4)
104         logf(LOG_LOG,"isamd_getDiffInfo: max=%d ix=%d dbuf=%p",
105           pp->diffinfo[i].maxidx, diffidx, pp->diffbuf);
106
107       if (0==pp->diffinfo[i].maxidx)
108       {
109          if (pp->is->method->debug > 4)
110            logf(LOG_LOG,"isamd_getDiffInfo:End mark at ix=%d n=%d",
111                diffidx, i);
112          return; /* end marker */
113       }
114       diffidx += sizeof(int);
115       pp->diffinfo[i].decodeData = (*pp->is->method->code_start)(ISAMD_DECODE);
116       pp->diffinfo[i].diffidx = diffidx;
117       if (pp->is->method->debug > 4)
118         logf(LOG_LOG,"isamd_getDiff[%d]:%d-%d %s",
119           i,diffidx-sizeof(int),pp->diffinfo[i].maxidx,
120           hexdump((char *)&pp->diffbuf[diffidx-4],8,0) );
121       diffidx=pp->diffinfo[i].maxidx;
122       if ( diffidx > pp->is->method->filecat[pp->cat].bsize )
123         return; /* whole block done */
124       ++i;
125    }
126    assert (!"too many diff sequences in the block");
127 }
128
129 static void loadDiffs(ISAMD_PP pp)
130 {  /* assumes pp is a firstblock! */
131    int diffidx;
132    int diffaddr;
133    if (0==pp->diffs)
134      return; /* no diffs to talk about */
135    if (pp->diffs & 1 )
136    { /* separate diff block, load it */
137       pp->diffbuf= xmalloc( pp->is->method->filecat[pp->cat].bsize);
138       diffaddr=isamd_addr(pp->diffs/2, pp->cat);
139       isamd_read_block (pp->is, isamd_type(diffaddr), 
140                                 isamd_block(diffaddr), pp->diffbuf );
141       diffidx= ISAMD_BLOCK_OFFSET_N; 
142       if (pp->is->method->debug > 4)
143         logf(LOG_LOG,"isamd_LoadDiffs: loaded block %d=%d:%d, d=%d ix=%d",
144           diffaddr, isamd_type(diffaddr),isamd_block(diffaddr), 
145           pp->diffs,diffidx);
146    }
147    else
148    { /* integrated block, just set the pointers */
149      pp->diffbuf = pp->buf;
150      diffidx = pp->size;  /* size is the beginning of diffs, diffidx the end*/
151       if (pp->is->method->debug > 4)
152         logf(LOG_LOG,"isamd_LoadDiffs: within %d=%d:%d, d=%d ix=%d ",
153           isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos, pp->diffs, diffidx);
154    }
155    getDiffInfo(pp,diffidx);
156 } /* loadDiffs */
157
158
159 void isamd_free_diffs(ISAMD_PP pp)
160 {
161   int i;
162   if (!pp->diffinfo) 
163     return;
164   for (i=0;pp->diffinfo[i].decodeData;i++) 
165       (*pp->is->method->code_stop)(ISAMD_DECODE,pp->diffinfo[i].decodeData);    
166   xfree(pp->diffinfo);
167   if (pp->diffbuf != pp->buf)
168     xfree (pp->diffbuf);  
169 } /* isamd_free_diffs */
170
171
172 /* Reads one item and corrects for the diffs, if any */
173 /* return 1 for ok, 0 for eof */
174 int isamd_read_item (ISAMD_PP pp, char **dst)
175 {
176   char *keyptr;
177   char *codeptr;
178   char *codestart;
179   int winner=0; /* which diff holds the day */
180   int i; /* looping diffs */
181   int cmp;
182   int retry=1;
183   if (pp->diffs==0)  /* no diffs, just read the thing */
184      return isamd_read_main_item(pp,dst);
185
186   if (!pp->diffinfo)
187     loadDiffs(pp);
188   while (retry)
189   {
190      retry=0;
191      if (0==pp->diffinfo[0].key.sysno) 
192      { /* 0 is special case, main data. */
193         keyptr=(char*) &(pp->diffinfo[0].key);
194         pp->diffinfo[0].mode = ! isamd_read_main_item(pp,&keyptr);
195         if (pp->is->method->debug > 4)
196           logf(LOG_LOG,"isamd_read_item: read main %d.%d (%x.%x)",
197             pp->diffinfo[0].key.sysno, pp->diffinfo[0].key.seqno,
198             pp->diffinfo[0].key.sysno, pp->diffinfo[0].key.seqno);
199      } /* get main data */
200      winner = 0;
201      for (i=1; (!retry) && (pp->diffinfo[i].decodeData); i++)
202      {
203         if (pp->is->method->debug > 4)
204           logf(LOG_LOG,"isamd_read_item: considering d%d %d.%d ix=%d mx=%d",
205                i, pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
206                   pp->diffinfo[i].diffidx,   pp->diffinfo[i].maxidx);
207             
208         if ( (0==pp->diffinfo[i].key.sysno) &&
209              (pp->diffinfo[i].diffidx < pp->diffinfo[i].maxidx))
210         {/* read a new one, if possible */
211            codeptr= codestart = &(pp->diffbuf[pp->diffinfo[i].diffidx]);
212            keyptr=(char *)&(pp->diffinfo[i].key);
213            (*pp->is->method->code_item)(ISAMD_DECODE,
214                  pp->diffinfo[i].decodeData, &keyptr, &codeptr);
215            pp->diffinfo[i].diffidx += codeptr-codestart;
216            pp->diffinfo[i].mode = pp->diffinfo[i].key.seqno & 1;
217            pp->diffinfo[i].key.seqno = pp->diffinfo[i].key.seqno >>1 ;
218            if (pp->is->method->debug > 4)
219              logf(LOG_LOG,"isamd_read_item: read diff[%d] %d.%d (%x.%x)",i,
220                pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
221                pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
222         } 
223         if ( 0!= pp->diffinfo[i].key.sysno)
224         { /* got a key, compare */
225           cmp=key_compare(&pp->diffinfo[i].key, &pp->diffinfo[winner].key);
226           if (0==pp->diffinfo[winner].key.sysno)
227             cmp=-1; /* end of main sequence, take all diffs */
228           if (cmp<0)
229           {
230              if (pp->is->method->debug > 4)
231                logf(LOG_LOG,"isamd_read_item: ins %d<%d %d.%d (%x.%x) < %d.%d (%x.%x)",
232                  i, winner,
233                  pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
234                  pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
235                  pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
236                  pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
237              if (pp->diffinfo[i].mode)  /* insert diff, should always be */
238                winner = i;
239              else
240                assert(!"delete diff for nonexisting item");  
241                /* is an assert too steep here?*/
242           } /* earlier key */
243           else if (cmp==0)
244           {
245              if (!pp->diffinfo[i].mode) /* delete diff. should always be */
246              {
247                 if (pp->is->method->debug > 4)
248                   logf(LOG_LOG,"isamd_read_item: del %d at%d %d.%d (%x.%x)",
249                     i, winner,
250                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
251                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
252                 pp->diffinfo[winner].key.sysno=0; /* delete it */
253              }
254              else
255                 if (pp->is->method->debug > 4)
256                   logf(LOG_LOG,"isamd_read_item: duplicate ins %d at%d %d.%d (%x.%x)",
257                     i, winner,
258                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno,
259                     pp->diffinfo[i].key.sysno, pp->diffinfo[i].key.seqno);
260                 /* skip the insert, since we already have it in the base */
261              pp->diffinfo[i].key.sysno=0; /* done with the delete */
262              retry=1; /* start all over again */
263           } /* matching key */
264           /* else it is a later key, its turn will come */
265         } /* got a key */
266      } /* for each diff */
267   } /* not retry */
268
269   if ( pp->diffinfo[winner].key.sysno)
270   {
271     if (pp->is->method->debug > 4)
272       logf(LOG_LOG,"isamd_read_item: got %d  %d.%d (%x.%x)",
273         winner,
274         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
275         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
276     memcpy(*dst, &pp->diffinfo[winner].key, sizeof(struct it_key) );
277     *dst += sizeof(struct it_key);
278     pp->diffinfo[winner].key.sysno=0; /* used that one up */
279     cmp= 1;
280   } 
281   else 
282   {
283     if (pp->is->method->debug > 4)
284       logf(LOG_LOG,"isamd_read_item: eof w=%d  %d.%d (%x.%x)",
285         winner,
286         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno,
287         pp->diffinfo[winner].key.sysno, pp->diffinfo[winner].key.seqno);
288     assert(winner==0); /* if nothing found, nothing comes from a diff */
289     cmp= 0; /* eof */
290   }
291   return cmp;
292    
293 } /* isamd_read_item */
294
295 /*****************************************************************
296  * Support routines 
297  *****************************************************************/
298
299 static void isamd_reduceblock(ISAMD_PP pp)
300 /* takes a large block, and reduces its category if possible */
301 /* Presumably the first block in an isam-list */
302 {
303    if (pp->pos)
304       return; /* existing block, do not touch */
305    if (pp->is->method->debug > 2)
306      logf(LOG_LOG,"isamd_reduce: start p=%d c=%d sz=%d",
307        pp->pos, pp->cat, pp->size); 
308    while ( ( pp->cat > 0 ) && (!pp->next) && 
309            (pp->offset < pp->is->method->filecat[pp->cat-1].bsize ) )
310       pp->cat--;
311    pp->pos = isamd_alloc_block(pp->is, pp->cat);
312    if (pp->is->method->debug > 2)
313      logf(LOG_LOG,"isamd_reduce:  got  p=%d c=%d sz=%d",
314        pp->pos, pp->cat, pp->size);    
315 } /* reduceblock */
316
317
318
319  
320 static int save_first_pp ( ISAMD_PP firstpp)
321 {
322    isamd_reduceblock(firstpp);
323    isamd_buildfirstblock(firstpp);
324    isamd_write_block(firstpp->is,firstpp->cat,firstpp->pos,firstpp->buf);
325    return isamd_addr(firstpp->pos,firstpp->cat);
326 }
327
328 static void save_last_pp (ISAMD_PP pp)
329 {
330    pp->next = 0;/* just to be sure */
331    isamd_buildlaterblock(pp);
332    isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
333 }
334
335
336 static int save_both_pps (ISAMD_PP firstpp, ISAMD_PP pp)
337 {
338    /* order of things: Better to save firstpp first, if there are just two */
339    /* blocks, but last if there are blocks in between, as these have already */
340    /* been saved... optimise later (that's why this is in its own func...*/
341    int retval = save_first_pp(firstpp);
342    if (firstpp!=pp){ 
343       save_last_pp(pp);
344       isamd_pp_close(pp);
345    }
346    isamd_pp_close(firstpp);
347    return retval;
348 } /* save_both_pps */
349
350 static ISAMD_PP read_diff_block(ISAMD_PP firstpp, int* p_diffidx)
351 { /* reads the diff block (if separate) and sets diffidx right */
352    ISAMD_PP pp=firstpp;
353    int diffidx;   
354    if (pp->diffs == 0)
355    { /* no diffs yet, create room for them */
356       if (separateDiffBlock(firstpp))
357       { /* create a new block */
358          pp=isamd_pp_open(pp->is,isamd_addr(0,firstpp->cat));
359          pp->pos = isamd_alloc_block(pp->is, pp->cat);
360          firstpp->diffs = pp->pos*2 +1;
361          diffidx = pp->size = pp->offset = ISAMD_BLOCK_OFFSET_N;
362          if (pp->is->method->debug >3) 
363              logf(LOG_LOG,"isamd_appd: alloc diff  (d=%d) %d=%d:%d ix=%d",
364                    firstpp->diffs,
365                    isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos, 
366                    diffidx);
367       }
368       else
369       { /* prepare to append diffs in head */
370         diffidx = pp->size;
371         pp->diffs = diffidx *2 +0;  
372          if (pp->is->method->debug >3) 
373              logf(LOG_LOG,"isamd_appd: set up diffhead  (d=%d) %d=%d:%d ix=%d",
374                    firstpp->diffs,
375                    isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos, 
376                    diffidx);
377       }
378    } /* new */
379    else
380    { /* existing diffs */
381       if (pp->diffs & 1)
382       { /* diffs in a separate block, load it */
383         pp=isamd_pp_open(pp->is, isamd_addr(firstpp->diffs/2,pp->cat));
384         diffidx = pp->offset= pp->size;
385         if (pp->is->method->debug >3) 
386            logf(LOG_LOG,"isamd_appd: loaded diff (d=%d) %d=%d:%d ix=%d",
387                  firstpp->diffs,
388                  isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos, 
389                  diffidx);
390       }
391       else
392       { /* diffs within the nead */
393          diffidx= pp->diffs/2;
394          if (pp->is->method->debug >3) 
395             logf(LOG_LOG,"isamd_appd: diffs in head d=%d %d=%d:%d ix=%d sz=%d",
396                      pp->diffs,
397                      isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos, 
398                      diffidx, pp->size);
399       }
400    } /* diffs exist already */
401    *p_diffidx = diffidx;
402    return pp;
403 } /* read_diff_block */
404
405
406
407
408 /*******************************************************************
409  * Building main blocks (no diffs)
410  *******************************************************************/
411
412
413
414 static ISAMD_PP get_new_main_block( ISAMD_PP firstpp, ISAMD_PP pp)
415 {  /* allocates a new block for the main data, and links it in */
416    int newblock;
417    if (firstpp==pp) 
418    { /* special case: it was the first block. Save much later */
419       if (0==firstpp->pos)
420       { /* firstpp not allocated yet, do so now, */
421         /* to keep blocks in order. Don't save yet, though */
422          firstpp->pos = isamd_alloc_block(pp->is, firstpp->cat);
423       }
424       newblock = isamd_alloc_block(pp->is, firstpp->cat);
425       firstpp->next = isamd_addr(newblock,firstpp->cat);
426         /* keep the largest category */
427       pp=isamd_pp_open(pp->is,isamd_addr(0,firstpp->cat));/*don't load*/
428       pp->pos=newblock; 
429       pp->size = pp->offset = ISAMD_BLOCK_OFFSET_N; 
430       pp->next=0;
431       if (pp->is->method->debug >3)
432          logf(LOG_LOG,"isamd_build: Alloc2 f=%d (%d:%d) n=%d(%d:%d)",
433             isamd_addr(firstpp->pos,firstpp->cat), 
434             firstpp->cat, firstpp->pos,
435             isamd_addr(pp->pos,pp->cat), pp->cat, pp->pos );
436    }
437    else
438    { /* it was not the first block */
439       newblock = isamd_alloc_block(pp->is, firstpp->cat);
440       pp->next = isamd_addr(newblock,firstpp->cat);
441       isamd_buildlaterblock(pp);
442       isamd_write_block(pp->is,pp->cat,pp->pos,pp->buf);
443       pp->size = pp->offset = ISAMD_BLOCK_OFFSET_N;
444       pp->next=0;
445       pp->cat = firstpp->cat;
446       pp->pos = isamd_block(firstpp->next);
447    }
448   return pp;
449 } /* get_new_main_block */
450
451
452 static ISAMD_PP  append_main_item(ISAMD_PP firstpp, 
453                                   ISAMD_PP pp, 
454                                   struct it_key *i_key,
455                                   void *encoder_data)
456 {  /* appends one item in the main data block, allocates new if needed */
457    char *i_item= (char *) i_key;  /* same as char */
458    char *i_ptr=i_item;
459    char codebuff[128];
460    char *c_ptr = codebuff;
461    int codelen;
462    char hexbuff[64];
463
464    int maxsize = pp->is->method->filecat[pp->is->max_cat].bsize; 
465
466    c_ptr=codebuff;
467    i_ptr=i_item;
468    (*pp->is->method->code_item)(ISAMD_ENCODE, encoder_data, &c_ptr, &i_ptr);
469    codelen = c_ptr - codebuff;
470    assert ( (codelen<128) && (codelen>0));
471    if (pp->is->method->debug >3)
472       logf(LOG_LOG,"isamd:build: coded into %s  (nk=%d)",
473           hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1);
474
475    if (pp->offset + codelen > maxsize )
476    { /* oops, block full - get a new one */
477       pp =  get_new_main_block( firstpp, pp );
478       /* reset encoging and code again */
479       (*pp->is->method->code_reset)(encoder_data);
480       c_ptr=codebuff;
481       i_ptr=i_item;
482       (*pp->is->method->code_item)(ISAMD_ENCODE, encoder_data, &c_ptr, &i_ptr);
483       codelen = c_ptr - codebuff;
484       assert ( (codelen<128) && (codelen>0));
485       if (pp->is->method->debug >3)
486          logf(LOG_LOG,"isamd:build: recoded into %s  (nk=%d)",
487              hexdump(codebuff, c_ptr-codebuff,hexbuff), firstpp->numKeys+1);
488    } /* block full */    
489    
490    /* write the data into pp, now we must have room */ 
491    memcpy(&(pp->buf[pp->offset]),codebuff,codelen);
492    pp->offset += codelen;
493    pp->size += codelen;
494    firstpp->numKeys++;
495    return pp;    
496 } /* append_main_item */
497
498
499 static int isamd_build_first_block(ISAMD is, ISAMD_I data) 
500 {
501    struct it_key i_key;  /* input key */
502    char *i_item= (char *) &i_key;  /* same as char */
503    char *i_ptr=i_item;
504    int i_more =1;
505    int i_mode;     /* 0 for delete, 1 for insert */ 
506
507    ISAMD_PP firstpp;
508    ISAMD_PP pp;
509    void *encoder_data;
510    
511    char hexbuff[64];
512    
513    firstpp=pp=isamd_pp_open(is, isamd_addr(0,is->max_cat));
514    firstpp->size = firstpp->offset = ISAMD_BLOCK_OFFSET_1;
515    encoder_data=(*is->method->code_start)(ISAMD_ENCODE);
516    
517    if (is->method->debug >3)
518       logf(LOG_LOG,"isamd_bld start: p=%d c=%d sz=%d maxsz=%d ",
519          pp->pos, pp->cat, pp->size, 
520          pp->is->method->filecat[pp->is->max_cat].bsize); 
521
522    /* read first input */
523    i_ptr = i_item;
524    i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); 
525    if (i_more)
526      assert( i_ptr-i_item == sizeof(i_key) );
527
528    if (pp->is->method->debug >3)
529       logf(LOG_LOG,"isamd: build_fi start: m=%d %s",
530          i_mode, hexdump(i_item,i_ptr-i_item,hexbuff) );
531
532    while (i_more)
533    { 
534       if (i_mode!=0) 
535       { /* ignore deletes here, should not happen */
536          pp= append_main_item(firstpp, pp, &i_key, encoder_data);      
537       } /* not delete */
538       
539       /* (try to) read the next item */
540       i_ptr = i_item;
541       i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); 
542       
543       if ( (i_more) && (pp->is->method->debug >3) )
544          logf(LOG_LOG,"isamd: build_fi start: m=%d %s",
545             i_mode, hexdump(i_item,i_ptr-i_item,hexbuff) );
546       
547    } /* i_more */
548
549    return save_both_pps( firstpp, pp );
550
551 } /* build_first_block */
552
553
554 /***************************************************************
555  * Merging diffs 
556  ***************************************************************/
557
558  
559 static int merge ( ISAMD_PP *p_firstpp,   /* first pp of the chain */
560                    ISAMD_PP *p_pp,        /* diff block */
561                    struct it_key *p_key )
562 {
563   ISAMD_PP readpp = *p_firstpp;
564   int diffidx;  
565   int killblk=0;
566   struct it_key r_key;
567   char * r_ptr;
568   int r_more = 1;
569   ISAMD_PP firstpp;  /* the new first, the one we write into */
570   ISAMD_PP pp;
571   void *encoder_data;
572      
573   /* set up diffs as they should be for reading */
574   readpp->offset= ISAMD_BLOCK_OFFSET_1; 
575   
576   if (*p_pp == *p_firstpp)
577   { /* integrated diffs */
578      diffidx=readpp->size;
579      readpp->diffs = diffidx*2+0;
580      readpp->diffbuf=readpp->buf;  /*? does this get freed right ???  */
581      if (readpp->is->method->debug >3) 
582          logf(LOG_LOG,"isamd_merge:local diffs at %d", diffidx);
583   }
584   else
585   { /* separate diff block in *p_pp */
586      killblk = readpp->diffs/2;
587      diffidx = readpp->is->method->filecat[readpp->cat].bsize;
588      readpp->diffbuf= xmalloc( diffidx); /* copy diffs to where read wants*/
589      memcpy( &readpp->diffbuf, &((*p_pp)->buf[0]), diffidx);
590      diffidx = ISAMD_BLOCK_OFFSET_N;
591      if (readpp->is->method->debug >3) 
592          logf(LOG_LOG,"isamd_merge:separate diffs at ix=%d", 
593                  diffidx);
594      if (readpp->is->method->debug >3) 
595          logf(LOG_LOG,"isamd_merge: dbuf=%p (from %p) pp=%p", 
596                   readpp->diffbuf, &((*p_pp)->buf[0]), (*p_pp) );
597   }
598   getDiffInfo(readpp,diffidx);
599
600   r_ptr= (char *) &r_key;
601   r_more = isamd_read_item( readpp, &r_ptr);
602   if (!r_more)  
603   { /* oops, all data has been deleted! what to do??? */
604     /* never mind, we have at least one more delta to add to the block */
605     /* pray that is not a delete as well... */
606     r_key.sysno = 0;
607     r_key.seqno = 0;
608      if (readpp->is->method->debug >3) 
609          logf(LOG_LOG,"isamd_merge:all data has been deleted (nk=%d) ",
610             readpp->numKeys);
611     assert (readpp->numKeys == 0);
612   }
613
614   if (killblk) 
615   {
616      isamd_release_block(readpp->is, isamd_type(killblk), isamd_block(killblk));
617      /* we have the data, let the block go */
618      if (readpp->is->method->debug >3) 
619          logf(LOG_LOG,"isamd_merge: released diff block %d (%d:%d)",
620               killblk, isamd_type(killblk), isamd_block(killblk) );
621   }
622   killblk=isamd_addr(readpp->pos, readpp->cat);
623   isamd_release_block(readpp->is, isamd_type(killblk), isamd_block(killblk));
624   if (readpp->is->method->debug >3) 
625       logf(LOG_LOG,"isamd_merge: released old firstblock %d (%d:%d)",
626             killblk, isamd_type(killblk), isamd_block(killblk) );
627    
628   /* set up the new blocks for simple writing */
629   firstpp=pp=isamd_pp_open(readpp->is,isamd_addr(0, readpp->is->max_cat));
630   firstpp->size = firstpp->offset = ISAMD_BLOCK_OFFSET_1;
631   encoder_data = (*pp->is->method->code_start)(ISAMD_ENCODE);
632   
633   while (r_more)
634   {
635      if (readpp->is->method->debug >4) 
636          logf(LOG_LOG,"isamd_merge: got key %d.%d",
637            r_key.sysno, r_key.seqno );
638      pp= append_main_item(firstpp, pp, &r_key, encoder_data);
639
640      if ( isamd_addr(readpp->pos, readpp->cat) != killblk )
641      {
642         isamd_release_block(readpp->is, readpp->cat, readpp->pos);
643         if (readpp->is->method->debug >3) 
644             logf(LOG_LOG,"isamd_merge: released data block %d (%d:%d)",
645                   killblk, isamd_type(killblk), isamd_block(killblk) );
646         killblk=isamd_addr(readpp->pos, readpp->cat);
647      }
648
649      /* (try to) read next item */
650      r_ptr= (char *) &r_key;
651      r_more = isamd_read_item( readpp, &r_ptr);
652
653   } /* while read */
654   
655   /* TODO: while pkey is an insert, and after last key inserted, append it */
656   /* will prevent multiple merges on large insert runs */  
657
658   /* set things up so that merge can continue */
659   isamd_reduceblock(firstpp);
660
661   if (firstpp!=pp) 
662   { /* the last data block is of no interest any more */
663     save_last_pp(pp);
664     isamd_pp_close(pp);
665   }
666   
667   *p_firstpp = firstpp; 
668     
669   return 0; 
670   
671 } /* merge */
672
673
674
675 /***************************************************************
676  * Appending diffs 
677  ***************************************************************/
678
679
680
681 static int append_diffs(ISAMD is, ISAMD_P ipos, ISAMD_I data)
682 {
683    struct it_key i_key;    /* one input item */
684    char *i_item = (char *) &i_key;  /* same as chars */
685    char *i_ptr=i_item;
686    int i_more =1;
687    int i_mode;     /* 0 for delete, 1 for insert */ 
688
689    ISAMD_PP firstpp;
690    ISAMD_PP pp;
691    void *encoder_data;
692    char hexbuff[64];
693    int diffidx=0;
694    int maxsize=0;
695    int difflenidx;
696    char codebuff[128];
697    char *c_ptr = codebuff;
698    int codelen;
699    int merge_rc;
700
701    firstpp=isamd_pp_open(is, ipos);
702    if (is->method->debug >4)
703       logf(LOG_LOG,"isamd_appd: Start ipos=%d=%d:%d d=%d=%d*2+%d",
704         ipos, isamd_type(ipos), isamd_block(ipos),
705         firstpp->diffs, firstpp->diffs/2, firstpp->diffs & 1);
706    pp=read_diff_block(firstpp, &diffidx);
707    encoder_data=(*is->method->code_start)(ISAMD_ENCODE);
708    maxsize = is->method->filecat[pp->cat].bsize; 
709    
710    difflenidx = diffidx;
711    diffidx+=sizeof(int);  /* difflen will be stored here */
712    
713    /* read first input */
714    i_ptr = i_item;
715    i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); 
716
717    if (is->method->debug >3)
718       logf(LOG_LOG,"isamd_appd: start with m=%d %s",
719          i_mode, hexdump(i_item,i_ptr-i_item,hexbuff) );
720
721    while (i_more)
722    {     
723       /* store the mode bit inside key */
724       assert( ((i_key.seqno<<1)>>1) == i_key.seqno); /* can spare the bit */
725       i_key.seqno = i_key.seqno * 2 + i_mode;  
726
727       c_ptr=codebuff;
728       i_ptr=i_item;
729       (*is->method->code_item)(ISAMD_ENCODE, encoder_data, &c_ptr, &i_ptr);
730       codelen = c_ptr - codebuff;
731       assert ( (codelen<128) && (codelen>0));
732       if (is->method->debug >3)
733          logf(LOG_LOG,"isamd_appd: coded into %d: %s (nk=%d) (ix=%d)",
734              codelen, hexdump(codebuff, codelen,hexbuff), 
735              firstpp->numKeys,diffidx);
736
737       if (diffidx + codelen > maxsize )
738       { /* block full */
739          if (is->method->debug >3)
740             logf(LOG_LOG,"isamd_appd: block full (ix=%d mx=%d lix=%d)",
741                diffidx, maxsize, difflenidx);
742          if (is->method->debug >3)
743             logf(LOG_LOG,"isamd_appd: block pp=%p buf=%p [%d]:%s",
744                pp, pp->buf, difflenidx, hexdump(&pp->buf[difflenidx],8,0));
745          merge_rc = merge (&firstpp, &pp, &i_key);
746          if (merge_rc)
747            return merge_rc;  /* merge handled them all ! */
748
749           /* set things up so we can continue */
750           pp = read_diff_block(firstpp, &diffidx);
751           
752       } /* block full */
753       
754       /* save the diff */ 
755       memcpy(&(pp->buf[diffidx]),codebuff,codelen);
756       diffidx += codelen;
757       if (i_mode)
758         firstpp->numKeys++; /* insert diff */
759       else
760         firstpp->numKeys--; /* delete diff */ 
761
762       /* update length of this diff run */
763       memcpy(&(pp->buf[difflenidx]),&diffidx,sizeof(diffidx));
764       if (firstpp==pp)
765         firstpp->diffs =diffidx*2+0;
766       else
767         pp->size =diffidx;
768       
769       /* (try to) read the next input */
770       i_ptr = i_item;
771       i_more = (*data->read_item)(data->clientData, &i_ptr, &i_mode); 
772       if ( (i_more) && (is->method->debug >3) )
773          logf(LOG_LOG,"isamd_appd: got m=%d %s",
774             i_mode, hexdump(i_item,i_ptr-i_item,hexbuff) );
775    } /* more loop */
776
777    /* clear the next difflen, if room for such */
778    difflenidx = diffidx;
779    while ( (difflenidx-diffidx<=sizeof(int)) && (difflenidx<maxsize))
780      pp->buf[difflenidx++]='\0';
781
782    return save_both_pps( firstpp, pp );
783
784 } /* append_diffs */
785
786
787
788 /*************************************************************
789  * isamd_append itself, Sweet, isn't it
790  *************************************************************/
791
792 ISAMD_P isamd_append (ISAMD is, ISAMD_P ipos, ISAMD_I data)
793 {
794    int retval=0;
795
796    if (0==ipos)
797       retval = isamd_build_first_block(is,data);
798    else
799       retval = append_diffs(is,ipos,data);
800
801    return retval;
802 } /*  isamd_append */
803
804
805 /*
806  * $Log: merge-d.c,v $
807  * Revision 1.5  1999-07-23 13:58:52  heikki
808  * merged closer to working, still fails on filling a separate, large block
809  *
810  * Revision 1.4  1999/07/21 14:53:55  heikki
811  * isamd read and write functions work, except when block full
812  * Merge missing still. Need to split some functions
813  *
814  * Revision 1.1  1999/07/14 13:14:47  heikki
815  * Created empty
816  *
817  *
818  */
819
820
821
822