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