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