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