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