MySQL 5.6.14 Source Code Document
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
myisampack.c
1 /* Copyright (c) 2000, 2012, Oracle and/or its affiliates. All rights reserved.
2 
3  This program is free software; you can redistribute it and/or modify
4  it under the terms of the GNU General Public License as published by
5  the Free Software Foundation; version 2 of the License.
6 
7  This program is distributed in the hope that it will be useful,
8  but WITHOUT ANY WARRANTY; without even the implied warranty of
9  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
10  GNU General Public License for more details.
11 
12  You should have received a copy of the GNU General Public License
13  along with this program; if not, write to the Free Software
14  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */
15 
16 /* Pack MyISAM file */
17 
18 #ifndef USE_MY_FUNC
19 #define USE_MY_FUNC /* We need at least my_malloc */
20 #endif
21 
22 #include "myisamdef.h"
23 #include "my_default.h"
24 #include <queues.h>
25 #include <my_tree.h>
26 #include "mysys_err.h"
27 #ifndef __GNU_LIBRARY__
28 #define __GNU_LIBRARY__ /* Skip warnings in getopt.h */
29 #endif
30 #include <my_getopt.h>
31 #include <assert.h>
32 
33 #if SIZEOF_LONG_LONG > 4
34 #define BITS_SAVED 64
35 #else
36 #define BITS_SAVED 32
37 #endif
38 
39 #define IS_OFFSET ((uint) 32768) /* Bit if offset or char in tree */
40 #define HEAD_LENGTH 32
41 #define ALLOWED_JOIN_DIFF 256 /* Diff allowed to join trees */
42 
43 #define DATA_TMP_EXT ".TMD"
44 #define OLD_EXT ".OLD"
45 #define FRM_EXT ".frm"
46 #define WRITE_COUNT MY_HOW_OFTEN_TO_WRITE
47 
49  File file;
50  uchar *buffer,*pos,*end;
51  my_off_t pos_in_file;
52  int bits;
53  ulonglong bitbucket;
54 };
55 
56 struct st_huff_tree;
57 struct st_huff_element;
58 
59 typedef struct st_huff_counts {
60  uint field_length,max_zero_fill;
61  uint pack_type;
62  uint max_end_space,max_pre_space,length_bits,min_space;
63  ulong max_length;
64  enum en_fieldtype field_type;
65  struct st_huff_tree *tree; /* Tree for field */
66  my_off_t counts[256];
67  my_off_t end_space[8];
68  my_off_t pre_space[8];
69  my_off_t tot_end_space,tot_pre_space,zero_fields,empty_fields,bytes_packed;
70  TREE int_tree; /* Tree for detecting distinct column values. */
71  uchar *tree_buff; /* Column values, 'field_length' each. */
72  uchar *tree_pos; /* Points to end of column values in 'tree_buff'. */
73 } HUFF_COUNTS;
74 
75 typedef struct st_huff_element HUFF_ELEMENT;
76 
77 /*
78  WARNING: It is crucial for the optimizations in calc_packed_length()
79  that 'count' is the first element of 'HUFF_ELEMENT'.
80 */
82  my_off_t count;
83  union un_element {
84  struct st_nod {
85  HUFF_ELEMENT *left,*right;
86  } nod;
87  struct st_leaf {
88  HUFF_ELEMENT *null;
89  uint element_nr; /* Number of element */
90  } leaf;
91  } a;
92 };
93 
94 
95 typedef struct st_huff_tree {
96  HUFF_ELEMENT *root,*element_buffer;
97  HUFF_COUNTS *counts;
98  uint tree_number;
99  uint elements;
100  my_off_t bytes_packed;
101  uint tree_pack_length;
102  uint min_chr,max_chr,char_bits,offset_bits,max_offset,height;
103  ulonglong *code;
104  uchar *code_len;
105 } HUFF_TREE;
106 
107 
108 typedef struct st_isam_mrg {
109  MI_INFO **file,**current,**end;
110  uint free_file;
111  uint count;
112  uint min_pack_length; /* Theese is used by packed data */
113  uint max_pack_length;
114  uint ref_length;
115  uint max_blob_length;
116  my_off_t records;
117  /* true if at least one source file has at least one disabled index */
118  my_bool src_file_has_indexes_disabled;
119 } PACK_MRG_INFO;
120 
121 
122 extern int main(int argc,char * *argv);
123 static void get_options(int *argc,char ***argv);
124 static MI_INFO *open_isam_file(char *name,int mode);
125 static my_bool open_isam_files(PACK_MRG_INFO *mrg,char **names,uint count);
126 static int compress(PACK_MRG_INFO *file,char *join_name);
127 static int create_dest_frm(char *source_table, char *dest_table);
128 static HUFF_COUNTS *init_huff_count(MI_INFO *info,my_off_t records);
129 static void free_counts_and_tree_and_queue(HUFF_TREE *huff_trees,
130  uint trees,
131  HUFF_COUNTS *huff_counts,
132  uint fields);
133 static int compare_tree(void* cmp_arg __attribute__((unused)),
134  const uchar *s,const uchar *t);
135 static int get_statistic(PACK_MRG_INFO *mrg,HUFF_COUNTS *huff_counts);
136 static void check_counts(HUFF_COUNTS *huff_counts,uint trees,
137  my_off_t records);
138 static int test_space_compress(HUFF_COUNTS *huff_counts,my_off_t records,
139  uint max_space_length,my_off_t *space_counts,
140  my_off_t tot_space_count,
141  enum en_fieldtype field_type);
142 static HUFF_TREE* make_huff_trees(HUFF_COUNTS *huff_counts,uint trees);
143 static int make_huff_tree(HUFF_TREE *tree,HUFF_COUNTS *huff_counts);
144 static int compare_huff_elements(void *not_used, uchar *a,uchar *b);
145 static int save_counts_in_queue(uchar *key,element_count count,
146  HUFF_TREE *tree);
147 static my_off_t calc_packed_length(HUFF_COUNTS *huff_counts,uint flag);
148 static uint join_same_trees(HUFF_COUNTS *huff_counts,uint trees);
149 static int make_huff_decode_table(HUFF_TREE *huff_tree,uint trees);
150 static void make_traverse_code_tree(HUFF_TREE *huff_tree,
151  HUFF_ELEMENT *element,uint size,
152  ulonglong code);
153 static int write_header(PACK_MRG_INFO *isam_file, uint header_length,uint trees,
154  my_off_t tot_elements,my_off_t filelength);
155 static void write_field_info(HUFF_COUNTS *counts, uint fields,uint trees);
156 static my_off_t write_huff_tree(HUFF_TREE *huff_tree,uint trees);
157 static uint *make_offset_code_tree(HUFF_TREE *huff_tree,
158  HUFF_ELEMENT *element,
159  uint *offset);
160 static uint max_bit(uint value);
161 static int compress_isam_file(PACK_MRG_INFO *file,HUFF_COUNTS *huff_counts);
162 static char *make_new_name(char *new_name,char *old_name);
163 static char *make_old_name(char *new_name,char *old_name);
164 static void init_file_buffer(File file,pbool read_buffer);
165 static int flush_buffer(ulong neaded_length);
166 static void end_file_buffer(void);
167 static void write_bits(ulonglong value, uint bits);
168 static void flush_bits(void);
169 static int save_state(MI_INFO *isam_file,PACK_MRG_INFO *mrg,my_off_t new_length,
170  ha_checksum crc);
171 static int save_state_mrg(File file,PACK_MRG_INFO *isam_file,my_off_t new_length,
172  ha_checksum crc);
173 static int mrg_close(PACK_MRG_INFO *mrg);
174 static int mrg_rrnd(PACK_MRG_INFO *info,uchar *buf);
175 static void mrg_reset(PACK_MRG_INFO *mrg);
176 #if !defined(DBUG_OFF)
177 static void fakebigcodes(HUFF_COUNTS *huff_counts, HUFF_COUNTS *end_count);
178 static int fakecmp(my_off_t **count1, my_off_t **count2);
179 #endif
180 
181 
182 static int error_on_write=0,test_only=0,verbose=0,silent=0,
183  write_loop=0,force_pack=0, isamchk_neaded=0;
184 static int tmpfile_createflag=O_RDWR | O_TRUNC | O_EXCL;
185 static my_bool backup, opt_wait;
186 /*
187  tree_buff_length is somewhat arbitrary. The bigger it is the better
188  the chance to win in terms of compression factor. On the other hand,
189  this table becomes part of the compressed file header. And its length
190  is coded with 16 bits in the header. Hence the limit is 2**16 - 1.
191 */
192 static uint tree_buff_length= 65536 - MALLOC_OVERHEAD;
193 static char tmp_dir[FN_REFLEN]={0},*join_table;
194 static my_off_t intervall_length;
195 static ha_checksum glob_crc;
196 static struct st_file_buffer file_buffer;
197 static QUEUE queue;
198 static HUFF_COUNTS *global_count;
199 static char zero_string[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
200 static const char *load_default_groups[]= { "myisampack",0 };
201 
202  /* The main program */
203 
204 int main(int argc, char **argv)
205 {
206  int error,ok;
207  PACK_MRG_INFO merge;
208  char **default_argv;
209  MY_INIT(argv[0]);
210 
211  if (load_defaults("my",load_default_groups,&argc,&argv))
212  exit(1);
213 
214  default_argv= argv;
215  get_options(&argc,&argv);
216 
217  error=ok=isamchk_neaded=0;
218  if (join_table)
219  {
220  /*
221  Join files into one and create FRM file for the compressed table only if
222  the compression succeeds
223  */
224  if (open_isam_files(&merge,argv,(uint) argc) ||
225  compress(&merge, join_table) || create_dest_frm(argv[0], join_table))
226  error=1;
227  }
228  else while (argc--)
229  {
230  MI_INFO *isam_file;
231  if (!(isam_file=open_isam_file(*argv++,O_RDWR)))
232  error=1;
233  else
234  {
235  merge.file= &isam_file;
236  merge.current=0;
237  merge.free_file=0;
238  merge.count=1;
239  if (compress(&merge,0))
240  error=1;
241  else
242  ok=1;
243  }
244  }
245  if (ok && isamchk_neaded && !silent)
246  puts("Remember to run myisamchk -rq on compressed tables");
247  (void) fflush(stdout);
248  (void) fflush(stderr);
249  free_defaults(default_argv);
250  my_end(verbose ? MY_CHECK_ERROR | MY_GIVE_INFO : MY_CHECK_ERROR);
251  exit(error ? 2 : 0);
252 #ifndef _lint
253  return 0; /* No compiler warning */
254 #endif
255 }
256 
257 enum options_mp {OPT_CHARSETS_DIR_MP=256};
258 
259 static struct my_option my_long_options[] =
260 {
261  {"backup", 'b', "Make a backup of the table as table_name.OLD.",
262  &backup, &backup, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
263  {"character-sets-dir", OPT_CHARSETS_DIR_MP,
264  "Directory where character sets are.", &charsets_dir,
265  &charsets_dir, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
266  {"debug", '#', "Output debug log. Often this is 'd:t:o,filename'.",
267  0, 0, 0, GET_STR, OPT_ARG, 0, 0, 0, 0, 0, 0},
268  {"force", 'f',
269  "Force packing of table even if it gets bigger or if tempfile exists.",
270  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
271  {"join", 'j',
272  "Join all given tables into 'new_table_name'. All tables MUST have identical layouts.",
273  &join_table, &join_table, 0, GET_STR, REQUIRED_ARG, 0, 0, 0,
274  0, 0, 0},
275  {"help", '?', "Display this help and exit.",
276  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
277  {"silent", 's', "Be more silent.",
278  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
279  {"tmpdir", 'T', "Use temporary directory to store temporary table.",
280  0, 0, 0, GET_STR, REQUIRED_ARG, 0, 0, 0, 0, 0, 0},
281  {"test", 't', "Don't pack table, only test packing it.",
282  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
283  {"verbose", 'v', "Write info about progress and packing result. Use many -v for more verbosity!",
284  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
285  {"version", 'V', "Output version information and exit.",
286  0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0},
287  {"wait", 'w', "Wait and retry if table is in use.", &opt_wait,
288  &opt_wait, 0, GET_BOOL, NO_ARG, 0, 0, 0, 0, 0, 0},
289  { 0, 0, 0, 0, 0, 0, GET_NO_ARG, NO_ARG, 0, 0, 0, 0, 0, 0}
290 };
291 
292 
293 static void print_version(void)
294 {
295  printf("%s Ver 1.23 for %s on %s\n",
296  my_progname, SYSTEM_TYPE, MACHINE_TYPE);
297 }
298 
299 
300 static void usage(void)
301 {
302  print_version();
303  puts("Copyright 2002-2008 MySQL AB, 2008 Sun Microsystems, Inc.");
304  puts("This software comes with ABSOLUTELY NO WARRANTY. This is free software,");
305  puts("and you are welcome to modify and redistribute it under the GPL license\n");
306 
307  puts("Pack a MyISAM-table to take much less space.");
308  puts("Keys are not updated, you must run myisamchk -rq on the datafile");
309  puts("afterwards to update the keys.");
310  puts("You should give the .MYI file as the filename argument.");
311 
312  printf("\nUsage: %s [OPTIONS] filename...\n", my_progname);
313  my_print_help(my_long_options);
314  print_defaults("my", load_default_groups);
315  my_print_variables(my_long_options);
316 }
317 
318 
319 static my_bool
320 get_one_option(int optid, const struct my_option *opt __attribute__((unused)),
321  char *argument)
322 {
323  uint length;
324 
325  switch(optid) {
326  case 'f':
327  force_pack= 1;
328  tmpfile_createflag= O_RDWR | O_TRUNC;
329  break;
330  case 's':
331  write_loop= verbose= 0;
332  silent= 1;
333  break;
334  case 't':
335  test_only= 1;
336  /* Avoid to reset 'verbose' if it was already set > 1. */
337  if (! verbose)
338  verbose= 1;
339  break;
340  case 'T':
341  length= (uint) (strmov(tmp_dir, argument) - tmp_dir);
342  if (length != dirname_length(tmp_dir))
343  {
344  tmp_dir[length]=FN_LIBCHAR;
345  tmp_dir[length+1]=0;
346  }
347  break;
348  case 'v':
349  verbose++; /* Allow for selecting the level of verbosity. */
350  silent= 0;
351  break;
352  case '#':
353  DBUG_PUSH(argument ? argument : "d:t:o");
354  break;
355  case 'V':
356  print_version();
357  exit(0);
358  case 'I':
359  case '?':
360  usage();
361  exit(0);
362  }
363  return 0;
364 }
365 
366  /* reads options */
367  /* Initiates DEBUG - but no debugging here ! */
368 
369 static void get_options(int *argc,char ***argv)
370 {
371  int ho_error;
372 
373  my_progname= argv[0][0];
374  if (isatty(fileno(stdout)))
375  write_loop=1;
376 
377  if ((ho_error=handle_options(argc, argv, my_long_options, get_one_option)))
378  exit(ho_error);
379 
380  if (!*argc)
381  {
382  usage();
383  exit(1);
384  }
385  if (join_table)
386  {
387  backup=0; /* Not needed */
388  tmp_dir[0]=0;
389  }
390  return;
391 }
392 
393 
394 static MI_INFO *open_isam_file(char *name,int mode)
395 {
396  MI_INFO *isam_file;
397  MYISAM_SHARE *share;
398  DBUG_ENTER("open_isam_file");
399 
400  if (!(isam_file=mi_open(name,mode,
401  (opt_wait ? HA_OPEN_WAIT_IF_LOCKED :
402  HA_OPEN_ABORT_IF_LOCKED))))
403  {
404  (void) fprintf(stderr, "%s gave error %d on open\n", name, my_errno);
405  DBUG_RETURN(0);
406  }
407  share=isam_file->s;
408  if (share->options & HA_OPTION_COMPRESS_RECORD && !join_table)
409  {
410  if (!force_pack)
411  {
412  (void) fprintf(stderr, "%s is already compressed\n", name);
413  (void) mi_close(isam_file);
414  DBUG_RETURN(0);
415  }
416  if (verbose)
417  puts("Recompressing already compressed table");
418  share->options&= ~HA_OPTION_READ_ONLY_DATA; /* We are modifing it */
419  }
420  if (! force_pack && share->state.state.records != 0 &&
421  (share->state.state.records <= 1 ||
422  share->state.state.data_file_length < 1024))
423  {
424  (void) fprintf(stderr, "%s is too small to compress\n", name);
425  (void) mi_close(isam_file);
426  DBUG_RETURN(0);
427  }
428  (void) mi_lock_database(isam_file,F_WRLCK);
429  DBUG_RETURN(isam_file);
430 }
431 
432 
433 static my_bool open_isam_files(PACK_MRG_INFO *mrg, char **names, uint count)
434 {
435  uint i,j;
436  mrg->count=0;
437  mrg->current=0;
438  mrg->file=(MI_INFO**) my_malloc(sizeof(MI_INFO*)*count,MYF(MY_FAE));
439  mrg->free_file=1;
440  mrg->src_file_has_indexes_disabled= 0;
441  for (i=0; i < count ; i++)
442  {
443  if (!(mrg->file[i]=open_isam_file(names[i],O_RDONLY)))
444  goto error;
445 
446  mrg->src_file_has_indexes_disabled|=
447  ! mi_is_all_keys_active(mrg->file[i]->s->state.key_map,
448  mrg->file[i]->s->base.keys);
449  }
450  /* Check that files are identical */
451  for (j=0 ; j < count-1 ; j++)
452  {
453  MI_COLUMNDEF *m1,*m2,*end;
454  if (mrg->file[j]->s->base.reclength != mrg->file[j+1]->s->base.reclength ||
455  mrg->file[j]->s->base.fields != mrg->file[j+1]->s->base.fields)
456  goto diff_file;
457  m1=mrg->file[j]->s->rec;
458  end=m1+mrg->file[j]->s->base.fields;
459  m2=mrg->file[j+1]->s->rec;
460  for ( ; m1 != end ; m1++,m2++)
461  {
462  if (m1->type != m2->type || m1->length != m2->length)
463  goto diff_file;
464  }
465  }
466  mrg->count=count;
467  return 0;
468 
469  diff_file:
470  (void) fprintf(stderr, "%s: Tables '%s' and '%s' are not identical\n",
471  my_progname, names[j], names[j+1]);
472  error:
473  while (i--)
474  mi_close(mrg->file[i]);
475  my_free(mrg->file);
476  return 1;
477 }
478 
479 
480 static int compress(PACK_MRG_INFO *mrg,char *result_table)
481 {
482  int error;
483  File new_file,join_isam_file;
484  MI_INFO *isam_file;
485  MYISAM_SHARE *share;
486  char org_name[FN_REFLEN],new_name[FN_REFLEN],temp_name[FN_REFLEN];
487  uint i,header_length,fields,trees,used_trees;
488  my_off_t old_length,new_length,tot_elements;
489  HUFF_COUNTS *huff_counts;
490  HUFF_TREE *huff_trees;
491  DBUG_ENTER("compress");
492 
493  isam_file=mrg->file[0]; /* Take this as an example */
494  share=isam_file->s;
495  new_file=join_isam_file= -1;
496  trees=fields=0;
497  huff_trees=0;
498  huff_counts=0;
499 
500  /* Create temporary or join file */
501 
502  if (backup)
503  (void) fn_format(org_name,isam_file->filename,"",MI_NAME_DEXT,2);
504  else
505  (void) fn_format(org_name,isam_file->filename,"",MI_NAME_DEXT,2+4+16);
506  if (!test_only && result_table)
507  {
508  /* Make a new indexfile based on first file in list */
509  uint length;
510  uchar *buff;
511  strmov(org_name,result_table); /* Fix error messages */
512  (void) fn_format(new_name,result_table,"",MI_NAME_IEXT,2);
513  if ((join_isam_file=my_create(new_name,0,tmpfile_createflag,MYF(MY_WME)))
514  < 0)
515  goto err;
516  length=(uint) share->base.keystart;
517  if (!(buff= (uchar*) my_malloc(length,MYF(MY_WME))))
518  goto err;
519  if (my_pread(share->kfile,buff,length,0L,MYF(MY_WME | MY_NABP)) ||
520  my_write(join_isam_file,buff,length,
521  MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)))
522  {
523  my_free(buff);
524  goto err;
525  }
526  my_free(buff);
527  (void) fn_format(new_name,result_table,"",MI_NAME_DEXT,2);
528  }
529  else if (!tmp_dir[0])
530  (void) make_new_name(new_name,org_name);
531  else
532  (void) fn_format(new_name,org_name,tmp_dir,DATA_TMP_EXT,1+2+4);
533  if (!test_only &&
534  (new_file=my_create(new_name,0,tmpfile_createflag,MYF(MY_WME))) < 0)
535  goto err;
536 
537  /* Start calculating statistics */
538 
539  mrg->records=0;
540  for (i=0 ; i < mrg->count ; i++)
541  mrg->records+=mrg->file[i]->s->state.state.records;
542 
543  DBUG_PRINT("info", ("Compressing %s: (%lu records)",
544  result_table ? new_name : org_name,
545  (ulong) mrg->records));
546  if (write_loop || verbose)
547  {
548  printf("Compressing %s: (%lu records)\n",
549  result_table ? new_name : org_name, (ulong) mrg->records);
550  }
551  trees=fields=share->base.fields;
552  huff_counts=init_huff_count(isam_file,mrg->records);
553 
554  /*
555  Read the whole data file(s) for statistics.
556  */
557  DBUG_PRINT("info", ("- Calculating statistics"));
558  if (write_loop || verbose)
559  printf("- Calculating statistics\n");
560  if (get_statistic(mrg,huff_counts))
561  goto err;
562 
563  old_length=0;
564  for (i=0; i < mrg->count ; i++)
565  old_length+= (mrg->file[i]->s->state.state.data_file_length -
566  mrg->file[i]->s->state.state.empty);
567 
568  /*
569  Create a global priority queue in preparation for making
570  temporary Huffman trees.
571  */
572  if (init_queue(&queue,256,0,0,compare_huff_elements,0))
573  goto err;
574 
575  /*
576  Check each column if we should use pre-space-compress, end-space-
577  compress, empty-field-compress or zero-field-compress.
578  */
579  check_counts(huff_counts,fields,mrg->records);
580 
581  /*
582  Build a Huffman tree for each column.
583  */
584  huff_trees=make_huff_trees(huff_counts,trees);
585 
586  /*
587  If the packed lengths of combined columns is less then the sum of
588  the non-combined columns, then create common Huffman trees for them.
589  We do this only for byte compressed columns, not for distinct values
590  compressed columns.
591  */
592  if ((int) (used_trees=join_same_trees(huff_counts,trees)) < 0)
593  goto err;
594 
595  /*
596  Assign codes to all byte or column values.
597  */
598  if (make_huff_decode_table(huff_trees,fields))
599  goto err;
600 
601  /* Prepare a file buffer. */
602  init_file_buffer(new_file,0);
603 
604  /*
605  Reserve space in the target file for the fixed compressed file header.
606  */
607  file_buffer.pos_in_file=HEAD_LENGTH;
608  if (! test_only)
609  my_seek(new_file,file_buffer.pos_in_file,MY_SEEK_SET,MYF(0));
610 
611  /*
612  Write field infos: field type, pack type, length bits, tree number.
613  */
614  write_field_info(huff_counts,fields,used_trees);
615 
616  /*
617  Write decode trees.
618  */
619  if (!(tot_elements=write_huff_tree(huff_trees,trees)))
620  goto err;
621 
622  /*
623  Calculate the total length of the compression info header.
624  This includes the fixed compressed file header, the column compression
625  type descriptions, and the decode trees.
626  */
627  header_length=(uint) file_buffer.pos_in_file+
628  (uint) (file_buffer.pos-file_buffer.buffer);
629 
630  /*
631  Compress the source file into the target file.
632  */
633  DBUG_PRINT("info", ("- Compressing file"));
634  if (write_loop || verbose)
635  printf("- Compressing file\n");
636  error=compress_isam_file(mrg,huff_counts);
637  new_length=file_buffer.pos_in_file;
638  if (!error && !test_only)
639  {
640  uchar buff[MEMMAP_EXTRA_MARGIN]; /* End marginal for memmap */
641  memset(buff, 0, sizeof(buff));
642  error=my_write(file_buffer.file,buff,sizeof(buff),
643  MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)) != 0;
644  }
645 
646  /*
647  Write the fixed compressed file header.
648  */
649  if (!error)
650  error=write_header(mrg,header_length,used_trees,tot_elements,
651  new_length);
652 
653  /* Flush the file buffer. */
654  end_file_buffer();
655 
656  /* Display statistics. */
657  DBUG_PRINT("info", ("Min record length: %6d Max length: %6d "
658  "Mean total length: %6ld\n",
659  mrg->min_pack_length, mrg->max_pack_length,
660  (ulong) (mrg->records ? (new_length/mrg->records) : 0)));
661  if (verbose && mrg->records)
662  printf("Min record length: %6d Max length: %6d "
663  "Mean total length: %6ld\n", mrg->min_pack_length,
664  mrg->max_pack_length, (ulong) (new_length/mrg->records));
665 
666  /* Close source and target file. */
667  if (!test_only)
668  {
669  error|=my_close(new_file,MYF(MY_WME));
670  if (!result_table)
671  {
672  error|=my_close(isam_file->dfile,MYF(MY_WME));
673  isam_file->dfile= -1; /* Tell mi_close file is closed */
674  }
675  }
676 
677  /* Cleanup. */
678  free_counts_and_tree_and_queue(huff_trees,trees,huff_counts,fields);
679  if (! test_only && ! error)
680  {
681  if (result_table)
682  {
683  error=save_state_mrg(join_isam_file,mrg,new_length,glob_crc);
684  }
685  else
686  {
687  if (backup)
688  {
689  if (my_rename(org_name,make_old_name(temp_name,isam_file->filename),
690  MYF(MY_WME)))
691  error=1;
692  else
693  {
694  if (tmp_dir[0])
695  error=my_copy(new_name,org_name,MYF(MY_WME));
696  else
697  error=my_rename(new_name,org_name,MYF(MY_WME));
698  if (!error)
699  {
700  (void) my_copystat(temp_name,org_name,MYF(MY_COPYTIME));
701  if (tmp_dir[0])
702  (void) my_delete(new_name,MYF(MY_WME));
703  }
704  }
705  }
706  else
707  {
708  if (tmp_dir[0])
709  {
710  error=my_copy(new_name,org_name,
711  MYF(MY_WME | MY_HOLD_ORIGINAL_MODES | MY_COPYTIME));
712  if (!error)
713  (void) my_delete(new_name,MYF(MY_WME));
714  }
715  else
716  error=my_redel(org_name,new_name,MYF(MY_WME | MY_COPYTIME));
717  }
718  if (! error)
719  error=save_state(isam_file,mrg,new_length,glob_crc);
720  }
721  }
722  error|=mrg_close(mrg);
723  if (join_isam_file >= 0)
724  error|=my_close(join_isam_file,MYF(MY_WME));
725  if (error)
726  {
727  (void) fprintf(stderr, "Aborting: %s is not compressed\n", org_name);
728  (void) my_delete(new_name,MYF(MY_WME));
729  DBUG_RETURN(-1);
730  }
731  if (write_loop || verbose)
732  {
733  if (old_length)
734  printf("%.4g%% \n",
735  (((longlong) (old_length - new_length)) * 100.0 /
736  (longlong) old_length));
737  else
738  puts("Empty file saved in compressed format");
739  }
740  DBUG_RETURN(0);
741 
742  err:
743  free_counts_and_tree_and_queue(huff_trees,trees,huff_counts,fields);
744  if (new_file >= 0)
745  (void) my_close(new_file,MYF(0));
746  if (join_isam_file >= 0)
747  (void) my_close(join_isam_file,MYF(0));
748  mrg_close(mrg);
749  (void) fprintf(stderr, "Aborted: %s is not compressed\n", org_name);
750  DBUG_RETURN(-1);
751 }
752 
753 
768 static int create_dest_frm(char *source_table, char *dest_table)
769 {
770  char source_name[FN_REFLEN], dest_name[FN_REFLEN];
771 
772  DBUG_ENTER("create_dest_frm");
773 
774  (void) fn_format(source_name, source_table,
775  "", FRM_EXT, MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS);
776  (void) fn_format(dest_name, dest_table,
777  "", FRM_EXT, MY_UNPACK_FILENAME | MY_RESOLVE_SYMLINKS);
778  /*
779  Error messages produced by my_copy() are suppressed as this
780  is not vital for --join operation. User shouldn't see any error messages
781  like "source file frm not found" and "unable to create destination frm
782  file. So we don't pass the flag MY_WME -Write Message on Error to
783  my_copy()
784  */
785  (void) my_copy(source_name, dest_name, MYF(MY_DONT_OVERWRITE_FILE));
786 
787  DBUG_RETURN(0);
788 }
789 
790 
791  /* Init a huff_count-struct for each field and init it */
792 
793 static HUFF_COUNTS *init_huff_count(MI_INFO *info,my_off_t records)
794 {
795  reg2 uint i;
796  reg1 HUFF_COUNTS *count;
797  if ((count = (HUFF_COUNTS*) my_malloc(info->s->base.fields*
798  sizeof(HUFF_COUNTS),
799  MYF(MY_ZEROFILL | MY_WME))))
800  {
801  for (i=0 ; i < info->s->base.fields ; i++)
802  {
803  enum en_fieldtype type;
804  count[i].field_length=info->s->rec[i].length;
805  type= count[i].field_type= (enum en_fieldtype) info->s->rec[i].type;
806  if (type == FIELD_INTERVALL ||
807  type == FIELD_CONSTANT ||
808  type == FIELD_ZERO)
809  type = FIELD_NORMAL;
810  if (count[i].field_length <= 8 &&
811  (type == FIELD_NORMAL ||
812  type == FIELD_SKIP_ZERO))
813  count[i].max_zero_fill= count[i].field_length;
814  /*
815  For every column initialize a tree, which is used to detect distinct
816  column values. 'int_tree' works together with 'tree_buff' and
817  'tree_pos'. It's keys are implemented by pointers into 'tree_buff'.
818  This is accomplished by '-1' as the element size.
819  */
820  init_tree(&count[i].int_tree,0,0,-1,(qsort_cmp2) compare_tree,0, NULL,
821  NULL);
822  if (records && type != FIELD_BLOB && type != FIELD_VARCHAR)
823  count[i].tree_pos=count[i].tree_buff =
824  my_malloc(count[i].field_length > 1 ? tree_buff_length : 2,
825  MYF(MY_WME));
826  }
827  }
828  return count;
829 }
830 
831 
832  /* Free memory used by counts and trees */
833 
834 static void free_counts_and_tree_and_queue(HUFF_TREE *huff_trees, uint trees,
835  HUFF_COUNTS *huff_counts,
836  uint fields)
837 {
838  register uint i;
839 
840  if (huff_trees)
841  {
842  for (i=0 ; i < trees ; i++)
843  {
844  if (huff_trees[i].element_buffer)
845  my_free(huff_trees[i].element_buffer);
846  if (huff_trees[i].code)
847  my_free(huff_trees[i].code);
848  }
849  my_free(huff_trees);
850  }
851  if (huff_counts)
852  {
853  for (i=0 ; i < fields ; i++)
854  {
855  if (huff_counts[i].tree_buff)
856  {
857  my_free(huff_counts[i].tree_buff);
858  delete_tree(&huff_counts[i].int_tree);
859  }
860  }
861  my_free(huff_counts);
862  }
863  delete_queue(&queue); /* This is safe to free */
864  return;
865 }
866 
867  /* Read through old file and gather some statistics */
868 
869 static int get_statistic(PACK_MRG_INFO *mrg,HUFF_COUNTS *huff_counts)
870 {
871  int error;
872  uint length;
873  ulong reclength,max_blob_length;
874  uchar *record,*pos,*next_pos,*end_pos,*start_pos;
875  ha_rows record_count;
876  my_bool static_row_size;
877  HUFF_COUNTS *count,*end_count;
878  TREE_ELEMENT *element;
879  DBUG_ENTER("get_statistic");
880 
881  reclength=mrg->file[0]->s->base.reclength;
882  record=(uchar*) my_alloca(reclength);
883  end_count=huff_counts+mrg->file[0]->s->base.fields;
884  record_count=0; glob_crc=0;
885  max_blob_length=0;
886 
887  /* Check how to calculate checksum */
888  static_row_size=1;
889  for (count=huff_counts ; count < end_count ; count++)
890  {
891  if (count->field_type == FIELD_BLOB ||
892  count->field_type == FIELD_VARCHAR)
893  {
894  static_row_size=0;
895  break;
896  }
897  }
898 
899  mrg_reset(mrg);
900  while ((error=mrg_rrnd(mrg,record)) != HA_ERR_END_OF_FILE)
901  {
902  ulong tot_blob_length=0;
903  if (! error)
904  {
905  /* glob_crc is a checksum over all bytes of all records. */
906  if (static_row_size)
907  glob_crc+=mi_static_checksum(mrg->file[0],record);
908  else
909  glob_crc+=mi_checksum(mrg->file[0],record);
910 
911  /* Count the incidence of values separately for every column. */
912  for (pos=record,count=huff_counts ;
913  count < end_count ;
914  count++,
915  pos=next_pos)
916  {
917  next_pos=end_pos=(start_pos=pos)+count->field_length;
918 
919  /*
920  Put the whole column value in a tree if there is room for it.
921  'int_tree' is used to quickly check for duplicate values.
922  'tree_buff' collects as many distinct column values as
923  possible. If the field length is > 1, it is tree_buff_length,
924  else 2 bytes. Each value is 'field_length' bytes big. If there
925  are more distinct column values than fit into the buffer, we
926  give up with this tree. BLOBs and VARCHARs do not have a
927  tree_buff as it can only be used with fixed length columns.
928  For the special case of field length == 1, we handle only the
929  case that there is only one distinct value in the table(s).
930  Otherwise, we can have a maximum of 256 distinct values. This
931  is then handled by the normal Huffman tree build.
932 
933  Another limit for collecting distinct column values is the
934  number of values itself. Since we would need to build a
935  Huffman tree for the values, we are limited by the 'IS_OFFSET'
936  constant. This constant expresses a bit which is used to
937  determine if a tree element holds a final value or an offset
938  to a child element. Hence, all values and offsets need to be
939  smaller than 'IS_OFFSET'. A tree element is implemented with
940  two integer values, one for the left branch and one for the
941  right branch. For the extreme case that the first element
942  points to the last element, the number of integers in the tree
943  must be less or equal to IS_OFFSET. So the number of elements
944  must be less or equal to IS_OFFSET / 2.
945 
946  WARNING: At first, we insert a pointer into the record buffer
947  as the key for the tree. If we got a new distinct value, which
948  is really inserted into the tree, instead of being counted
949  only, we will copy the column value from the record buffer to
950  'tree_buff' and adjust the key pointer of the tree accordingly.
951  */
952  if (count->tree_buff)
953  {
954  global_count=count;
955  if (!(element=tree_insert(&count->int_tree,pos, 0,
956  count->int_tree.custom_arg)) ||
957  (element->count == 1 &&
958  (count->tree_buff + tree_buff_length <
959  count->tree_pos + count->field_length)) ||
960  (count->int_tree.elements_in_tree > IS_OFFSET / 2) ||
961  (count->field_length == 1 &&
962  count->int_tree.elements_in_tree > 1))
963  {
964  delete_tree(&count->int_tree);
965  my_free(count->tree_buff);
966  count->tree_buff=0;
967  }
968  else
969  {
970  /*
971  If tree_insert() succeeds, it either creates a new element
972  or increments the counter of an existing element.
973  */
974  if (element->count == 1)
975  {
976  /* Copy the new column value into 'tree_buff'. */
977  memcpy(count->tree_pos,pos,(size_t) count->field_length);
978  /* Adjust the key pointer in the tree. */
979  tree_set_pointer(element,count->tree_pos);
980  /* Point behind the last column value so far. */
981  count->tree_pos+=count->field_length;
982  }
983  }
984  }
985 
986  /* Save character counters and space-counts and zero-field-counts */
987  if (count->field_type == FIELD_NORMAL ||
988  count->field_type == FIELD_SKIP_ENDSPACE)
989  {
990  /* Ignore trailing space. */
991  for ( ; end_pos > pos ; end_pos--)
992  if (end_pos[-1] != ' ')
993  break;
994  /* Empty fields are just counted. Go to the next record. */
995  if (end_pos == pos)
996  {
997  count->empty_fields++;
998  count->max_zero_fill=0;
999  continue;
1000  }
1001  /*
1002  Count the total of all trailing spaces and the number of
1003  short trailing spaces. Remember the longest trailing space.
1004  */
1005  length= (uint) (next_pos-end_pos);
1006  count->tot_end_space+=length;
1007  if (length < 8)
1008  count->end_space[length]++;
1009  if (count->max_end_space < length)
1010  count->max_end_space = length;
1011  }
1012 
1013  if (count->field_type == FIELD_NORMAL ||
1014  count->field_type == FIELD_SKIP_PRESPACE)
1015  {
1016  /* Ignore leading space. */
1017  for (pos=start_pos; pos < end_pos ; pos++)
1018  if (pos[0] != ' ')
1019  break;
1020  /* Empty fields are just counted. Go to the next record. */
1021  if (end_pos == pos)
1022  {
1023  count->empty_fields++;
1024  count->max_zero_fill=0;
1025  continue;
1026  }
1027  /*
1028  Count the total of all leading spaces and the number of
1029  short leading spaces. Remember the longest leading space.
1030  */
1031  length= (uint) (pos-start_pos);
1032  count->tot_pre_space+=length;
1033  if (length < 8)
1034  count->pre_space[length]++;
1035  if (count->max_pre_space < length)
1036  count->max_pre_space = length;
1037  }
1038 
1039  /* Calculate pos, end_pos, and max_length for variable length fields. */
1040  if (count->field_type == FIELD_BLOB)
1041  {
1042  uint field_length=count->field_length -portable_sizeof_char_ptr;
1043  ulong blob_length= _mi_calc_blob_length(field_length, start_pos);
1044  memcpy(&pos, start_pos+field_length, sizeof(char*));
1045  end_pos=pos+blob_length;
1046  tot_blob_length+=blob_length;
1047  set_if_bigger(count->max_length,blob_length);
1048  }
1049  else if (count->field_type == FIELD_VARCHAR)
1050  {
1051  uint pack_length= HA_VARCHAR_PACKLENGTH(count->field_length-1);
1052  length= (pack_length == 1 ? (uint) *(uchar*) start_pos :
1053  uint2korr(start_pos));
1054  pos= start_pos+pack_length;
1055  end_pos= pos+length;
1056  set_if_bigger(count->max_length,length);
1057  }
1058 
1059  /* Evaluate 'max_zero_fill' for short fields. */
1060  if (count->field_length <= 8 &&
1061  (count->field_type == FIELD_NORMAL ||
1062  count->field_type == FIELD_SKIP_ZERO))
1063  {
1064  uint i;
1065  /* Zero fields are just counted. Go to the next record. */
1066  if (!memcmp((uchar*) start_pos,zero_string,count->field_length))
1067  {
1068  count->zero_fields++;
1069  continue;
1070  }
1071  /*
1072  max_zero_fill starts with field_length. It is decreased every
1073  time a shorter "zero trailer" is found. It is set to zero when
1074  an empty field is found (see above). This suggests that the
1075  variable should be called 'min_zero_fill'.
1076  */
1077  for (i =0 ; i < count->max_zero_fill && ! end_pos[-1 - (int) i] ;
1078  i++) ;
1079  if (i < count->max_zero_fill)
1080  count->max_zero_fill=i;
1081  }
1082 
1083  /* Ignore zero fields and check fields. */
1084  if (count->field_type == FIELD_ZERO ||
1085  count->field_type == FIELD_CHECK)
1086  continue;
1087 
1088  /*
1089  Count the incidence of every byte value in the
1090  significant field value.
1091  */
1092  for ( ; pos < end_pos ; pos++)
1093  count->counts[(uchar) *pos]++;
1094 
1095  /* Step to next field. */
1096  }
1097 
1098  if (tot_blob_length > max_blob_length)
1099  max_blob_length=tot_blob_length;
1100  record_count++;
1101  if (write_loop && record_count % WRITE_COUNT == 0)
1102  {
1103  printf("%lu\r", (ulong) record_count);
1104  (void) fflush(stdout);
1105  }
1106  }
1107  else if (error != HA_ERR_RECORD_DELETED)
1108  {
1109  (void) fprintf(stderr, "Got error %d while reading rows", error);
1110  break;
1111  }
1112 
1113  /* Step to next record. */
1114  }
1115  if (write_loop)
1116  {
1117  printf(" \r");
1118  (void) fflush(stdout);
1119  }
1120 
1121  /*
1122  If --debug=d,fakebigcodes is set, fake the counts to get big Huffman
1123  codes.
1124  */
1125  DBUG_EXECUTE_IF("fakebigcodes", fakebigcodes(huff_counts, end_count););
1126 
1127  DBUG_PRINT("info", ("Found the following number of incidents "
1128  "of the byte codes:"));
1129  if (verbose >= 2)
1130  printf("Found the following number of incidents "
1131  "of the byte codes:\n");
1132  for (count= huff_counts ; count < end_count; count++)
1133  {
1134  uint idx;
1135  my_off_t total_count;
1136  char llbuf[32];
1137 
1138  DBUG_PRINT("info", ("column: %3u", (uint) (count - huff_counts + 1)));
1139  if (verbose >= 2)
1140  printf("column: %3u\n", (uint) (count - huff_counts + 1));
1141  if (count->tree_buff)
1142  {
1143  DBUG_PRINT("info", ("number of distinct values: %u",
1144  (uint) ((count->tree_pos - count->tree_buff) /
1145  count->field_length)));
1146  if (verbose >= 2)
1147  printf("number of distinct values: %u\n",
1148  (uint) ((count->tree_pos - count->tree_buff) /
1149  count->field_length));
1150  }
1151  total_count= 0;
1152  for (idx= 0; idx < 256; idx++)
1153  {
1154  if (count->counts[idx])
1155  {
1156  total_count+= count->counts[idx];
1157  DBUG_PRINT("info", ("counts[0x%02x]: %12s", idx,
1158  llstr((longlong) count->counts[idx], llbuf)));
1159  if (verbose >= 2)
1160  printf("counts[0x%02x]: %12s\n", idx,
1161  llstr((longlong) count->counts[idx], llbuf));
1162  }
1163  }
1164  DBUG_PRINT("info", ("total: %12s", llstr((longlong) total_count,
1165  llbuf)));
1166  if ((verbose >= 2) && total_count)
1167  {
1168  printf("total: %12s\n",
1169  llstr((longlong) total_count, llbuf));
1170  }
1171  }
1172 
1173  mrg->records=record_count;
1174  mrg->max_blob_length=max_blob_length;
1175  my_afree((uchar*) record);
1176  DBUG_RETURN(error != HA_ERR_END_OF_FILE);
1177 }
1178 
1179 static int compare_huff_elements(void *not_used __attribute__((unused)),
1180  uchar *a, uchar *b)
1181 {
1182  return *((my_off_t*) a) < *((my_off_t*) b) ? -1 :
1183  (*((my_off_t*) a) == *((my_off_t*) b) ? 0 : 1);
1184 }
1185 
1186  /* Check each tree if we should use pre-space-compress, end-space-
1187  compress, empty-field-compress or zero-field-compress */
1188 
1189 static void check_counts(HUFF_COUNTS *huff_counts, uint trees,
1190  my_off_t records)
1191 {
1192  uint space_fields,fill_zero_fields,field_count[(int) FIELD_enum_val_count];
1193  my_off_t old_length,new_length,length;
1194  DBUG_ENTER("check_counts");
1195 
1196  memset(field_count, 0, sizeof(field_count));
1197  space_fields=fill_zero_fields=0;
1198 
1199  for (; trees-- ; huff_counts++)
1200  {
1201  if (huff_counts->field_type == FIELD_BLOB)
1202  {
1203  huff_counts->length_bits=max_bit(huff_counts->max_length);
1204  goto found_pack;
1205  }
1206  else if (huff_counts->field_type == FIELD_VARCHAR)
1207  {
1208  huff_counts->length_bits=max_bit(huff_counts->max_length);
1209  goto found_pack;
1210  }
1211  else if (huff_counts->field_type == FIELD_CHECK)
1212  {
1213  huff_counts->bytes_packed=0;
1214  huff_counts->counts[0]=0;
1215  goto found_pack;
1216  }
1217 
1218  huff_counts->field_type=FIELD_NORMAL;
1219  huff_counts->pack_type=0;
1220 
1221  /* Check for zero-filled records (in this column), or zero records. */
1222  if (huff_counts->zero_fields || ! records)
1223  {
1224  my_off_t old_space_count;
1225  /*
1226  If there are only zero filled records (in this column),
1227  or no records at all, we are done.
1228  */
1229  if (huff_counts->zero_fields == records)
1230  {
1231  huff_counts->field_type= FIELD_ZERO;
1232  huff_counts->bytes_packed=0;
1233  huff_counts->counts[0]=0;
1234  goto found_pack;
1235  }
1236  /* Remeber the number of significant spaces. */
1237  old_space_count=huff_counts->counts[' '];
1238  /* Add all leading and trailing spaces. */
1239  huff_counts->counts[' ']+= (huff_counts->tot_end_space +
1240  huff_counts->tot_pre_space +
1241  huff_counts->empty_fields *
1242  huff_counts->field_length);
1243  /* Check, what the compressed length of this would be. */
1244  old_length=calc_packed_length(huff_counts,0)+records/8;
1245  /* Get the number of zero bytes. */
1246  length=huff_counts->zero_fields*huff_counts->field_length;
1247  /* Add it to the counts. */
1248  huff_counts->counts[0]+=length;
1249  /* Check, what the compressed length of this would be. */
1250  new_length=calc_packed_length(huff_counts,0);
1251  /* If the compression without the zeroes would be shorter, we are done. */
1252  if (old_length < new_length && huff_counts->field_length > 1)
1253  {
1254  huff_counts->field_type=FIELD_SKIP_ZERO;
1255  huff_counts->counts[0]-=length;
1256  huff_counts->bytes_packed=old_length- records/8;
1257  goto found_pack;
1258  }
1259  /* Remove the insignificant spaces, but keep the zeroes. */
1260  huff_counts->counts[' ']=old_space_count;
1261  }
1262  /* Check, what the compressed length of this column would be. */
1263  huff_counts->bytes_packed=calc_packed_length(huff_counts,0);
1264 
1265  /*
1266  If there are enough empty records (in this column),
1267  treating them specially may pay off.
1268  */
1269  if (huff_counts->empty_fields)
1270  {
1271  if (huff_counts->field_length > 2 &&
1272  huff_counts->empty_fields + (records - huff_counts->empty_fields)*
1273  (1+max_bit(MY_MAX(huff_counts->max_pre_space,
1274  huff_counts->max_end_space))) <
1275  records * max_bit(huff_counts->field_length))
1276  {
1277  huff_counts->pack_type |= PACK_TYPE_SPACE_FIELDS;
1278  }
1279  else
1280  {
1281  length=huff_counts->empty_fields*huff_counts->field_length;
1282  if (huff_counts->tot_end_space || ! huff_counts->tot_pre_space)
1283  {
1284  huff_counts->tot_end_space+=length;
1285  huff_counts->max_end_space=huff_counts->field_length;
1286  if (huff_counts->field_length < 8)
1287  huff_counts->end_space[huff_counts->field_length]+=
1288  huff_counts->empty_fields;
1289  }
1290  if (huff_counts->tot_pre_space)
1291  {
1292  huff_counts->tot_pre_space+=length;
1293  huff_counts->max_pre_space=huff_counts->field_length;
1294  if (huff_counts->field_length < 8)
1295  huff_counts->pre_space[huff_counts->field_length]+=
1296  huff_counts->empty_fields;
1297  }
1298  }
1299  }
1300 
1301  /*
1302  If there are enough trailing spaces (in this column),
1303  treating them specially may pay off.
1304  */
1305  if (huff_counts->tot_end_space)
1306  {
1307  huff_counts->counts[' ']+=huff_counts->tot_pre_space;
1308  if (test_space_compress(huff_counts,records,huff_counts->max_end_space,
1309  huff_counts->end_space,
1310  huff_counts->tot_end_space,FIELD_SKIP_ENDSPACE))
1311  goto found_pack;
1312  huff_counts->counts[' ']-=huff_counts->tot_pre_space;
1313  }
1314 
1315  /*
1316  If there are enough leading spaces (in this column),
1317  treating them specially may pay off.
1318  */
1319  if (huff_counts->tot_pre_space)
1320  {
1321  if (test_space_compress(huff_counts,records,huff_counts->max_pre_space,
1322  huff_counts->pre_space,
1323  huff_counts->tot_pre_space,FIELD_SKIP_PRESPACE))
1324  goto found_pack;
1325  }
1326 
1327  found_pack: /* Found field-packing */
1328 
1329  /* Test if we can use zero-fill */
1330 
1331  if (huff_counts->max_zero_fill &&
1332  (huff_counts->field_type == FIELD_NORMAL ||
1333  huff_counts->field_type == FIELD_SKIP_ZERO))
1334  {
1335  huff_counts->counts[0]-=huff_counts->max_zero_fill*
1336  (huff_counts->field_type == FIELD_SKIP_ZERO ?
1337  records - huff_counts->zero_fields : records);
1338  huff_counts->pack_type|=PACK_TYPE_ZERO_FILL;
1339  huff_counts->bytes_packed=calc_packed_length(huff_counts,0);
1340  }
1341 
1342  /* Test if intervall-field is better */
1343 
1344  if (huff_counts->tree_buff)
1345  {
1346  HUFF_TREE tree;
1347 
1348  DBUG_EXECUTE_IF("forceintervall",
1349  huff_counts->bytes_packed= ~ (my_off_t) 0;);
1350  tree.element_buffer=0;
1351  if (!make_huff_tree(&tree,huff_counts) &&
1352  tree.bytes_packed+tree.tree_pack_length < huff_counts->bytes_packed)
1353  {
1354  if (tree.elements == 1)
1355  huff_counts->field_type=FIELD_CONSTANT;
1356  else
1357  huff_counts->field_type=FIELD_INTERVALL;
1358  huff_counts->pack_type=0;
1359  }
1360  else
1361  {
1362  my_free(huff_counts->tree_buff);
1363  delete_tree(&huff_counts->int_tree);
1364  huff_counts->tree_buff=0;
1365  }
1366  if (tree.element_buffer)
1367  my_free(tree.element_buffer);
1368  }
1369  if (huff_counts->pack_type & PACK_TYPE_SPACE_FIELDS)
1370  space_fields++;
1371  if (huff_counts->pack_type & PACK_TYPE_ZERO_FILL)
1372  fill_zero_fields++;
1373  field_count[huff_counts->field_type]++;
1374  }
1375  DBUG_PRINT("info", ("normal: %3d empty-space: %3d "
1376  "empty-zero: %3d empty-fill: %3d",
1377  field_count[FIELD_NORMAL],space_fields,
1378  field_count[FIELD_SKIP_ZERO],fill_zero_fields));
1379  DBUG_PRINT("info", ("pre-space: %3d end-space: %3d "
1380  "intervall-fields: %3d zero: %3d",
1381  field_count[FIELD_SKIP_PRESPACE],
1382  field_count[FIELD_SKIP_ENDSPACE],
1383  field_count[FIELD_INTERVALL],
1384  field_count[FIELD_ZERO]));
1385  if (verbose)
1386  printf("\nnormal: %3d empty-space: %3d "
1387  "empty-zero: %3d empty-fill: %3d\n"
1388  "pre-space: %3d end-space: %3d "
1389  "intervall-fields: %3d zero: %3d\n",
1390  field_count[FIELD_NORMAL],space_fields,
1391  field_count[FIELD_SKIP_ZERO],fill_zero_fields,
1392  field_count[FIELD_SKIP_PRESPACE],
1393  field_count[FIELD_SKIP_ENDSPACE],
1394  field_count[FIELD_INTERVALL],
1395  field_count[FIELD_ZERO]);
1396  DBUG_VOID_RETURN;
1397 }
1398 
1399  /* Test if we can use space-compression and empty-field-compression */
1400 
1401 static int
1402 test_space_compress(HUFF_COUNTS *huff_counts, my_off_t records,
1403  uint max_space_length, my_off_t *space_counts,
1404  my_off_t tot_space_count, enum en_fieldtype field_type)
1405 {
1406  int min_pos;
1407  uint length_bits,i;
1408  my_off_t space_count,min_space_count,min_pack,new_length,skip;
1409 
1410  length_bits=max_bit(max_space_length);
1411 
1412  /* Default no end_space-packing */
1413  space_count=huff_counts->counts[(uint) ' '];
1414  min_space_count= (huff_counts->counts[(uint) ' ']+= tot_space_count);
1415  min_pack=calc_packed_length(huff_counts,0);
1416  min_pos= -2;
1417  huff_counts->counts[(uint) ' ']=space_count;
1418 
1419  /* Test with allways space-count */
1420  new_length=huff_counts->bytes_packed+length_bits*records/8;
1421  if (new_length+1 < min_pack)
1422  {
1423  min_pos= -1;
1424  min_pack=new_length;
1425  min_space_count=space_count;
1426  }
1427  /* Test with length-flag */
1428  for (skip=0L, i=0 ; i < 8 ; i++)
1429  {
1430  if (space_counts[i])
1431  {
1432  if (i)
1433  huff_counts->counts[(uint) ' ']+=space_counts[i];
1434  skip+=huff_counts->pre_space[i];
1435  new_length=calc_packed_length(huff_counts,0)+
1436  (records+(records-skip)*(1+length_bits))/8;
1437  if (new_length < min_pack)
1438  {
1439  min_pos=(int) i;
1440  min_pack=new_length;
1441  min_space_count=huff_counts->counts[(uint) ' '];
1442  }
1443  }
1444  }
1445 
1446  huff_counts->counts[(uint) ' ']=min_space_count;
1447  huff_counts->bytes_packed=min_pack;
1448  switch (min_pos) {
1449  case -2:
1450  return(0); /* No space-compress */
1451  case -1: /* Always space-count */
1452  huff_counts->field_type=field_type;
1453  huff_counts->min_space=0;
1454  huff_counts->length_bits=max_bit(max_space_length);
1455  break;
1456  default:
1457  huff_counts->field_type=field_type;
1458  huff_counts->min_space=(uint) min_pos;
1459  huff_counts->pack_type|=PACK_TYPE_SELECTED;
1460  huff_counts->length_bits=max_bit(max_space_length);
1461  break;
1462  }
1463  return(1); /* Using space-compress */
1464 }
1465 
1466 
1467  /* Make a huff_tree of each huff_count */
1468 
1469 static HUFF_TREE* make_huff_trees(HUFF_COUNTS *huff_counts, uint trees)
1470 {
1471  uint tree;
1472  HUFF_TREE *huff_tree;
1473  DBUG_ENTER("make_huff_trees");
1474 
1475  if (!(huff_tree=(HUFF_TREE*) my_malloc(trees*sizeof(HUFF_TREE),
1476  MYF(MY_WME | MY_ZEROFILL))))
1477  DBUG_RETURN(0);
1478 
1479  for (tree=0 ; tree < trees ; tree++)
1480  {
1481  if (make_huff_tree(huff_tree+tree,huff_counts+tree))
1482  {
1483  while (tree--)
1484  my_free(huff_tree[tree].element_buffer);
1485  my_free(huff_tree);
1486  DBUG_RETURN(0);
1487  }
1488  }
1489  DBUG_RETURN(huff_tree);
1490 }
1491 
1492 /*
1493  Build a Huffman tree.
1494 
1495  SYNOPSIS
1496  make_huff_tree()
1497  huff_tree The Huffman tree.
1498  huff_counts The counts.
1499 
1500  DESCRIPTION
1501  Build a Huffman tree according to huff_counts->counts or
1502  huff_counts->tree_buff. tree_buff, if non-NULL contains up to
1503  tree_buff_length of distinct column values. In that case, whole
1504  values can be Huffman encoded instead of single bytes.
1505 
1506  RETURN
1507  0 OK
1508  != 0 Error
1509 */
1510 
1511 static int make_huff_tree(HUFF_TREE *huff_tree, HUFF_COUNTS *huff_counts)
1512 {
1513  uint i,found,bits_packed,first,last;
1514  my_off_t bytes_packed;
1515  HUFF_ELEMENT *a,*b,*new_huff_el;
1516 
1517  first=last=0;
1518  if (huff_counts->tree_buff)
1519  {
1520  /* Calculate the number of distinct values in tree_buff. */
1521  found= (uint) (huff_counts->tree_pos - huff_counts->tree_buff) /
1522  huff_counts->field_length;
1523  first=0; last=found-1;
1524  }
1525  else
1526  {
1527  /* Count the number of byte codes found in the column. */
1528  for (i=found=0 ; i < 256 ; i++)
1529  {
1530  if (huff_counts->counts[i])
1531  {
1532  if (! found++)
1533  first=i;
1534  last=i;
1535  }
1536  }
1537  if (found < 2)
1538  found=2;
1539  }
1540 
1541  /* When using 'tree_buff' we can have more that 256 values. */
1542  if (queue.max_elements < found)
1543  {
1544  delete_queue(&queue);
1545  if (init_queue(&queue,found,0,0,compare_huff_elements,0))
1546  return -1;
1547  }
1548 
1549  /* Allocate or reallocate an element buffer for the Huffman tree. */
1550  if (!huff_tree->element_buffer)
1551  {
1552  if (!(huff_tree->element_buffer=
1553  (HUFF_ELEMENT*) my_malloc(found*2*sizeof(HUFF_ELEMENT),MYF(MY_WME))))
1554  return 1;
1555  }
1556  else
1557  {
1558  HUFF_ELEMENT *temp;
1559  if (!(temp=
1560  (HUFF_ELEMENT*) my_realloc((uchar*) huff_tree->element_buffer,
1561  found*2*sizeof(HUFF_ELEMENT),
1562  MYF(MY_WME))))
1563  return 1;
1564  huff_tree->element_buffer=temp;
1565  }
1566 
1567  huff_counts->tree=huff_tree;
1568  huff_tree->counts=huff_counts;
1569  huff_tree->min_chr=first;
1570  huff_tree->max_chr=last;
1571  huff_tree->char_bits=max_bit(last-first);
1572  huff_tree->offset_bits=max_bit(found-1)+1;
1573 
1574  if (huff_counts->tree_buff)
1575  {
1576  huff_tree->elements=0;
1577  huff_tree->tree_pack_length=(1+15+16+5+5+
1578  (huff_tree->char_bits+1)*found+
1579  (huff_tree->offset_bits+1)*
1580  (found-2)+7)/8 +
1581  (uint) (huff_tree->counts->tree_pos-
1582  huff_tree->counts->tree_buff);
1583  /*
1584  Put a HUFF_ELEMENT into the queue for every distinct column value.
1585 
1586  tree_walk() calls save_counts_in_queue() for every element in
1587  'int_tree'. This takes elements from the target trees element
1588  buffer and places references to them into the buffer of the
1589  priority queue. We insert in column value order, but the order is
1590  in fact irrelevant here. We will establish the correct order
1591  later.
1592  */
1593  tree_walk(&huff_counts->int_tree,
1594  (int (*)(void*, element_count,void*)) save_counts_in_queue,
1595  (uchar*) huff_tree, left_root_right);
1596  }
1597  else
1598  {
1599  huff_tree->elements=found;
1600  huff_tree->tree_pack_length=(9+9+5+5+
1601  (huff_tree->char_bits+1)*found+
1602  (huff_tree->offset_bits+1)*
1603  (found-2)+7)/8;
1604  /*
1605  Put a HUFF_ELEMENT into the queue for every byte code found in the column.
1606 
1607  The elements are taken from the target trees element buffer.
1608  Instead of using queue_insert(), we just place references to the
1609  elements into the buffer of the priority queue. We insert in byte
1610  value order, but the order is in fact irrelevant here. We will
1611  establish the correct order later.
1612  */
1613  for (i=first, found=0 ; i <= last ; i++)
1614  {
1615  if (huff_counts->counts[i])
1616  {
1617  new_huff_el=huff_tree->element_buffer+(found++);
1618  new_huff_el->count=huff_counts->counts[i];
1619  new_huff_el->a.leaf.null=0;
1620  new_huff_el->a.leaf.element_nr=i;
1621  queue.root[found]=(uchar*) new_huff_el;
1622  }
1623  }
1624  /*
1625  If there is only a single byte value in this field in all records,
1626  add a second element with zero incidence. This is required to enter
1627  the loop, which builds the Huffman tree.
1628  */
1629  while (found < 2)
1630  {
1631  new_huff_el=huff_tree->element_buffer+(found++);
1632  new_huff_el->count=0;
1633  new_huff_el->a.leaf.null=0;
1634  if (last)
1635  new_huff_el->a.leaf.element_nr=huff_tree->min_chr=last-1;
1636  else
1637  new_huff_el->a.leaf.element_nr=huff_tree->max_chr=last+1;
1638  queue.root[found]=(uchar*) new_huff_el;
1639  }
1640  }
1641 
1642  /* Make a queue from the queue buffer. */
1643  queue.elements=found;
1644 
1645  /*
1646  Make a priority queue from the queue. Construct its index so that we
1647  have a partially ordered tree.
1648  */
1649  for (i=found/2 ; i > 0 ; i--)
1650  _downheap(&queue,i);
1651 
1652  /* The Huffman algorithm. */
1653  bytes_packed=0; bits_packed=0;
1654  for (i=1 ; i < found ; i++)
1655  {
1656  /*
1657  Pop the top element from the queue (the one with the least incidence).
1658  Popping from a priority queue includes a re-ordering of the queue,
1659  to get the next least incidence element to the top.
1660  */
1661  a=(HUFF_ELEMENT*) queue_remove(&queue,0);
1662  /*
1663  Copy the next least incidence element. The queue implementation
1664  reserves root[0] for temporary purposes. root[1] is the top.
1665  */
1666  b=(HUFF_ELEMENT*) queue.root[1];
1667  /* Get a new element from the element buffer. */
1668  new_huff_el=huff_tree->element_buffer+found+i;
1669  /* The new element gets the sum of the two least incidence elements. */
1670  new_huff_el->count=a->count+b->count;
1671  /*
1672  The Huffman algorithm assigns another bit to the code for a byte
1673  every time that bytes incidence is combined (directly or indirectly)
1674  to a new element as one of the two least incidence elements.
1675  This means that one more bit per incidence of that byte is required
1676  in the resulting file. So we add the new combined incidence as the
1677  number of bits by which the result grows.
1678  */
1679  bits_packed+=(uint) (new_huff_el->count & 7);
1680  bytes_packed+=new_huff_el->count/8;
1681  /* The new element points to its children, lesser in left. */
1682  new_huff_el->a.nod.left=a;
1683  new_huff_el->a.nod.right=b;
1684  /*
1685  Replace the copied top element by the new element and re-order the
1686  queue.
1687  */
1688  queue.root[1]=(uchar*) new_huff_el;
1689  queue_replaced(&queue);
1690  }
1691  huff_tree->root=(HUFF_ELEMENT*) queue.root[1];
1692  huff_tree->bytes_packed=bytes_packed+(bits_packed+7)/8;
1693  return 0;
1694 }
1695 
1696 static int compare_tree(void* cmp_arg __attribute__((unused)),
1697  register const uchar *s, register const uchar *t)
1698 {
1699  uint length;
1700  for (length=global_count->field_length; length-- ;)
1701  if (*s++ != *t++)
1702  return (int) s[-1] - (int) t[-1];
1703  return 0;
1704 }
1705 
1706 /*
1707  Organize distinct column values and their incidences into a priority queue.
1708 
1709  SYNOPSIS
1710  save_counts_in_queue()
1711  key The column value.
1712  count The incidence of this value.
1713  tree The Huffman tree to be built later.
1714 
1715  DESCRIPTION
1716  We use the element buffer of the targeted tree. The distinct column
1717  values are organized in a priority queue first. The Huffman
1718  algorithm will later organize the elements into a Huffman tree. For
1719  the time being, we just place references to the elements into the
1720  queue buffer. The buffer will later be organized into a priority
1721  queue.
1722 
1723  RETURN
1724  0
1725  */
1726 
1727 static int save_counts_in_queue(uchar *key, element_count count,
1728  HUFF_TREE *tree)
1729 {
1730  HUFF_ELEMENT *new_huff_el;
1731 
1732  new_huff_el=tree->element_buffer+(tree->elements++);
1733  new_huff_el->count=count;
1734  new_huff_el->a.leaf.null=0;
1735  new_huff_el->a.leaf.element_nr= (uint) (key- tree->counts->tree_buff) /
1736  tree->counts->field_length;
1737  queue.root[tree->elements]=(uchar*) new_huff_el;
1738  return 0;
1739 }
1740 
1741 
1742 /*
1743  Calculate length of file if given counts should be used.
1744 
1745  SYNOPSIS
1746  calc_packed_length()
1747  huff_counts The counts for a column of the table(s).
1748  add_tree_lenght If the decode tree length should be added.
1749 
1750  DESCRIPTION
1751  We need to follow the Huffman algorithm until we know, how many bits
1752  are required for each byte code. But we do not need the resulting
1753  Huffman tree. Hence, we can leave out some steps which are essential
1754  in make_huff_tree().
1755 
1756  RETURN
1757  Number of bytes required to compress this table column.
1758 */
1759 
1760 static my_off_t calc_packed_length(HUFF_COUNTS *huff_counts,
1761  uint add_tree_lenght)
1762 {
1763  uint i,found,bits_packed,first,last;
1764  my_off_t bytes_packed;
1765  HUFF_ELEMENT element_buffer[256];
1766  DBUG_ENTER("calc_packed_length");
1767 
1768  /*
1769  WARNING: We use a small hack for efficiency: Instead of placing
1770  references to HUFF_ELEMENTs into the queue, we just insert
1771  references to the counts of the byte codes which appeared in this
1772  table column. During the Huffman algorithm they are successively
1773  replaced by references to HUFF_ELEMENTs. This works, because
1774  HUFF_ELEMENTs have the incidence count at their beginning.
1775  Regardless, wether the queue array contains references to counts of
1776  type my_off_t or references to HUFF_ELEMENTs which have the count of
1777  type my_off_t at their beginning, it always points to a count of the
1778  same type.
1779 
1780  Instead of using queue_insert(), we just copy the references into
1781  the buffer of the priority queue. We insert in byte value order, but
1782  the order is in fact irrelevant here. We will establish the correct
1783  order later.
1784  */
1785  first=last=0;
1786  for (i=found=0 ; i < 256 ; i++)
1787  {
1788  if (huff_counts->counts[i])
1789  {
1790  if (! found++)
1791  first=i;
1792  last=i;
1793  /* We start with root[1], which is the queues top element. */
1794  queue.root[found]=(uchar*) &huff_counts->counts[i];
1795  }
1796  }
1797  if (!found)
1798  DBUG_RETURN(0); /* Empty tree */
1799  /*
1800  If there is only a single byte value in this field in all records,
1801  add a second element with zero incidence. This is required to enter
1802  the loop, which follows the Huffman algorithm.
1803  */
1804  if (found < 2)
1805  queue.root[++found]=(uchar*) &huff_counts->counts[last ? 0 : 1];
1806 
1807  /* Make a queue from the queue buffer. */
1808  queue.elements=found;
1809 
1810  bytes_packed=0; bits_packed=0;
1811  /* Add the length of the coding table, which would become part of the file. */
1812  if (add_tree_lenght)
1813  bytes_packed=(8+9+5+5+(max_bit(last-first)+1)*found+
1814  (max_bit(found-1)+1+1)*(found-2) +7)/8;
1815 
1816  /*
1817  Make a priority queue from the queue. Construct its index so that we
1818  have a partially ordered tree.
1819  */
1820  for (i=(found+1)/2 ; i > 0 ; i--)
1821  _downheap(&queue,i);
1822 
1823  /* The Huffman algorithm. */
1824  for (i=0 ; i < found-1 ; i++)
1825  {
1826  my_off_t *a;
1827  my_off_t *b;
1828  HUFF_ELEMENT *new_huff_el;
1829 
1830  /*
1831  Pop the top element from the queue (the one with the least
1832  incidence). Popping from a priority queue includes a re-ordering
1833  of the queue, to get the next least incidence element to the top.
1834  */
1835  a= (my_off_t*) queue_remove(&queue, 0);
1836  /*
1837  Copy the next least incidence element. The queue implementation
1838  reserves root[0] for temporary purposes. root[1] is the top.
1839  */
1840  b= (my_off_t*) queue.root[1];
1841  /* Create a new element in a local (automatic) buffer. */
1842  new_huff_el= element_buffer + i;
1843  /* The new element gets the sum of the two least incidence elements. */
1844  new_huff_el->count= *a + *b;
1845  /*
1846  The Huffman algorithm assigns another bit to the code for a byte
1847  every time that bytes incidence is combined (directly or indirectly)
1848  to a new element as one of the two least incidence elements.
1849  This means that one more bit per incidence of that byte is required
1850  in the resulting file. So we add the new combined incidence as the
1851  number of bits by which the result grows.
1852  */
1853  bits_packed+=(uint) (new_huff_el->count & 7);
1854  bytes_packed+=new_huff_el->count/8;
1855  /*
1856  Replace the copied top element by the new element and re-order the
1857  queue. This successively replaces the references to counts by
1858  references to HUFF_ELEMENTs.
1859  */
1860  queue.root[1]=(uchar*) new_huff_el;
1861  queue_replaced(&queue);
1862  }
1863  DBUG_RETURN(bytes_packed+(bits_packed+7)/8);
1864 }
1865 
1866 
1867  /* Remove trees that don't give any compression */
1868 
1869 static uint join_same_trees(HUFF_COUNTS *huff_counts, uint trees)
1870 {
1871  uint k,tree_number;
1872  HUFF_COUNTS count,*i,*j,*last_count;
1873 
1874  last_count=huff_counts+trees;
1875  for (tree_number=0, i=huff_counts ; i < last_count ; i++)
1876  {
1877  if (!i->tree->tree_number)
1878  {
1879  i->tree->tree_number= ++tree_number;
1880  if (i->tree_buff)
1881  continue; /* Don't join intervall */
1882  for (j=i+1 ; j < last_count ; j++)
1883  {
1884  if (! j->tree->tree_number && ! j->tree_buff)
1885  {
1886  for (k=0 ; k < 256 ; k++)
1887  count.counts[k]=i->counts[k]+j->counts[k];
1888  if (calc_packed_length(&count,1) <=
1889  i->tree->bytes_packed + j->tree->bytes_packed+
1890  i->tree->tree_pack_length+j->tree->tree_pack_length+
1891  ALLOWED_JOIN_DIFF)
1892  {
1893  memcpy(i->counts, count.counts,
1894  sizeof(count.counts[0])*256);
1895  my_free(j->tree->element_buffer);
1896  j->tree->element_buffer=0;
1897  j->tree=i->tree;
1898  bmove((uchar*) i->counts,(uchar*) count.counts,
1899  sizeof(count.counts[0])*256);
1900  if (make_huff_tree(i->tree,i))
1901  return (uint) -1;
1902  }
1903  }
1904  }
1905  }
1906  }
1907  DBUG_PRINT("info", ("Original trees: %d After join: %d",
1908  trees, tree_number));
1909  if (verbose)
1910  printf("Original trees: %d After join: %d\n", trees, tree_number);
1911  return tree_number; /* Return trees left */
1912 }
1913 
1914 
1915 /*
1916  Fill in huff_tree encode tables.
1917 
1918  SYNOPSIS
1919  make_huff_decode_table()
1920  huff_tree An array of HUFF_TREE which are to be encoded.
1921  trees The number of HUFF_TREE in the array.
1922 
1923  RETURN
1924  0 success
1925  != 0 error
1926 */
1927 
1928 static int make_huff_decode_table(HUFF_TREE *huff_tree, uint trees)
1929 {
1930  uint elements;
1931  for ( ; trees-- ; huff_tree++)
1932  {
1933  if (huff_tree->tree_number > 0)
1934  {
1935  elements=huff_tree->counts->tree_buff ? huff_tree->elements : 256;
1936  if (!(huff_tree->code =
1937  (ulonglong*) my_malloc(elements*
1938  (sizeof(ulonglong) + sizeof(uchar)),
1939  MYF(MY_WME | MY_ZEROFILL))))
1940  return 1;
1941  huff_tree->code_len=(uchar*) (huff_tree->code+elements);
1942  make_traverse_code_tree(huff_tree, huff_tree->root,
1943  8 * sizeof(ulonglong), LL(0));
1944  }
1945  }
1946  return 0;
1947 }
1948 
1949 
1950 static void make_traverse_code_tree(HUFF_TREE *huff_tree,
1951  HUFF_ELEMENT *element,
1952  uint size, ulonglong code)
1953 {
1954  uint chr;
1955  if (!element->a.leaf.null)
1956  {
1957  chr=element->a.leaf.element_nr;
1958  huff_tree->code_len[chr]= (uchar) (8 * sizeof(ulonglong) - size);
1959  huff_tree->code[chr]= (code >> size);
1960  if (huff_tree->height < 8 * sizeof(ulonglong) - size)
1961  huff_tree->height= 8 * sizeof(ulonglong) - size;
1962  }
1963  else
1964  {
1965  size--;
1966  make_traverse_code_tree(huff_tree,element->a.nod.left,size,code);
1967  make_traverse_code_tree(huff_tree, element->a.nod.right, size,
1968  code + (((ulonglong) 1) << size));
1969  }
1970  return;
1971 }
1972 
1973 
1974 /*
1975  Convert a value into binary digits.
1976 
1977  SYNOPSIS
1978  bindigits()
1979  value The value.
1980  length The number of low order bits to convert.
1981 
1982  NOTE
1983  The result string is in static storage. It is reused on every call.
1984  So you cannot use it twice in one expression.
1985 
1986  RETURN
1987  A pointer to a static NUL-terminated string.
1988  */
1989 
1990 static char *bindigits(ulonglong value, uint bits)
1991 {
1992  static char digits[72];
1993  char *ptr= digits;
1994  uint idx= bits;
1995 
1996  DBUG_ASSERT(idx < sizeof(digits));
1997  while (idx)
1998  *(ptr++)= '0' + ((char) (value >> (--idx)) & (char) 1);
1999  *ptr= '\0';
2000  return digits;
2001 }
2002 
2003 
2004 /*
2005  Convert a value into hexadecimal digits.
2006 
2007  SYNOPSIS
2008  hexdigits()
2009  value The value.
2010 
2011  NOTE
2012  The result string is in static storage. It is reused on every call.
2013  So you cannot use it twice in one expression.
2014 
2015  RETURN
2016  A pointer to a static NUL-terminated string.
2017  */
2018 
2019 static char *hexdigits(ulonglong value)
2020 {
2021  static char digits[20];
2022  char *ptr= digits;
2023  uint idx= 2 * sizeof(value); /* Two hex digits per byte. */
2024 
2025  DBUG_ASSERT(idx < sizeof(digits));
2026  while (idx)
2027  {
2028  if ((*(ptr++)= '0' + ((char) (value >> (4 * (--idx))) & (char) 0xf)) > '9')
2029  *(ptr - 1)+= 'a' - '9' - 1;
2030  }
2031  *ptr= '\0';
2032  return digits;
2033 }
2034 
2035 
2036  /* Write header to new packed data file */
2037 
2038 static int write_header(PACK_MRG_INFO *mrg,uint head_length,uint trees,
2039  my_off_t tot_elements,my_off_t filelength)
2040 {
2041  uchar *buff= (uchar*) file_buffer.pos;
2042 
2043  memset(buff, 0, HEAD_LENGTH);
2044  memcpy(buff,myisam_pack_file_magic,4);
2045  int4store(buff+4,head_length);
2046  int4store(buff+8, mrg->min_pack_length);
2047  int4store(buff+12,mrg->max_pack_length);
2048  int4store(buff+16,tot_elements);
2049  int4store(buff+20,intervall_length);
2050  int2store(buff+24,trees);
2051  buff[26]=(char) mrg->ref_length;
2052  /* Save record pointer length */
2053  buff[27]= (uchar) mi_get_pointer_length((ulonglong) filelength,2);
2054  if (test_only)
2055  return 0;
2056  my_seek(file_buffer.file,0L,MY_SEEK_SET,MYF(0));
2057  return my_write(file_buffer.file,(const uchar *) file_buffer.pos,HEAD_LENGTH,
2058  MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)) != 0;
2059 }
2060 
2061  /* Write fieldinfo to new packed file */
2062 
2063 static void write_field_info(HUFF_COUNTS *counts, uint fields, uint trees)
2064 {
2065  reg1 uint i;
2066  uint huff_tree_bits;
2067  huff_tree_bits=max_bit(trees ? trees-1 : 0);
2068 
2069  DBUG_PRINT("info", (" "));
2070  DBUG_PRINT("info", ("column types:"));
2071  DBUG_PRINT("info", ("FIELD_NORMAL 0"));
2072  DBUG_PRINT("info", ("FIELD_SKIP_ENDSPACE 1"));
2073  DBUG_PRINT("info", ("FIELD_SKIP_PRESPACE 2"));
2074  DBUG_PRINT("info", ("FIELD_SKIP_ZERO 3"));
2075  DBUG_PRINT("info", ("FIELD_BLOB 4"));
2076  DBUG_PRINT("info", ("FIELD_CONSTANT 5"));
2077  DBUG_PRINT("info", ("FIELD_INTERVALL 6"));
2078  DBUG_PRINT("info", ("FIELD_ZERO 7"));
2079  DBUG_PRINT("info", ("FIELD_VARCHAR 8"));
2080  DBUG_PRINT("info", ("FIELD_CHECK 9"));
2081  DBUG_PRINT("info", (" "));
2082  DBUG_PRINT("info", ("pack type as a set of flags:"));
2083  DBUG_PRINT("info", ("PACK_TYPE_SELECTED 1"));
2084  DBUG_PRINT("info", ("PACK_TYPE_SPACE_FIELDS 2"));
2085  DBUG_PRINT("info", ("PACK_TYPE_ZERO_FILL 4"));
2086  DBUG_PRINT("info", (" "));
2087  if (verbose >= 2)
2088  {
2089  printf("\n");
2090  printf("column types:\n");
2091  printf("FIELD_NORMAL 0\n");
2092  printf("FIELD_SKIP_ENDSPACE 1\n");
2093  printf("FIELD_SKIP_PRESPACE 2\n");
2094  printf("FIELD_SKIP_ZERO 3\n");
2095  printf("FIELD_BLOB 4\n");
2096  printf("FIELD_CONSTANT 5\n");
2097  printf("FIELD_INTERVALL 6\n");
2098  printf("FIELD_ZERO 7\n");
2099  printf("FIELD_VARCHAR 8\n");
2100  printf("FIELD_CHECK 9\n");
2101  printf("\n");
2102  printf("pack type as a set of flags:\n");
2103  printf("PACK_TYPE_SELECTED 1\n");
2104  printf("PACK_TYPE_SPACE_FIELDS 2\n");
2105  printf("PACK_TYPE_ZERO_FILL 4\n");
2106  printf("\n");
2107  }
2108  for (i=0 ; i++ < fields ; counts++)
2109  {
2110  write_bits((ulonglong) (int) counts->field_type, 5);
2111  write_bits(counts->pack_type,6);
2112  if (counts->pack_type & PACK_TYPE_ZERO_FILL)
2113  write_bits(counts->max_zero_fill,5);
2114  else
2115  write_bits(counts->length_bits,5);
2116  write_bits((ulonglong) counts->tree->tree_number - 1, huff_tree_bits);
2117  DBUG_PRINT("info", ("column: %3u type: %2u pack: %2u zero: %4u "
2118  "lbits: %2u tree: %2u length: %4u",
2119  i , counts->field_type, counts->pack_type,
2120  counts->max_zero_fill, counts->length_bits,
2121  counts->tree->tree_number, counts->field_length));
2122  if (verbose >= 2)
2123  printf("column: %3u type: %2u pack: %2u zero: %4u lbits: %2u "
2124  "tree: %2u length: %4u\n", i , counts->field_type,
2125  counts->pack_type, counts->max_zero_fill, counts->length_bits,
2126  counts->tree->tree_number, counts->field_length);
2127  }
2128  flush_bits();
2129  return;
2130 }
2131 
2132  /* Write all huff_trees to new datafile. Return tot count of
2133  elements in all trees
2134  Returns 0 on error */
2135 
2136 static my_off_t write_huff_tree(HUFF_TREE *huff_tree, uint trees)
2137 {
2138  uint i,int_length;
2139  uint tree_no;
2140  uint codes;
2141  uint errors= 0;
2142  uint *packed_tree,*offset,length;
2143  my_off_t elements;
2144 
2145  /* Find the highest number of elements in the trees. */
2146  for (i=length=0 ; i < trees ; i++)
2147  if (huff_tree[i].tree_number > 0 && huff_tree[i].elements > length)
2148  length=huff_tree[i].elements;
2149  /*
2150  Allocate a buffer for packing a decode tree. Two numbers per element
2151  (left child and right child).
2152  */
2153  if (!(packed_tree=(uint*) my_alloca(sizeof(uint)*length*2)))
2154  {
2155  my_error(EE_OUTOFMEMORY, MYF(ME_BELL+ME_FATALERROR),
2156  sizeof(uint)*length*2);
2157  return 0;
2158  }
2159 
2160  DBUG_PRINT("info", (" "));
2161  if (verbose >= 2)
2162  printf("\n");
2163  tree_no= 0;
2164  intervall_length=0;
2165  for (elements=0; trees-- ; huff_tree++)
2166  {
2167  /* Skip columns that have been joined with other columns. */
2168  if (huff_tree->tree_number == 0)
2169  continue; /* Deleted tree */
2170  tree_no++;
2171  DBUG_PRINT("info", (" "));
2172  if (verbose >= 3)
2173  printf("\n");
2174  /* Count the total number of elements (byte codes or column values). */
2175  elements+=huff_tree->elements;
2176  huff_tree->max_offset=2;
2177  /* Build a tree of offsets and codes for decoding in 'packed_tree'. */
2178  if (huff_tree->elements <= 1)
2179  offset=packed_tree;
2180  else
2181  offset=make_offset_code_tree(huff_tree,huff_tree->root,packed_tree);
2182 
2183  /* This should be the same as 'length' above. */
2184  huff_tree->offset_bits=max_bit(huff_tree->max_offset);
2185 
2186  /*
2187  Since we check this during collecting the distinct column values,
2188  this should never happen.
2189  */
2190  if (huff_tree->max_offset >= IS_OFFSET)
2191  { /* This should be impossible */
2192  (void) fprintf(stderr, "Tree offset got too big: %d, aborted\n",
2193  huff_tree->max_offset);
2194  my_afree((uchar*) packed_tree);
2195  return 0;
2196  }
2197 
2198  DBUG_PRINT("info", ("pos: %lu elements: %u tree-elements: %lu "
2199  "char_bits: %u\n",
2200  (ulong) (file_buffer.pos - file_buffer.buffer),
2201  huff_tree->elements, (ulong) (offset - packed_tree),
2202  huff_tree->char_bits));
2203  if (!huff_tree->counts->tree_buff)
2204  {
2205  /* We do a byte compression on this column. Mark with bit 0. */
2206  write_bits(0,1);
2207  write_bits(huff_tree->min_chr,8);
2208  write_bits(huff_tree->elements,9);
2209  write_bits(huff_tree->char_bits,5);
2210  write_bits(huff_tree->offset_bits,5);
2211  int_length=0;
2212  }
2213  else
2214  {
2215  int_length=(uint) (huff_tree->counts->tree_pos -
2216  huff_tree->counts->tree_buff);
2217  /* We have distinct column values for this column. Mark with bit 1. */
2218  write_bits(1,1);
2219  write_bits(huff_tree->elements,15);
2220  write_bits(int_length,16);
2221  write_bits(huff_tree->char_bits,5);
2222  write_bits(huff_tree->offset_bits,5);
2223  intervall_length+=int_length;
2224  }
2225  DBUG_PRINT("info", ("tree: %2u elements: %4u char_bits: %2u "
2226  "offset_bits: %2u %s: %5u codelen: %2u",
2227  tree_no, huff_tree->elements, huff_tree->char_bits,
2228  huff_tree->offset_bits, huff_tree->counts->tree_buff ?
2229  "bufflen" : "min_chr", huff_tree->counts->tree_buff ?
2230  int_length : huff_tree->min_chr, huff_tree->height));
2231  if (verbose >= 2)
2232  printf("tree: %2u elements: %4u char_bits: %2u offset_bits: %2u "
2233  "%s: %5u codelen: %2u\n", tree_no, huff_tree->elements,
2234  huff_tree->char_bits, huff_tree->offset_bits,
2235  huff_tree->counts->tree_buff ? "bufflen" : "min_chr",
2236  huff_tree->counts->tree_buff ? int_length :
2237  huff_tree->min_chr, huff_tree->height);
2238 
2239  /* Check that the code tree length matches the element count. */
2240  length=(uint) (offset-packed_tree);
2241  if (length != huff_tree->elements*2-2)
2242  {
2243  (void) fprintf(stderr, "error: Huff-tree-length: %d != calc_length: %d\n",
2244  length, huff_tree->elements * 2 - 2);
2245  errors++;
2246  break;
2247  }
2248 
2249  for (i=0 ; i < length ; i++)
2250  {
2251  if (packed_tree[i] & IS_OFFSET)
2252  write_bits(packed_tree[i] - IS_OFFSET+ (1 << huff_tree->offset_bits),
2253  huff_tree->offset_bits+1);
2254  else
2255  write_bits(packed_tree[i]-huff_tree->min_chr,huff_tree->char_bits+1);
2256  DBUG_PRINT("info", ("tree[0x%04x]: %s0x%04x",
2257  i, (packed_tree[i] & IS_OFFSET) ?
2258  " -> " : "", (packed_tree[i] & IS_OFFSET) ?
2259  packed_tree[i] - IS_OFFSET + i : packed_tree[i]));
2260  if (verbose >= 3)
2261  printf("tree[0x%04x]: %s0x%04x\n",
2262  i, (packed_tree[i] & IS_OFFSET) ? " -> " : "",
2263  (packed_tree[i] & IS_OFFSET) ?
2264  packed_tree[i] - IS_OFFSET + i : packed_tree[i]);
2265  }
2266  flush_bits();
2267 
2268  /*
2269  Display coding tables and check their correctness.
2270  */
2271  codes= huff_tree->counts->tree_buff ? huff_tree->elements : 256;
2272  for (i= 0; i < codes; i++)
2273  {
2274  ulonglong code;
2275  uint bits;
2276  uint len;
2277  uint idx;
2278 
2279  if (! (len= huff_tree->code_len[i]))
2280  continue;
2281  DBUG_PRINT("info", ("code[0x%04x]: 0x%s bits: %2u bin: %s", i,
2282  hexdigits(huff_tree->code[i]), huff_tree->code_len[i],
2283  bindigits(huff_tree->code[i],
2284  huff_tree->code_len[i])));
2285  if (verbose >= 3)
2286  printf("code[0x%04x]: 0x%s bits: %2u bin: %s\n", i,
2287  hexdigits(huff_tree->code[i]), huff_tree->code_len[i],
2288  bindigits(huff_tree->code[i], huff_tree->code_len[i]));
2289 
2290  /* Check that the encode table decodes correctly. */
2291  code= 0;
2292  bits= 0;
2293  idx= 0;
2294  DBUG_EXECUTE_IF("forcechkerr1", len--;);
2295  DBUG_EXECUTE_IF("forcechkerr2", bits= 8 * sizeof(code););
2296  DBUG_EXECUTE_IF("forcechkerr3", idx= length;);
2297  for (;;)
2298  {
2299  if (! len)
2300  {
2301  (void) fflush(stdout);
2302  (void) fprintf(stderr, "error: code 0x%s with %u bits not found\n",
2303  hexdigits(huff_tree->code[i]), huff_tree->code_len[i]);
2304  errors++;
2305  break;
2306  }
2307  code<<= 1;
2308  code|= (huff_tree->code[i] >> (--len)) & 1;
2309  bits++;
2310  if (bits > 8 * sizeof(code))
2311  {
2312  (void) fflush(stdout);
2313  (void) fprintf(stderr, "error: Huffman code too long: %u/%u\n",
2314  bits, (uint) (8 * sizeof(code)));
2315  errors++;
2316  break;
2317  }
2318  idx+= (uint) code & 1;
2319  if (idx >= length)
2320  {
2321  (void) fflush(stdout);
2322  (void) fprintf(stderr, "error: illegal tree offset: %u/%u\n",
2323  idx, length);
2324  errors++;
2325  break;
2326  }
2327  if (packed_tree[idx] & IS_OFFSET)
2328  idx+= packed_tree[idx] & ~IS_OFFSET;
2329  else
2330  break; /* Hit a leaf. This contains the result value. */
2331  }
2332  if (errors)
2333  break;
2334 
2335  DBUG_EXECUTE_IF("forcechkerr4", packed_tree[idx]++;);
2336  if (packed_tree[idx] != i)
2337  {
2338  (void) fflush(stdout);
2339  (void) fprintf(stderr, "error: decoded value 0x%04x should be: 0x%04x\n",
2340  packed_tree[idx], i);
2341  errors++;
2342  break;
2343  }
2344  } /*end for (codes)*/
2345  if (errors)
2346  break;
2347 
2348  /* Write column values in case of distinct column value compression. */
2349  if (huff_tree->counts->tree_buff)
2350  {
2351  for (i=0 ; i < int_length ; i++)
2352  {
2353  write_bits((ulonglong) (uchar) huff_tree->counts->tree_buff[i], 8);
2354  DBUG_PRINT("info", ("column_values[0x%04x]: 0x%02x",
2355  i, (uchar) huff_tree->counts->tree_buff[i]));
2356  if (verbose >= 3)
2357  printf("column_values[0x%04x]: 0x%02x\n",
2358  i, (uchar) huff_tree->counts->tree_buff[i]);
2359  }
2360  }
2361  flush_bits();
2362  }
2363  DBUG_PRINT("info", (" "));
2364  if (verbose >= 2)
2365  printf("\n");
2366  my_afree((uchar*) packed_tree);
2367  if (errors)
2368  {
2369  (void) fprintf(stderr, "Error: Generated decode trees are corrupt. Stop.\n");
2370  return 0;
2371  }
2372  return elements;
2373 }
2374 
2375 
2376 static uint *make_offset_code_tree(HUFF_TREE *huff_tree, HUFF_ELEMENT *element,
2377  uint *offset)
2378 {
2379  uint *prev_offset;
2380 
2381  prev_offset= offset;
2382  /*
2383  'a.leaf.null' takes the same place as 'a.nod.left'. If this is null,
2384  then there is no left child and, hence no right child either. This
2385  is a property of a binary tree. An element is either a node with two
2386  childs, or a leaf without childs.
2387 
2388  The current element is always a node with two childs. Go left first.
2389  */
2390  if (!element->a.nod.left->a.leaf.null)
2391  {
2392  /* Store the byte code or the index of the column value. */
2393  prev_offset[0] =(uint) element->a.nod.left->a.leaf.element_nr;
2394  offset+=2;
2395  }
2396  else
2397  {
2398  /*
2399  Recursively traverse the tree to the left. Mark it as an offset to
2400  another tree node (in contrast to a byte code or column value index).
2401  */
2402  prev_offset[0]= IS_OFFSET+2;
2403  offset=make_offset_code_tree(huff_tree,element->a.nod.left,offset+2);
2404  }
2405 
2406  /* Now, check the right child. */
2407  if (!element->a.nod.right->a.leaf.null)
2408  {
2409  /* Store the byte code or the index of the column value. */
2410  prev_offset[1]=element->a.nod.right->a.leaf.element_nr;
2411  return offset;
2412  }
2413  else
2414  {
2415  /*
2416  Recursively traverse the tree to the right. Mark it as an offset to
2417  another tree node (in contrast to a byte code or column value index).
2418  */
2419  uint temp=(uint) (offset-prev_offset-1);
2420  prev_offset[1]= IS_OFFSET+ temp;
2421  if (huff_tree->max_offset < temp)
2422  huff_tree->max_offset = temp;
2423  return make_offset_code_tree(huff_tree,element->a.nod.right,offset);
2424  }
2425 }
2426 
2427  /* Get number of bits neaded to represent value */
2428 
2429 static uint max_bit(register uint value)
2430 {
2431  reg2 uint power=1;
2432 
2433  while ((value>>=1))
2434  power++;
2435  return (power);
2436 }
2437 
2438 
2439 static int compress_isam_file(PACK_MRG_INFO *mrg, HUFF_COUNTS *huff_counts)
2440 {
2441  int error;
2442  uint i,max_calc_length,pack_ref_length,min_record_length,max_record_length,
2443  intervall,field_length,max_pack_length,pack_blob_length;
2444  my_off_t record_count;
2445  char llbuf[32];
2446  ulong length,pack_length;
2447  uchar *record,*pos,*end_pos,*record_pos,*start_pos;
2448  HUFF_COUNTS *count,*end_count;
2449  HUFF_TREE *tree;
2450  MI_INFO *isam_file=mrg->file[0];
2451  uint pack_version= (uint) isam_file->s->pack.version;
2452  DBUG_ENTER("compress_isam_file");
2453 
2454  /* Allocate a buffer for the records (excluding blobs). */
2455  if (!(record=(uchar*) my_alloca(isam_file->s->base.reclength)))
2456  return -1;
2457 
2458  end_count=huff_counts+isam_file->s->base.fields;
2459  min_record_length= (uint) ~0;
2460  max_record_length=0;
2461 
2462  /*
2463  Calculate the maximum number of bits required to pack the records.
2464  Remember to understand 'max_zero_fill' as 'min_zero_fill'.
2465  The tree height determines the maximum number of bits per value.
2466  Some fields skip leading or trailing spaces or zeroes. The skipped
2467  number of bytes is encoded by 'length_bits' bits.
2468  Empty blobs and varchar are encoded with a single 1 bit. Other blobs
2469  and varchar get a leading 0 bit.
2470  */
2471  for (i=max_calc_length=0 ; i < isam_file->s->base.fields ; i++)
2472  {
2473  if (!(huff_counts[i].pack_type & PACK_TYPE_ZERO_FILL))
2474  huff_counts[i].max_zero_fill=0;
2475  if (huff_counts[i].field_type == FIELD_CONSTANT ||
2476  huff_counts[i].field_type == FIELD_ZERO ||
2477  huff_counts[i].field_type == FIELD_CHECK)
2478  continue;
2479  if (huff_counts[i].field_type == FIELD_INTERVALL)
2480  max_calc_length+=huff_counts[i].tree->height;
2481  else if (huff_counts[i].field_type == FIELD_BLOB ||
2482  huff_counts[i].field_type == FIELD_VARCHAR)
2483  max_calc_length+=huff_counts[i].tree->height*huff_counts[i].max_length + huff_counts[i].length_bits +1;
2484  else
2485  max_calc_length+=
2486  (huff_counts[i].field_length - huff_counts[i].max_zero_fill)*
2487  huff_counts[i].tree->height+huff_counts[i].length_bits;
2488  }
2489  max_calc_length= (max_calc_length + 7) / 8;
2490  pack_ref_length= calc_pack_length(pack_version, max_calc_length);
2491  record_count=0;
2492  /* 'max_blob_length' is the max length of all blobs of a record. */
2493  pack_blob_length= isam_file->s->base.blobs ?
2494  calc_pack_length(pack_version, mrg->max_blob_length) : 0;
2495  max_pack_length=pack_ref_length+pack_blob_length;
2496 
2497  DBUG_PRINT("fields", ("==="));
2498  mrg_reset(mrg);
2499  while ((error=mrg_rrnd(mrg,record)) != HA_ERR_END_OF_FILE)
2500  {
2501  ulong tot_blob_length=0;
2502  if (! error)
2503  {
2504  if (flush_buffer((ulong) max_calc_length + (ulong) max_pack_length))
2505  break;
2506  record_pos= (uchar*) file_buffer.pos;
2507  file_buffer.pos+=max_pack_length;
2508  for (start_pos=record, count= huff_counts; count < end_count ; count++)
2509  {
2510  end_pos=start_pos+(field_length=count->field_length);
2511  tree=count->tree;
2512 
2513  DBUG_PRINT("fields", ("column: %3lu type: %2u pack: %2u zero: %4u "
2514  "lbits: %2u tree: %2u length: %4u",
2515  (ulong) (count - huff_counts + 1),
2516  count->field_type,
2517  count->pack_type, count->max_zero_fill,
2518  count->length_bits, count->tree->tree_number,
2519  count->field_length));
2520 
2521  /* Check if the column contains spaces only. */
2522  if (count->pack_type & PACK_TYPE_SPACE_FIELDS)
2523  {
2524  for (pos=start_pos ; *pos == ' ' && pos < end_pos; pos++) ;
2525  if (pos == end_pos)
2526  {
2527  DBUG_PRINT("fields",
2528  ("PACK_TYPE_SPACE_FIELDS spaces only, bits: 1"));
2529  DBUG_PRINT("fields", ("---"));
2530  write_bits(1,1);
2531  start_pos=end_pos;
2532  continue;
2533  }
2534  DBUG_PRINT("fields",
2535  ("PACK_TYPE_SPACE_FIELDS not only spaces, bits: 1"));
2536  write_bits(0,1);
2537  }
2538  end_pos-=count->max_zero_fill;
2539  field_length-=count->max_zero_fill;
2540 
2541  switch (count->field_type) {
2542  case FIELD_SKIP_ZERO:
2543  if (!memcmp((uchar*) start_pos,zero_string,field_length))
2544  {
2545  DBUG_PRINT("fields", ("FIELD_SKIP_ZERO zeroes only, bits: 1"));
2546  write_bits(1,1);
2547  start_pos=end_pos;
2548  break;
2549  }
2550  DBUG_PRINT("fields", ("FIELD_SKIP_ZERO not only zeroes, bits: 1"));
2551  write_bits(0,1);
2552  /* Fall through */
2553  case FIELD_NORMAL:
2554  DBUG_PRINT("fields", ("FIELD_NORMAL %lu bytes",
2555  (ulong) (end_pos - start_pos)));
2556  for ( ; start_pos < end_pos ; start_pos++)
2557  {
2558  DBUG_PRINT("fields",
2559  ("value: 0x%02x code: 0x%s bits: %2u bin: %s",
2560  (uchar) *start_pos,
2561  hexdigits(tree->code[(uchar) *start_pos]),
2562  (uint) tree->code_len[(uchar) *start_pos],
2563  bindigits(tree->code[(uchar) *start_pos],
2564  (uint) tree->code_len[(uchar) *start_pos])));
2565  write_bits(tree->code[(uchar) *start_pos],
2566  (uint) tree->code_len[(uchar) *start_pos]);
2567  }
2568  break;
2569  case FIELD_SKIP_ENDSPACE:
2570  for (pos=end_pos ; pos > start_pos && pos[-1] == ' ' ; pos--) ;
2571  length= (ulong) (end_pos - pos);
2572  if (count->pack_type & PACK_TYPE_SELECTED)
2573  {
2574  if (length > count->min_space)
2575  {
2576  DBUG_PRINT("fields",
2577  ("FIELD_SKIP_ENDSPACE more than min_space, bits: 1"));
2578  DBUG_PRINT("fields",
2579  ("FIELD_SKIP_ENDSPACE skip %lu/%u bytes, bits: %2u",
2580  length, field_length, count->length_bits));
2581  write_bits(1,1);
2582  write_bits(length,count->length_bits);
2583  }
2584  else
2585  {
2586  DBUG_PRINT("fields",
2587  ("FIELD_SKIP_ENDSPACE not more than min_space, "
2588  "bits: 1"));
2589  write_bits(0,1);
2590  pos=end_pos;
2591  }
2592  }
2593  else
2594  {
2595  DBUG_PRINT("fields",
2596  ("FIELD_SKIP_ENDSPACE skip %lu/%u bytes, bits: %2u",
2597  length, field_length, count->length_bits));
2598  write_bits(length,count->length_bits);
2599  }
2600  /* Encode all significant bytes. */
2601  DBUG_PRINT("fields", ("FIELD_SKIP_ENDSPACE %lu bytes",
2602  (ulong) (pos - start_pos)));
2603  for ( ; start_pos < pos ; start_pos++)
2604  {
2605  DBUG_PRINT("fields",
2606  ("value: 0x%02x code: 0x%s bits: %2u bin: %s",
2607  (uchar) *start_pos,
2608  hexdigits(tree->code[(uchar) *start_pos]),
2609  (uint) tree->code_len[(uchar) *start_pos],
2610  bindigits(tree->code[(uchar) *start_pos],
2611  (uint) tree->code_len[(uchar) *start_pos])));
2612  write_bits(tree->code[(uchar) *start_pos],
2613  (uint) tree->code_len[(uchar) *start_pos]);
2614  }
2615  start_pos=end_pos;
2616  break;
2617  case FIELD_SKIP_PRESPACE:
2618  for (pos=start_pos ; pos < end_pos && pos[0] == ' ' ; pos++) ;
2619  length= (ulong) (pos - start_pos);
2620  if (count->pack_type & PACK_TYPE_SELECTED)
2621  {
2622  if (length > count->min_space)
2623  {
2624  DBUG_PRINT("fields",
2625  ("FIELD_SKIP_PRESPACE more than min_space, bits: 1"));
2626  DBUG_PRINT("fields",
2627  ("FIELD_SKIP_PRESPACE skip %lu/%u bytes, bits: %2u",
2628  length, field_length, count->length_bits));
2629  write_bits(1,1);
2630  write_bits(length,count->length_bits);
2631  }
2632  else
2633  {
2634  DBUG_PRINT("fields",
2635  ("FIELD_SKIP_PRESPACE not more than min_space, "
2636  "bits: 1"));
2637  pos=start_pos;
2638  write_bits(0,1);
2639  }
2640  }
2641  else
2642  {
2643  DBUG_PRINT("fields",
2644  ("FIELD_SKIP_PRESPACE skip %lu/%u bytes, bits: %2u",
2645  length, field_length, count->length_bits));
2646  write_bits(length,count->length_bits);
2647  }
2648  /* Encode all significant bytes. */
2649  DBUG_PRINT("fields", ("FIELD_SKIP_PRESPACE %lu bytes",
2650  (ulong) (end_pos - start_pos)));
2651  for (start_pos=pos ; start_pos < end_pos ; start_pos++)
2652  {
2653  DBUG_PRINT("fields",
2654  ("value: 0x%02x code: 0x%s bits: %2u bin: %s",
2655  (uchar) *start_pos,
2656  hexdigits(tree->code[(uchar) *start_pos]),
2657  (uint) tree->code_len[(uchar) *start_pos],
2658  bindigits(tree->code[(uchar) *start_pos],
2659  (uint) tree->code_len[(uchar) *start_pos])));
2660  write_bits(tree->code[(uchar) *start_pos],
2661  (uint) tree->code_len[(uchar) *start_pos]);
2662  }
2663  break;
2664  case FIELD_CONSTANT:
2665  case FIELD_ZERO:
2666  case FIELD_CHECK:
2667  DBUG_PRINT("fields", ("FIELD_CONSTANT/ZERO/CHECK"));
2668  start_pos=end_pos;
2669  break;
2670  case FIELD_INTERVALL:
2671  global_count=count;
2672  pos=(uchar*) tree_search(&count->int_tree, start_pos,
2673  count->int_tree.custom_arg);
2674  intervall=(uint) (pos - count->tree_buff)/field_length;
2675  DBUG_PRINT("fields", ("FIELD_INTERVALL"));
2676  DBUG_PRINT("fields", ("index: %4u code: 0x%s bits: %2u",
2677  intervall, hexdigits(tree->code[intervall]),
2678  (uint) tree->code_len[intervall]));
2679  write_bits(tree->code[intervall],(uint) tree->code_len[intervall]);
2680  start_pos=end_pos;
2681  break;
2682  case FIELD_BLOB:
2683  {
2684  ulong blob_length=_mi_calc_blob_length(field_length-
2685  portable_sizeof_char_ptr,
2686  start_pos);
2687  /* Empty blobs are encoded with a single 1 bit. */
2688  if (!blob_length)
2689  {
2690  DBUG_PRINT("fields", ("FIELD_BLOB empty, bits: 1"));
2691  write_bits(1,1);
2692  }
2693  else
2694  {
2695  uchar *blob,*blob_end;
2696  DBUG_PRINT("fields", ("FIELD_BLOB not empty, bits: 1"));
2697  write_bits(0,1);
2698  /* Write the blob length. */
2699  DBUG_PRINT("fields", ("FIELD_BLOB %lu bytes, bits: %2u",
2700  blob_length, count->length_bits));
2701  write_bits(blob_length,count->length_bits);
2702  memcpy(&blob, end_pos-portable_sizeof_char_ptr, sizeof(char*));
2703  blob_end=blob+blob_length;
2704  /* Encode the blob bytes. */
2705  for ( ; blob < blob_end ; blob++)
2706  {
2707  DBUG_PRINT("fields",
2708  ("value: 0x%02x code: 0x%s bits: %2u bin: %s",
2709  (uchar) *blob, hexdigits(tree->code[(uchar) *blob]),
2710  (uint) tree->code_len[(uchar) *blob],
2711  bindigits(tree->code[(uchar) *start_pos],
2712  (uint)tree->code_len[(uchar) *start_pos])));
2713  write_bits(tree->code[(uchar) *blob],
2714  (uint) tree->code_len[(uchar) *blob]);
2715  }
2716  tot_blob_length+=blob_length;
2717  }
2718  start_pos= end_pos;
2719  break;
2720  }
2721  case FIELD_VARCHAR:
2722  {
2723  uint var_pack_length= HA_VARCHAR_PACKLENGTH(count->field_length-1);
2724  ulong col_length= (var_pack_length == 1 ?
2725  (uint) *(uchar*) start_pos :
2726  uint2korr(start_pos));
2727  /* Empty varchar are encoded with a single 1 bit. */
2728  if (!col_length)
2729  {
2730  DBUG_PRINT("fields", ("FIELD_VARCHAR empty, bits: 1"));
2731  write_bits(1,1); /* Empty varchar */
2732  }
2733  else
2734  {
2735  uchar *end= start_pos + var_pack_length + col_length;
2736  DBUG_PRINT("fields", ("FIELD_VARCHAR not empty, bits: 1"));
2737  write_bits(0,1);
2738  /* Write the varchar length. */
2739  DBUG_PRINT("fields", ("FIELD_VARCHAR %lu bytes, bits: %2u",
2740  col_length, count->length_bits));
2741  write_bits(col_length,count->length_bits);
2742  /* Encode the varchar bytes. */
2743  for (start_pos+= var_pack_length ; start_pos < end ; start_pos++)
2744  {
2745  DBUG_PRINT("fields",
2746  ("value: 0x%02x code: 0x%s bits: %2u bin: %s",
2747  (uchar) *start_pos,
2748  hexdigits(tree->code[(uchar) *start_pos]),
2749  (uint) tree->code_len[(uchar) *start_pos],
2750  bindigits(tree->code[(uchar) *start_pos],
2751  (uint)tree->code_len[(uchar) *start_pos])));
2752  write_bits(tree->code[(uchar) *start_pos],
2753  (uint) tree->code_len[(uchar) *start_pos]);
2754  }
2755  }
2756  start_pos= end_pos;
2757  break;
2758  }
2759  case FIELD_LAST:
2760  case FIELD_enum_val_count:
2761  abort(); /* Impossible */
2762  }
2763  start_pos+=count->max_zero_fill;
2764  DBUG_PRINT("fields", ("---"));
2765  }
2766  flush_bits();
2767  length=(ulong) ((uchar*) file_buffer.pos - record_pos) - max_pack_length;
2768  pack_length= save_pack_length(pack_version, record_pos, length);
2769  if (pack_blob_length)
2770  pack_length+= save_pack_length(pack_version, record_pos + pack_length,
2771  tot_blob_length);
2772  DBUG_PRINT("fields", ("record: %lu length: %lu blob-length: %lu "
2773  "length-bytes: %lu", (ulong) record_count, length,
2774  tot_blob_length, pack_length));
2775  DBUG_PRINT("fields", ("==="));
2776 
2777  /* Correct file buffer if the header was smaller */
2778  if (pack_length != max_pack_length)
2779  {
2780  bmove(record_pos+pack_length,record_pos+max_pack_length,length);
2781  file_buffer.pos-= (max_pack_length-pack_length);
2782  }
2783  if (length < (ulong) min_record_length)
2784  min_record_length=(uint) length;
2785  if (length > (ulong) max_record_length)
2786  max_record_length=(uint) length;
2787  record_count++;
2788  if (write_loop && record_count % WRITE_COUNT == 0)
2789  {
2790  printf("%lu\r", (ulong) record_count);
2791  (void) fflush(stdout);
2792  }
2793  }
2794  else if (error != HA_ERR_RECORD_DELETED)
2795  break;
2796  }
2797  if (error == HA_ERR_END_OF_FILE)
2798  error=0;
2799  else
2800  {
2801  (void) fprintf(stderr, "%s: Got error %d reading records\n",
2802  my_progname, error);
2803  }
2804  if (verbose >= 2)
2805  printf("wrote %s records.\n", llstr((longlong) record_count, llbuf));
2806 
2807  my_afree((uchar*) record);
2808  mrg->ref_length=max_pack_length;
2809  mrg->min_pack_length=max_record_length ? min_record_length : 0;
2810  mrg->max_pack_length=max_record_length;
2811  DBUG_RETURN(error || error_on_write || flush_buffer(~(ulong) 0));
2812 }
2813 
2814 
2815 static char *make_new_name(char *new_name, char *old_name)
2816 {
2817  return fn_format(new_name,old_name,"",DATA_TMP_EXT,2+4);
2818 }
2819 
2820 static char *make_old_name(char *new_name, char *old_name)
2821 {
2822  return fn_format(new_name,old_name,"",OLD_EXT,2+4);
2823 }
2824 
2825  /* rutines for bit writing buffer */
2826 
2827 static void init_file_buffer(File file, pbool read_buffer)
2828 {
2829  file_buffer.file=file;
2830  file_buffer.buffer= (uchar*) my_malloc(ALIGN_SIZE(RECORD_CACHE_SIZE),
2831  MYF(MY_WME));
2832  file_buffer.end=file_buffer.buffer+ALIGN_SIZE(RECORD_CACHE_SIZE)-8;
2833  file_buffer.pos_in_file=0;
2834  error_on_write=0;
2835  if (read_buffer)
2836  {
2837 
2838  file_buffer.pos=file_buffer.end;
2839  file_buffer.bits=0;
2840  }
2841  else
2842  {
2843  file_buffer.pos=file_buffer.buffer;
2844  file_buffer.bits=BITS_SAVED;
2845  }
2846  file_buffer.bitbucket= 0;
2847 }
2848 
2849 
2850 static int flush_buffer(ulong neaded_length)
2851 {
2852  ulong length;
2853 
2854  /*
2855  file_buffer.end is 8 bytes lower than the real end of the buffer.
2856  This is done so that the end-of-buffer condition does not need to be
2857  checked for every byte (see write_bits()). Consequently,
2858  file_buffer.pos can become greater than file_buffer.end. The
2859  algorithms in the other functions ensure that there will never be
2860  more than 8 bytes written to the buffer without an end-of-buffer
2861  check. So the buffer cannot be overrun. But we need to check for the
2862  near-to-buffer-end condition to avoid a negative result, which is
2863  casted to unsigned and thus becomes giant.
2864  */
2865  if ((file_buffer.pos < file_buffer.end) &&
2866  ((ulong) (file_buffer.end - file_buffer.pos) > neaded_length))
2867  return 0;
2868  length=(ulong) (file_buffer.pos-file_buffer.buffer);
2869  file_buffer.pos=file_buffer.buffer;
2870  file_buffer.pos_in_file+=length;
2871  if (test_only)
2872  return 0;
2873  if (error_on_write|| my_write(file_buffer.file,
2874  (const uchar*) file_buffer.buffer,
2875  length,
2876  MYF(MY_WME | MY_NABP | MY_WAIT_IF_FULL)))
2877  {
2878  error_on_write=1;
2879  return 1;
2880  }
2881 
2882  if (neaded_length != ~(ulong) 0 &&
2883  (ulong) (file_buffer.end-file_buffer.buffer) < neaded_length)
2884  {
2885  char *tmp;
2886  neaded_length+=256; /* some margin */
2887  tmp= my_realloc((char*) file_buffer.buffer, neaded_length,MYF(MY_WME));
2888  if (!tmp)
2889  return 1;
2890  file_buffer.pos= ((uchar*) tmp +
2891  (ulong) (file_buffer.pos - file_buffer.buffer));
2892  file_buffer.buffer= (uchar*) tmp;
2893  file_buffer.end= (uchar*) (tmp+neaded_length-8);
2894  }
2895  return 0;
2896 }
2897 
2898 
2899 static void end_file_buffer(void)
2900 {
2901  my_free(file_buffer.buffer);
2902 }
2903 
2904  /* output `bits` low bits of `value' */
2905 
2906 static void write_bits(register ulonglong value, register uint bits)
2907 {
2908  DBUG_ASSERT(((bits < 8 * sizeof(value)) && ! (value >> bits)) ||
2909  (bits == 8 * sizeof(value)));
2910 
2911  if ((file_buffer.bits-= (int) bits) >= 0)
2912  {
2913  file_buffer.bitbucket|= value << file_buffer.bits;
2914  }
2915  else
2916  {
2917  reg3 ulonglong bit_buffer;
2918  bits= (uint) -file_buffer.bits;
2919  bit_buffer= (file_buffer.bitbucket |
2920  ((bits != 8 * sizeof(value)) ? (value >> bits) : 0));
2921 #if BITS_SAVED == 64
2922  *file_buffer.pos++= (uchar) (bit_buffer >> 56);
2923  *file_buffer.pos++= (uchar) (bit_buffer >> 48);
2924  *file_buffer.pos++= (uchar) (bit_buffer >> 40);
2925  *file_buffer.pos++= (uchar) (bit_buffer >> 32);
2926 #endif
2927  *file_buffer.pos++= (uchar) (bit_buffer >> 24);
2928  *file_buffer.pos++= (uchar) (bit_buffer >> 16);
2929  *file_buffer.pos++= (uchar) (bit_buffer >> 8);
2930  *file_buffer.pos++= (uchar) (bit_buffer);
2931 
2932  if (bits != 8 * sizeof(value))
2933  value&= (((ulonglong) 1) << bits) - 1;
2934  if (file_buffer.pos >= file_buffer.end)
2935  (void) flush_buffer(~ (ulong) 0);
2936  file_buffer.bits=(int) (BITS_SAVED - bits);
2937  file_buffer.bitbucket= value << (BITS_SAVED - bits);
2938  }
2939  return;
2940 }
2941 
2942  /* Flush bits in bit_buffer to buffer */
2943 
2944 static void flush_bits(void)
2945 {
2946  int bits;
2947  ulonglong bit_buffer;
2948 
2949  bits= file_buffer.bits & ~7;
2950  bit_buffer= file_buffer.bitbucket >> bits;
2951  bits= BITS_SAVED - bits;
2952  while (bits > 0)
2953  {
2954  bits-= 8;
2955  *file_buffer.pos++= (uchar) (bit_buffer >> bits);
2956  }
2957  if (file_buffer.pos >= file_buffer.end)
2958  (void) flush_buffer(~ (ulong) 0);
2959  file_buffer.bits= BITS_SAVED;
2960  file_buffer.bitbucket= 0;
2961 }
2962 
2963 
2964 /****************************************************************************
2965 ** functions to handle the joined files
2966 ****************************************************************************/
2967 
2968 static int save_state(MI_INFO *isam_file,PACK_MRG_INFO *mrg,my_off_t new_length,
2969  ha_checksum crc)
2970 {
2971  MYISAM_SHARE *share=isam_file->s;
2972  uint options=mi_uint2korr(share->state.header.options);
2973  uint key;
2974  DBUG_ENTER("save_state");
2975 
2976  options|= HA_OPTION_COMPRESS_RECORD | HA_OPTION_READ_ONLY_DATA;
2977  mi_int2store(share->state.header.options,options);
2978 
2979  share->state.state.data_file_length=new_length;
2980  share->state.state.del=0;
2981  share->state.state.empty=0;
2982  share->state.dellink= HA_OFFSET_ERROR;
2983  share->state.split=(ha_rows) mrg->records;
2984  share->state.version=(ulong) time((time_t*) 0);
2985  if (! mi_is_all_keys_active(share->state.key_map, share->base.keys))
2986  {
2987  /*
2988  Some indexes are disabled, cannot use current key_file_length value
2989  as an estimate of upper bound of index file size. Use packed data file
2990  size instead.
2991  */
2992  share->state.state.key_file_length= new_length;
2993  }
2994  /*
2995  If there are no disabled indexes, keep key_file_length value from
2996  original file so "myisamchk -rq" can use this value (this is necessary
2997  because index size cannot be easily calculated for fulltext keys)
2998  */
2999  mi_clear_all_keys_active(share->state.key_map);
3000  for (key=0 ; key < share->base.keys ; key++)
3001  share->state.key_root[key]= HA_OFFSET_ERROR;
3002  for (key=0 ; key < share->state.header.max_block_size_index ; key++)
3003  share->state.key_del[key]= HA_OFFSET_ERROR;
3004  isam_file->state->checksum=crc; /* Save crc here */
3005  share->changed=1; /* Force write of header */
3006  share->state.open_count=0;
3007  share->global_changed=0;
3008  (void) my_chsize(share->kfile, share->base.keystart, 0, MYF(0));
3009  if (share->base.keys)
3010  isamchk_neaded=1;
3011  DBUG_RETURN(mi_state_info_write(share->kfile,&share->state,1+2));
3012 }
3013 
3014 
3015 static int save_state_mrg(File file,PACK_MRG_INFO *mrg,my_off_t new_length,
3016  ha_checksum crc)
3017 {
3018  MI_STATE_INFO state;
3019  MI_INFO *isam_file=mrg->file[0];
3020  uint options;
3021  DBUG_ENTER("save_state_mrg");
3022 
3023  state= isam_file->s->state;
3024  options= (mi_uint2korr(state.header.options) | HA_OPTION_COMPRESS_RECORD |
3025  HA_OPTION_READ_ONLY_DATA);
3026  mi_int2store(state.header.options,options);
3027  state.state.data_file_length=new_length;
3028  state.state.del=0;
3029  state.state.empty=0;
3030  state.state.records=state.split=(ha_rows) mrg->records;
3031  /* See comment above in save_state about key_file_length handling. */
3032  if (mrg->src_file_has_indexes_disabled)
3033  {
3034  isam_file->s->state.state.key_file_length=
3035  MY_MAX(isam_file->s->state.state.key_file_length, new_length);
3036  }
3037  state.dellink= HA_OFFSET_ERROR;
3038  state.version=(ulong) time((time_t*) 0);
3039  mi_clear_all_keys_active(state.key_map);
3040  state.state.checksum=crc;
3041  if (isam_file->s->base.keys)
3042  isamchk_neaded=1;
3043  state.changed=STATE_CHANGED | STATE_NOT_ANALYZED; /* Force check of table */
3044  DBUG_RETURN (mi_state_info_write(file,&state,1+2));
3045 }
3046 
3047 
3048 /* reset for mrg_rrnd */
3049 
3050 static void mrg_reset(PACK_MRG_INFO *mrg)
3051 {
3052  if (mrg->current)
3053  {
3054  mi_extra(*mrg->current, HA_EXTRA_NO_CACHE, 0);
3055  mrg->current=0;
3056  }
3057 }
3058 
3059 static int mrg_rrnd(PACK_MRG_INFO *info,uchar *buf)
3060 {
3061  int error;
3062  MI_INFO *isam_info;
3063  my_off_t filepos;
3064 
3065  if (!info->current)
3066  {
3067  isam_info= *(info->current=info->file);
3068  info->end=info->current+info->count;
3069  mi_reset(isam_info);
3070  mi_extra(isam_info, HA_EXTRA_CACHE, 0);
3071  filepos=isam_info->s->pack.header_length;
3072  }
3073  else
3074  {
3075  isam_info= *info->current;
3076  filepos= isam_info->nextpos;
3077  }
3078 
3079  for (;;)
3080  {
3081  isam_info->update&= HA_STATE_CHANGED;
3082  if (!(error=(*isam_info->s->read_rnd)(isam_info,(uchar*) buf,
3083  filepos, 1)) ||
3084  error != HA_ERR_END_OF_FILE)
3085  return (error);
3086  mi_extra(isam_info,HA_EXTRA_NO_CACHE, 0);
3087  if (info->current+1 == info->end)
3088  return(HA_ERR_END_OF_FILE);
3089  info->current++;
3090  isam_info= *info->current;
3091  filepos=isam_info->s->pack.header_length;
3092  mi_reset(isam_info);
3093  mi_extra(isam_info,HA_EXTRA_CACHE, 0);
3094  }
3095 }
3096 
3097 
3098 static int mrg_close(PACK_MRG_INFO *mrg)
3099 {
3100  uint i;
3101  int error=0;
3102  for (i=0 ; i < mrg->count ; i++)
3103  error|=mi_close(mrg->file[i]);
3104  if (mrg->free_file)
3105  my_free(mrg->file);
3106  return error;
3107 }
3108 
3109 
3110 #if !defined(DBUG_OFF)
3111 /*
3112  Fake the counts to get big Huffman codes.
3113 
3114  SYNOPSIS
3115  fakebigcodes()
3116  huff_counts A pointer to the counts array.
3117  end_count A pointer past the counts array.
3118 
3119  DESCRIPTION
3120 
3121  Huffman coding works by removing the two least frequent values from
3122  the list of values and add a new value with the sum of their
3123  incidences in a loop until only one value is left. Every time a
3124  value is reused for a new value, it gets one more bit for its
3125  encoding. Hence, the least frequent values get the longest codes.
3126 
3127  To get a maximum code length for a value, two of the values must
3128  have an incidence of 1. As their sum is 2, the next infrequent value
3129  must have at least an incidence of 2, then 4, 8, 16 and so on. This
3130  means that one needs 2**n bytes (values) for a code length of n
3131  bits. However, using more distinct values forces the use of longer
3132  codes, or reaching the code length with less total bytes (values).
3133 
3134  To get 64(32)-bit codes, I sort the counts by decreasing incidence.
3135  I assign counts of 1 to the two most frequent values, a count of 2
3136  for the next one, then 4, 8, and so on until 2**64-1(2**30-1). All
3137  the remaining values get 1. That way every possible byte has an
3138  assigned code, though not all codes are used if not all byte values
3139  are present in the column.
3140 
3141  This strategy would work with distinct column values too, but
3142  requires that at least 64(32) values are present. To make things
3143  easier here, I cancel all distinct column values and force byte
3144  compression for all columns.
3145 
3146  RETURN
3147  void
3148 */
3149 
3150 static void fakebigcodes(HUFF_COUNTS *huff_counts, HUFF_COUNTS *end_count)
3151 {
3152  HUFF_COUNTS *count;
3153  my_off_t *cur_count_p;
3154  my_off_t *end_count_p;
3155  my_off_t **cur_sort_p;
3156  my_off_t **end_sort_p;
3157  my_off_t *sort_counts[256];
3158  my_off_t total;
3159  DBUG_ENTER("fakebigcodes");
3160 
3161  for (count= huff_counts; count < end_count; count++)
3162  {
3163  /*
3164  Remove distinct column values.
3165  */
3166  if (huff_counts->tree_buff)
3167  {
3168  my_free(huff_counts->tree_buff);
3169  delete_tree(&huff_counts->int_tree);
3170  huff_counts->tree_buff= NULL;
3171  DBUG_PRINT("fakebigcodes", ("freed distinct column values"));
3172  }
3173 
3174  /*
3175  Sort counts by decreasing incidence.
3176  */
3177  cur_count_p= count->counts;
3178  end_count_p= cur_count_p + 256;
3179  cur_sort_p= sort_counts;
3180  while (cur_count_p < end_count_p)
3181  *(cur_sort_p++)= cur_count_p++;
3182  (void) my_qsort(sort_counts, 256, sizeof(my_off_t*), (qsort_cmp) fakecmp);
3183 
3184  /*
3185  Assign faked counts.
3186  */
3187  cur_sort_p= sort_counts;
3188 #if SIZEOF_LONG_LONG > 4
3189  end_sort_p= sort_counts + 8 * sizeof(ulonglong) - 1;
3190 #else
3191  end_sort_p= sort_counts + 8 * sizeof(ulonglong) - 2;
3192 #endif
3193  /* Most frequent value gets a faked count of 1. */
3194  **(cur_sort_p++)= 1;
3195  total= 1;
3196  while (cur_sort_p < end_sort_p)
3197  {
3198  **(cur_sort_p++)= total;
3199  total<<= 1;
3200  }
3201  /* Set the last value. */
3202  **(cur_sort_p++)= --total;
3203  /*
3204  Set the remaining counts.
3205  */
3206  end_sort_p= sort_counts + 256;
3207  while (cur_sort_p < end_sort_p)
3208  **(cur_sort_p++)= 1;
3209  }
3210  DBUG_VOID_RETURN;
3211 }
3212 
3213 
3214 /*
3215  Compare two counts for reverse sorting.
3216 
3217  SYNOPSIS
3218  fakecmp()
3219  count1 One count.
3220  count2 Another count.
3221 
3222  RETURN
3223  1 count1 < count2
3224  0 count1 == count2
3225  -1 count1 > count2
3226 */
3227 
3228 static int fakecmp(my_off_t **count1, my_off_t **count2)
3229 {
3230  return ((**count1 < **count2) ? 1 :
3231  (**count1 > **count2) ? -1 : 0);
3232 }
3233 #endif
3234 
3235 #include "mi_extrafunc.h"