home *** CD-ROM | disk | FTP | other *** search
/ Chip 2004 March / CMCD0304.ISO / Software / Freeware / Programare / nullsoft / nsis20.exe / Source / bzip2 / blocksort.c next >
C/C++ Source or Header  |  2003-07-12  |  32KB  |  1,097 lines

  1. #include "bzlib.h"
  2.  
  3. #if (defined(NSIS_COMPRESS_USE_BZIP2) && defined(NSIS_CONFIG_COMPRESSION_SUPPORT)) || !defined(EXEHEAD)
  4. /*-------------------------------------------------------------*/
  5. /*--- Block sorting machinery                               ---*/
  6. /*---                                           blocksort.c ---*/
  7. /*-------------------------------------------------------------*/
  8.  
  9. /*--
  10.   This file is a part of bzip2 and/or libbzip2, a program and
  11.   library for lossless, block-sorting data compression.
  12.  
  13.   Copyright (C) 1996-2000 Julian R Seward.  All rights reserved.
  14.  
  15.   Redistribution and use in source and binary forms, with or without
  16.   modification, are permitted provided that the following conditions
  17.   are met:
  18.  
  19.   1. Redistributions of source code must retain the above copyright
  20.      notice, this list of conditions and the following disclaimer.
  21.  
  22.   2. The origin of this software must not be misrepresented; you must 
  23.      not claim that you wrote the original software.  If you use this 
  24.      software in a product, an acknowledgment in the product 
  25.      documentation would be appreciated but is not required.
  26.  
  27.   3. Altered source versions must be plainly marked as such, and must
  28.      not be misrepresented as being the original software.
  29.  
  30.   4. The name of the author may not be used to endorse or promote 
  31.      products derived from this software without specific prior written 
  32.      permission.
  33.  
  34.   THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
  35.   OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  36.   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  37.   ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
  38.   DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  39.   DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
  40.   GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  41.   INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
  42.   WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  43.   NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  44.   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  45.  
  46.   Julian Seward, Cambridge, UK.
  47.   jseward@acm.org
  48.   bzip2/libbzip2 version 1.0 of 21 March 2000
  49.  
  50.   This program is based on (at least) the work of:
  51.      Mike Burrows
  52.      David Wheeler
  53.      Peter Fenwick
  54.      Alistair Moffat
  55.      Radford Neal
  56.      Ian H. Witten
  57.      Robert Sedgewick
  58.      Jon L. Bentley
  59.  
  60.   For more information on these sources, see the manual.
  61.  
  62.   To get some idea how the block sorting algorithms in this file 
  63.   work, read my paper 
  64.      On the Performance of BWT Sorting Algorithms
  65.   in Proceedings of the IEEE Data Compression Conference 2000,
  66.   Snowbird, Utah, USA, 27-30 March 2000.  The main sort in this
  67.   file implements the algorithm called  cache  in the paper.
  68. --*/
  69.  
  70. /*---------------------------------------------*/
  71. /*--- Fallback O(N log(N)^2) sorting        ---*/
  72. /*--- algorithm, for repetitive blocks      ---*/
  73. /*---------------------------------------------*/
  74.  
  75. /*---------------------------------------------*/
  76. static void fallbackSimpleSort ( UInt32* fmap, 
  77.                           UInt32* eclass, 
  78.                           Int32   lo, 
  79.                           Int32   hi )
  80. {
  81.    Int32 i, j, tmp;
  82.    UInt32 ec_tmp;
  83.  
  84.    if (lo == hi) return;
  85.  
  86.    if (hi - lo > 3) {
  87.       for ( i = hi-4; i >= lo; i-- ) {
  88.          tmp = fmap[i];
  89.          ec_tmp = eclass[tmp];
  90.          for ( j = i+4; j <= hi && ec_tmp > eclass[fmap[j]]; j += 4 )
  91.             fmap[j-4] = fmap[j];
  92.          fmap[j-4] = tmp;
  93.       }
  94.    }
  95.  
  96.    for ( i = hi-1; i >= lo; i-- ) {
  97.       tmp = fmap[i];
  98.       ec_tmp = eclass[tmp];
  99.       for ( j = i+1; j <= hi && ec_tmp > eclass[fmap[j]]; j++ )
  100.          fmap[j-1] = fmap[j];
  101.       fmap[j-1] = tmp;
  102.    }
  103. }
  104.  
  105.  
  106. /*---------------------------------------------*/
  107. #define fswap(zz1, zz2) \
  108.    { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }
  109.  
  110. #define fvswap(zzp1, zzp2, zzn)       \
  111. {                                     \
  112.    Int32 yyp1 = (zzp1);               \
  113.    Int32 yyp2 = (zzp2);               \
  114.    Int32 yyn  = (zzn);                \
  115.    while (yyn > 0) {                  \
  116.       fswap(fmap[yyp1], fmap[yyp2]);  \
  117.       yyp1++; yyp2++; yyn--;          \
  118.    }                                  \
  119. }
  120.  
  121.  
  122. #define fmin(a,b) ((a) < (b)) ? (a) : (b)
  123.  
  124. #define fpush(lz,hz) { stackLo[sp] = lz; \
  125.                        stackHi[sp] = hz; \
  126.                        sp++; }
  127.  
  128. #define fpop(lz,hz) { sp--;              \
  129.                       lz = stackLo[sp];  \
  130.                       hz = stackHi[sp]; }
  131.  
  132. #define FALLBACK_QSORT_SMALL_THRESH 10
  133. #define FALLBACK_QSORT_STACK_SIZE   100
  134.  
  135.  
  136. static
  137. void fallbackQSort3 ( UInt32* fmap, 
  138.                       UInt32* eclass,
  139.                       Int32   loSt, 
  140.                       Int32   hiSt )
  141. {
  142.    Int32 unLo, unHi, ltLo, gtHi, n, m;
  143.    Int32 sp, lo, hi;
  144.    UInt32 med, r, r3;
  145.    Int32 stackLo[FALLBACK_QSORT_STACK_SIZE];
  146.    Int32 stackHi[FALLBACK_QSORT_STACK_SIZE];
  147.  
  148.    r = 0;
  149.  
  150.    sp = 0;
  151.    fpush ( loSt, hiSt );
  152.  
  153.    while (sp > 0) {
  154.  
  155.       AssertH ( sp < FALLBACK_QSORT_STACK_SIZE, 1004 );
  156.  
  157.       fpop ( lo, hi );
  158.       if (hi - lo < FALLBACK_QSORT_SMALL_THRESH) {
  159.          fallbackSimpleSort ( fmap, eclass, lo, hi );
  160.          continue;
  161.       }
  162.  
  163.       /* Random partitioning.  Median of 3 sometimes fails to
  164.          avoid bad cases.  Median of 9 seems to help but 
  165.          looks rather expensive.  This too seems to work but
  166.          is cheaper.  Guidance for the magic constants 
  167.          7621 and 32768 is taken from Sedgewick's algorithms
  168.          book, chapter 35.
  169.       */
  170.       r = ((r * 7621) + 1) % 32768;
  171.       r3 = r % 3;
  172.       if (r3 == 0) med = eclass[fmap[lo]]; else
  173.       if (r3 == 1) med = eclass[fmap[(lo+hi)>>1]]; else
  174.                    med = eclass[fmap[hi]];
  175.  
  176.       unLo = ltLo = lo;
  177.       unHi = gtHi = hi;
  178.  
  179.       while (1) {
  180.          while (1) {
  181.             if (unLo > unHi) break;
  182.             n = (Int32)eclass[fmap[unLo]] - (Int32)med;
  183.             if (n == 0) { 
  184.                fswap(fmap[unLo], fmap[ltLo]); 
  185.                ltLo++; unLo++; 
  186.                continue; 
  187.             };
  188.             if (n > 0) break;
  189.             unLo++;
  190.          }
  191.          while (1) {
  192.             if (unLo > unHi) break;
  193.             n = (Int32)eclass[fmap[unHi]] - (Int32)med;
  194.             if (n == 0) { 
  195.                fswap(fmap[unHi], fmap[gtHi]); 
  196.                gtHi--; unHi--; 
  197.                continue; 
  198.             };
  199.             if (n < 0) break;
  200.             unHi--;
  201.          }
  202.          if (unLo > unHi) break;
  203.          fswap(fmap[unLo], fmap[unHi]); unLo++; unHi--;
  204.       }
  205.  
  206.       AssertD ( unHi == unLo-1, "fallbackQSort3(2)" );
  207.  
  208.       if (gtHi < ltLo) continue;
  209.  
  210.       n = fmin(ltLo-lo, unLo-ltLo); fvswap(lo, unLo-n, n);
  211.       m = fmin(hi-gtHi, gtHi-unHi); fvswap(unLo, hi-m+1, m);
  212.  
  213.       n = lo + unLo - ltLo - 1;
  214.       m = hi - (gtHi - unHi) + 1;
  215.  
  216.       if (n - lo > hi - m) {
  217.          fpush ( lo, n );
  218.          fpush ( m, hi );
  219.       } else {
  220.          fpush ( m, hi );
  221.          fpush ( lo, n );
  222.       }
  223.    }
  224. }
  225.  
  226. #undef fmin
  227. #undef fpush
  228. #undef fpop
  229. #undef fswap
  230. #undef fvswap
  231. #undef FALLBACK_QSORT_SMALL_THRESH
  232. #undef FALLBACK_QSORT_STACK_SIZE
  233.  
  234.  
  235. /*---------------------------------------------*/
  236. /* Pre:
  237.       nblock > 0
  238.       eclass exists for [0 .. nblock-1]
  239.       ((UChar*)eclass) [0 .. nblock-1] holds block
  240.       ptr exists for [0 .. nblock-1]
  241.  
  242.    Post:
  243.       ((UChar*)eclass) [0 .. nblock-1] holds block
  244.       All other areas of eclass destroyed
  245.       fmap [0 .. nblock-1] holds sorted order
  246.       bhtab [ 0 .. 2+(nblock/32) ] destroyed
  247. */
  248.  
  249. #define       SET_BH(zz)  bhtab[(zz) >> 5] |= (1 << ((zz) & 31))
  250. #define     CLEAR_BH(zz)  bhtab[(zz) >> 5] &= ~(1 << ((zz) & 31))
  251. #define     ISSET_BH(zz)  (bhtab[(zz) >> 5] & (1 << ((zz) & 31)))
  252. #define      WORD_BH(zz)  bhtab[(zz) >> 5]
  253. #define UNALIGNED_BH(zz)  ((zz) & 0x01f)
  254.  
  255. static
  256. void fallbackSort ( UInt32* fmap, 
  257.                     UInt32* eclass, 
  258.                     UInt32* bhtab,
  259.                     Int32   nblock)
  260. {
  261.    Int32 ftab[257];
  262.    Int32 ftabCopy[256];
  263.    Int32 H, i, j, k, l, r, cc, cc1;
  264.    Int32 nNotDone;
  265.    Int32 nBhtab;
  266.    UChar* eclass8 = (UChar*)eclass;
  267.  
  268.    /*--
  269.       Initial 1-char radix sort to generate
  270.       initial fmap and initial BH bits.
  271.    --*/
  272.    for (i = 0; i < 257;    i++) ftab[i] = 0;
  273.    for (i = 0; i < nblock; i++) ftab[eclass8[i]]++;
  274.    for (i = 0; i < 256;    i++) ftabCopy[i] = ftab[i];
  275.    for (i = 1; i < 257;    i++) ftab[i] += ftab[i-1];
  276.  
  277.    for (i = 0; i < nblock; i++) {
  278.       j = eclass8[i];
  279.       k = ftab[j] - 1;
  280.       ftab[j] = k;
  281.       fmap[k] = i;
  282.    }
  283.  
  284.    nBhtab = 2 + (nblock / 32);
  285.    for (i = 0; i < nBhtab; i++) bhtab[i] = 0;
  286.    for (i = 0; i < 256; i++) SET_BH(ftab[i]);
  287.  
  288.    /*--
  289.       Inductively refine the buckets.  Kind-of an
  290.       "exponential radix sort" (!), inspired by the
  291.       Manber-Myers suffix array construction algorithm.
  292.    --*/
  293.  
  294.    /*-- set sentinel bits for block-end detection --*/
  295.    for (i = 0; i < 32; i++) { 
  296.       SET_BH(nblock + 2*i);
  297.       CLEAR_BH(nblock + 2*i + 1);
  298.    }
  299.  
  300.    /*-- the log(N) loop --*/
  301.    H = 1;
  302.    while (1) {
  303.  
  304.       j = 0;
  305.       for (i = 0; i < nblock; i++) {
  306.          if (ISSET_BH(i)) j = i;
  307.          k = fmap[i] - H; if (k < 0) k += nblock;
  308.          eclass[k] = j;
  309.       }
  310.  
  311.       nNotDone = 0;
  312.       r = -1;
  313.       while (1) {
  314.  
  315.          /*-- find the next non-singleton bucket --*/
  316.          k = r + 1;
  317.          while (ISSET_BH(k) && UNALIGNED_BH(k)) k++;
  318.          if (ISSET_BH(k)) {
  319.             while (WORD_BH(k) == 0xffffffff) k += 32;
  320.             while (ISSET_BH(k)) k++;
  321.          }
  322.          l = k - 1;
  323.          if (l >= nblock) break;
  324.          while (!ISSET_BH(k) && UNALIGNED_BH(k)) k++;
  325.          if (!ISSET_BH(k)) {
  326.             while (WORD_BH(k) == 0x00000000) k += 32;
  327.             while (!ISSET_BH(k)) k++;
  328.          }
  329.          r = k - 1;
  330.          if (r >= nblock) break;
  331.  
  332.          /*-- now [l, r] bracket current bucket --*/
  333.          if (r > l) {
  334.             nNotDone += (r - l + 1);
  335.             fallbackQSort3 ( fmap, eclass, l, r );
  336.  
  337.             /*-- scan bucket and generate header bits-- */
  338.             cc = -1;
  339.             for (i = l; i <= r; i++) {
  340.                cc1 = eclass[fmap[i]];
  341.                if (cc != cc1) { SET_BH(i); cc = cc1; };
  342.             }
  343.          }
  344.       }
  345.  
  346.       H *= 2;
  347.       if (H > nblock || nNotDone == 0) break;
  348.    }
  349.  
  350.    /*-- 
  351.       Reconstruct the original block in
  352.       eclass8 [0 .. nblock-1], since the
  353.       previous phase destroyed it.
  354.    --*/
  355.    j = 0;
  356.    for (i = 0; i < nblock; i++) {
  357.       while (ftabCopy[j] == 0) j++;
  358.       ftabCopy[j]--;
  359.       eclass8[fmap[i]] = (UChar)j;
  360.    }
  361.    AssertH ( j < 256, 1005 );
  362. }
  363.  
  364. #undef       SET_BH
  365. #undef     CLEAR_BH
  366. #undef     ISSET_BH
  367. #undef      WORD_BH
  368. #undef UNALIGNED_BH
  369.  
  370.  
  371. /*---------------------------------------------*/
  372. /*--- The main, O(N^2 log(N)) sorting       ---*/
  373. /*--- algorithm.  Faster for "normal"       ---*/
  374. /*--- non-repetitive blocks.                ---*/
  375. /*---------------------------------------------*/
  376.  
  377. /*---------------------------------------------*/
  378. static Bool mainGtU ( UInt32  i1, 
  379.                UInt32  i2,
  380.                UChar*  block, 
  381.                UInt16* quadrant,
  382.                UInt32  nblock,
  383.                Int32*  budget )
  384. {
  385.    Int32  k;
  386.    UChar  c1, c2;
  387.    UInt16 s1, s2;
  388.  
  389.    AssertD ( i1 != i2, "mainGtU" );
  390.    /* 1 */
  391.    c1 = block[i1]; c2 = block[i2];
  392.    if (c1 != c2) return (c1 > c2);
  393.    i1++; i2++;
  394.    /* 2 */
  395.    c1 = block[i1]; c2 = block[i2];
  396.    if (c1 != c2) return (c1 > c2);
  397.    i1++; i2++;
  398.    /* 3 */
  399.    c1 = block[i1]; c2 = block[i2];
  400.    if (c1 != c2) return (c1 > c2);
  401.    i1++; i2++;
  402.    /* 4 */
  403.    c1 = block[i1]; c2 = block[i2];
  404.    if (c1 != c2) return (c1 > c2);
  405.    i1++; i2++;
  406.    /* 5 */
  407.    c1 = block[i1]; c2 = block[i2];
  408.    if (c1 != c2) return (c1 > c2);
  409.    i1++; i2++;
  410.    /* 6 */
  411.    c1 = block[i1]; c2 = block[i2];
  412.    if (c1 != c2) return (c1 > c2);
  413.    i1++; i2++;
  414.    /* 7 */
  415.    c1 = block[i1]; c2 = block[i2];
  416.    if (c1 != c2) return (c1 > c2);
  417.    i1++; i2++;
  418.    /* 8 */
  419.    c1 = block[i1]; c2 = block[i2];
  420.    if (c1 != c2) return (c1 > c2);
  421.    i1++; i2++;
  422.    /* 9 */
  423.    c1 = block[i1]; c2 = block[i2];
  424.    if (c1 != c2) return (c1 > c2);
  425.    i1++; i2++;
  426.    /* 10 */
  427.    c1 = block[i1]; c2 = block[i2];
  428.    if (c1 != c2) return (c1 > c2);
  429.    i1++; i2++;
  430.    /* 11 */
  431.    c1 = block[i1]; c2 = block[i2];
  432.    if (c1 != c2) return (c1 > c2);
  433.    i1++; i2++;
  434.    /* 12 */
  435.    c1 = block[i1]; c2 = block[i2];
  436.    if (c1 != c2) return (c1 > c2);
  437.    i1++; i2++;
  438.  
  439.    k = nblock + 8;
  440.  
  441.    do {
  442.       /* 1 */
  443.       c1 = block[i1]; c2 = block[i2];
  444.       if (c1 != c2) return (c1 > c2);
  445.       s1 = quadrant[i1]; s2 = quadrant[i2];
  446.       if (s1 != s2) return (s1 > s2);
  447.       i1++; i2++;
  448.       /* 2 */
  449.       c1 = block[i1]; c2 = block[i2];
  450.       if (c1 != c2) return (c1 > c2);
  451.       s1 = quadrant[i1]; s2 = quadrant[i2];
  452.       if (s1 != s2) return (s1 > s2);
  453.       i1++; i2++;
  454.       /* 3 */
  455.       c1 = block[i1]; c2 = block[i2];
  456.       if (c1 != c2) return (c1 > c2);
  457.       s1 = quadrant[i1]; s2 = quadrant[i2];
  458.       if (s1 != s2) return (s1 > s2);
  459.       i1++; i2++;
  460.       /* 4 */
  461.       c1 = block[i1]; c2 = block[i2];
  462.       if (c1 != c2) return (c1 > c2);
  463.       s1 = quadrant[i1]; s2 = quadrant[i2];
  464.       if (s1 != s2) return (s1 > s2);
  465.       i1++; i2++;
  466.       /* 5 */
  467.       c1 = block[i1]; c2 = block[i2];
  468.       if (c1 != c2) return (c1 > c2);
  469.       s1 = quadrant[i1]; s2 = quadrant[i2];
  470.       if (s1 != s2) return (s1 > s2);
  471.       i1++; i2++;
  472.       /* 6 */
  473.       c1 = block[i1]; c2 = block[i2];
  474.       if (c1 != c2) return (c1 > c2);
  475.       s1 = quadrant[i1]; s2 = quadrant[i2];
  476.       if (s1 != s2) return (s1 > s2);
  477.       i1++; i2++;
  478.       /* 7 */
  479.       c1 = block[i1]; c2 = block[i2];
  480.       if (c1 != c2) return (c1 > c2);
  481.       s1 = quadrant[i1]; s2 = quadrant[i2];
  482.       if (s1 != s2) return (s1 > s2);
  483.       i1++; i2++;
  484.       /* 8 */
  485.       c1 = block[i1]; c2 = block[i2];
  486.       if (c1 != c2) return (c1 > c2);
  487.       s1 = quadrant[i1]; s2 = quadrant[i2];
  488.       if (s1 != s2) return (s1 > s2);
  489.       i1++; i2++;
  490.  
  491.       if (i1 >= nblock) i1 -= nblock;
  492.       if (i2 >= nblock) i2 -= nblock;
  493.  
  494.       k -= 8;
  495.       (*budget)--;
  496.    }
  497.       while (k >= 0);
  498.  
  499.    return False;
  500. }
  501.  
  502.  
  503. /*---------------------------------------------*/
  504. /*--
  505.    Knuth's increments seem to work better
  506.    than Incerpi-Sedgewick here.  Possibly
  507.    because the number of elems to sort is
  508.    usually small, typically <= 20.
  509. --*/
  510. static
  511. Int32 incs[14] = { 1, 4, 13, 40, 121, 364, 1093, 3280,
  512.                    9841, 29524, 88573, 265720,
  513.                    797161, 2391484 };
  514.  
  515. static
  516. void mainSimpleSort ( UInt32* ptr,
  517.                       UChar*  block,
  518.                       UInt16* quadrant,
  519.                       Int32   nblock,
  520.                       Int32   lo, 
  521.                       Int32   hi, 
  522.                       Int32   d,
  523.                       Int32*  budget )
  524. {
  525.    Int32 i, j, h, bigN, hp;
  526.    UInt32 v;
  527.  
  528.    bigN = hi - lo + 1;
  529.    if (bigN < 2) return;
  530.  
  531.    hp = 0;
  532.    while (incs[hp] < bigN) hp++;
  533.    hp--;
  534.  
  535.    for (; hp >= 0; hp--) {
  536.       h = incs[hp];
  537.  
  538.       i = lo + h;
  539.       while (True) {
  540.  
  541.          /*-- copy 1 --*/
  542.          if (i > hi) break;
  543.          v = ptr[i];
  544.          j = i;
  545.          while ( mainGtU ( 
  546.                     ptr[j-h]+d, v+d, block, quadrant, nblock, budget 
  547.                  ) ) {
  548.             ptr[j] = ptr[j-h];
  549.             j = j - h;
  550.             if (j <= (lo + h - 1)) break;
  551.          }
  552.          ptr[j] = v;
  553.          i++;
  554.  
  555.          /*-- copy 2 --*/
  556.          if (i > hi) break;
  557.          v = ptr[i];
  558.          j = i;
  559.          while ( mainGtU ( 
  560.                     ptr[j-h]+d, v+d, block, quadrant, nblock, budget 
  561.                  ) ) {
  562.             ptr[j] = ptr[j-h];
  563.             j = j - h;
  564.             if (j <= (lo + h - 1)) break;
  565.          }
  566.          ptr[j] = v;
  567.          i++;
  568.  
  569.          /*-- copy 3 --*/
  570.          if (i > hi) break;
  571.          v = ptr[i];
  572.          j = i;
  573.          while ( mainGtU ( 
  574.                     ptr[j-h]+d, v+d, block, quadrant, nblock, budget 
  575.                  ) ) {
  576.             ptr[j] = ptr[j-h];
  577.             j = j - h;
  578.             if (j <= (lo + h - 1)) break;
  579.          }
  580.          ptr[j] = v;
  581.          i++;
  582.  
  583.          if (*budget < 0) return;
  584.       }
  585.    }
  586. }
  587.  
  588.  
  589. /*---------------------------------------------*/
  590. /*--
  591.    The following is an implementation of
  592.    an elegant 3-way quicksort for strings,
  593.    described in a paper "Fast Algorithms for
  594.    Sorting and Searching Strings", by Robert
  595.    Sedgewick and Jon L. Bentley.
  596. --*/
  597.  
  598. #define mswap(zz1, zz2) \
  599.    { Int32 zztmp = zz1; zz1 = zz2; zz2 = zztmp; }
  600.  
  601. #define mvswap(zzp1, zzp2, zzn)       \
  602. {                                     \
  603.    Int32 yyp1 = (zzp1);               \
  604.    Int32 yyp2 = (zzp2);               \
  605.    Int32 yyn  = (zzn);                \
  606.    while (yyn > 0) {                  \
  607.       mswap(ptr[yyp1], ptr[yyp2]);    \
  608.       yyp1++; yyp2++; yyn--;          \
  609.    }                                  \
  610. }
  611.  
  612. static 
  613. UChar mmed3 ( UChar a, UChar b, UChar c )
  614. {
  615.    UChar t;
  616.    if (a > b) { t = a; a = b; b = t; };
  617.    if (b > c) { 
  618.       b = c;
  619.       if (a > b) b = a;
  620.    }
  621.    return b;
  622. }
  623.  
  624. #define mmin(a,b) ((a) < (b)) ? (a) : (b)
  625.  
  626. #define mpush(lz,hz,dz) { stackLo[sp] = lz; \
  627.                           stackHi[sp] = hz; \
  628.                           stackD [sp] = dz; \
  629.                           sp++; }
  630.  
  631. #define mpop(lz,hz,dz) { sp--;             \
  632.                          lz = stackLo[sp]; \
  633.                          hz = stackHi[sp]; \
  634.                          dz = stackD [sp]; }
  635.  
  636.  
  637. #define mnextsize(az) (nextHi[az]-nextLo[az])
  638.  
  639. #define mnextswap(az,bz)                                        \
  640.    { Int32 tz;                                                  \
  641.      tz = nextLo[az]; nextLo[az] = nextLo[bz]; nextLo[bz] = tz; \
  642.      tz = nextHi[az]; nextHi[az] = nextHi[bz]; nextHi[bz] = tz; \
  643.      tz = nextD [az]; nextD [az] = nextD [bz]; nextD [bz] = tz; }
  644.  
  645.  
  646. #define MAIN_QSORT_SMALL_THRESH 20
  647. #define MAIN_QSORT_DEPTH_THRESH (BZ_N_RADIX + BZ_N_QSORT)
  648. #define MAIN_QSORT_STACK_SIZE 100
  649.  
  650. static
  651. void mainQSort3 ( UInt32* ptr,
  652.                   UChar*  block,
  653.                   UInt16* quadrant,
  654.                   Int32   nblock,
  655.                   Int32   loSt, 
  656.                   Int32   hiSt, 
  657.                   Int32   dSt,
  658.                   Int32*  budget )
  659. {
  660.    Int32 unLo, unHi, ltLo, gtHi, n, m, med;
  661.    Int32 sp, lo, hi, d;
  662.  
  663.    Int32 stackLo[MAIN_QSORT_STACK_SIZE];
  664.    Int32 stackHi[MAIN_QSORT_STACK_SIZE];
  665.    Int32 stackD [MAIN_QSORT_STACK_SIZE];
  666.  
  667.    Int32 nextLo[3];
  668.    Int32 nextHi[3];
  669.    Int32 nextD [3];
  670.  
  671.    sp = 0;
  672.    mpush ( loSt, hiSt, dSt );
  673.  
  674.    while (sp > 0) {
  675.  
  676.       AssertH ( sp < MAIN_QSORT_STACK_SIZE, 1001 );
  677.  
  678.       mpop ( lo, hi, d );
  679.       if (hi - lo < MAIN_QSORT_SMALL_THRESH || 
  680.           d > MAIN_QSORT_DEPTH_THRESH) {
  681.          mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget );
  682.          if (*budget < 0) return;
  683.          continue;
  684.       }
  685.  
  686.       med = (Int32) 
  687.             mmed3 ( block[ptr[ lo         ]+d],
  688.                     block[ptr[ hi         ]+d],
  689.                     block[ptr[ (lo+hi)>>1 ]+d] );
  690.  
  691.       unLo = ltLo = lo;
  692.       unHi = gtHi = hi;
  693.  
  694.       while (True) {
  695.          while (True) {
  696.             if (unLo > unHi) break;
  697.             n = ((Int32)block[ptr[unLo]+d]) - med;
  698.             if (n == 0) { 
  699.                mswap(ptr[unLo], ptr[ltLo]); 
  700.                ltLo++; unLo++; continue; 
  701.             };
  702.             if (n >  0) break;
  703.             unLo++;
  704.          }
  705.          while (True) {
  706.             if (unLo > unHi) break;
  707.             n = ((Int32)block[ptr[unHi]+d]) - med;
  708.             if (n == 0) { 
  709.                mswap(ptr[unHi], ptr[gtHi]); 
  710.                gtHi--; unHi--; continue; 
  711.             };
  712.             if (n <  0) break;
  713.             unHi--;
  714.          }
  715.          if (unLo > unHi) break;
  716.          mswap(ptr[unLo], ptr[unHi]); unLo++; unHi--;
  717.       }
  718.  
  719.       AssertD ( unHi == unLo-1, "mainQSort3(2)" );
  720.  
  721.       if (gtHi < ltLo) {
  722.          mpush(lo, hi, d+1 );
  723.          continue;
  724.       }
  725.  
  726.       n = mmin(ltLo-lo, unLo-ltLo); mvswap(lo, unLo-n, n);
  727.       m = mmin(hi-gtHi, gtHi-unHi); mvswap(unLo, hi-m+1, m);
  728.  
  729.       n = lo + unLo - ltLo - 1;
  730.       m = hi - (gtHi - unHi) + 1;
  731.  
  732.       nextLo[0] = lo;  nextHi[0] = n;   nextD[0] = d;
  733.       nextLo[1] = m;   nextHi[1] = hi;  nextD[1] = d;
  734.       nextLo[2] = n+1; nextHi[2] = m-1; nextD[2] = d+1;
  735.  
  736.       if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);
  737.       if (mnextsize(1) < mnextsize(2)) mnextswap(1,2);
  738.       if (mnextsize(0) < mnextsize(1)) mnextswap(0,1);
  739.  
  740.       AssertD (mnextsize(0) >= mnextsize(1), "mainQSort3(8)" );
  741.       AssertD (mnextsize(1) >= mnextsize(2), "mainQSort3(9)" );
  742.  
  743.       mpush (nextLo[0], nextHi[0], nextD[0]);
  744.       mpush (nextLo[1], nextHi[1], nextD[1]);
  745.       mpush (nextLo[2], nextHi[2], nextD[2]);
  746.    }
  747. }
  748.  
  749. #undef mswap
  750. #undef mvswap
  751. #undef mpush
  752. #undef mpop
  753. #undef mmin
  754. #undef mnextsize
  755. #undef mnextswap
  756. #undef MAIN_QSORT_SMALL_THRESH
  757. #undef MAIN_QSORT_DEPTH_THRESH
  758. #undef MAIN_QSORT_STACK_SIZE
  759.  
  760.  
  761. /*---------------------------------------------*/
  762. /* Pre:
  763.       nblock > N_OVERSHOOT
  764.       block32 exists for [0 .. nblock-1 +N_OVERSHOOT]
  765.       ((UChar*)block32) [0 .. nblock-1] holds block
  766.       ptr exists for [0 .. nblock-1]
  767.  
  768.    Post:
  769.       ((UChar*)block32) [0 .. nblock-1] holds block
  770.       All other areas of block32 destroyed
  771.       ftab [0 .. 65536 ] destroyed
  772.       ptr [0 .. nblock-1] holds sorted order
  773.       if (*budget < 0), sorting was abandoned
  774. */
  775.  
  776. #define BIGFREQ(b) (ftab[((b)+1) << 8] - ftab[(b) << 8])
  777. #define SETMASK (1 << 21)
  778. #define CLEARMASK (~(SETMASK))
  779.  
  780. static
  781. void mainSort ( UInt32* ptr, 
  782.                 UChar*  block,
  783.                 UInt16* quadrant, 
  784.                 UInt32* ftab,
  785.                 Int32   nblock,
  786.                 Int32*  budget )
  787. {
  788.    Int32  i, j, k, ss, sb;
  789.    Int32  runningOrder[256];
  790.    Bool   bigDone[256];
  791.    Int32  copyStart[256];
  792.    Int32  copyEnd  [256];
  793.    UChar  c1;
  794.    Int32  numQSorted;
  795.    UInt16 s;
  796.  
  797.    /*-- set up the 2-byte frequency table --*/
  798.    for (i = 65536; i >= 0; i--) ftab[i] = 0;
  799.  
  800.    j = block[0] << 8;
  801.    i = nblock-1;
  802.    for (; i >= 3; i -= 4) {
  803.       quadrant[i] = 0;
  804.       j = (j >> 8) | ( ((UInt16)block[i]) << 8);
  805.       ftab[j]++;
  806.       quadrant[i-1] = 0;
  807.       j = (j >> 8) | ( ((UInt16)block[i-1]) << 8);
  808.       ftab[j]++;
  809.       quadrant[i-2] = 0;
  810.       j = (j >> 8) | ( ((UInt16)block[i-2]) << 8);
  811.       ftab[j]++;
  812.       quadrant[i-3] = 0;
  813.       j = (j >> 8) | ( ((UInt16)block[i-3]) << 8);
  814.       ftab[j]++;
  815.    }
  816.    for (; i >= 0; i--) {
  817.       quadrant[i] = 0;
  818.       j = (j >> 8) | ( ((UInt16)block[i]) << 8);
  819.       ftab[j]++;
  820.    }
  821.  
  822.    /*-- (emphasises close relationship of block & quadrant) --*/
  823.    for (i = 0; i < BZ_N_OVERSHOOT; i++) {
  824.       block   [nblock+i] = block[i];
  825.       quadrant[nblock+i] = 0;
  826.    }
  827.  
  828.    /*-- Complete the initial radix sort --*/
  829.    for (i = 1; i <= 65536; i++) ftab[i] += ftab[i-1];
  830.  
  831.    s = block[0] << 8;
  832.    i = nblock-1;
  833.    for (; i >= 3; i -= 4) {
  834.       s = (s >> 8) | (block[i] << 8);
  835.       j = ftab[s] -1;
  836.       ftab[s] = j;
  837.       ptr[j] = i;
  838.       s = (s >> 8) | (block[i-1] << 8);
  839.       j = ftab[s] -1;
  840.       ftab[s] = j;
  841.       ptr[j] = i-1;
  842.       s = (s >> 8) | (block[i-2] << 8);
  843.       j = ftab[s] -1;
  844.       ftab[s] = j;
  845.       ptr[j] = i-2;
  846.       s = (s >> 8) | (block[i-3] << 8);
  847.       j = ftab[s] -1;
  848.       ftab[s] = j;
  849.       ptr[j] = i-3;
  850.    }
  851.    for (; i >= 0; i--) {
  852.       s = (s >> 8) | (block[i] << 8);
  853.       j = ftab[s] -1;
  854.       ftab[s] = j;
  855.       ptr[j] = i;
  856.    }
  857.  
  858.    /*--
  859.       Now ftab contains the first loc of every small bucket.
  860.       Calculate the running order, from smallest to largest
  861.       big bucket.
  862.    --*/
  863.    for (i = 0; i <= 255; i++) {
  864.       bigDone     [i] = False;
  865.       runningOrder[i] = i;
  866.    }
  867.  
  868.    {
  869.       Int32 vv;
  870.       Int32 h = 1;
  871.       do h = 3 * h + 1; while (h <= 256);
  872.       do {
  873.          h = h / 3;
  874.          for (i = h; i <= 255; i++) {
  875.             vv = runningOrder[i];
  876.             j = i;
  877.             while ( BIGFREQ(runningOrder[j-h]) > BIGFREQ(vv) ) {
  878.                runningOrder[j] = runningOrder[j-h];
  879.                j = j - h;
  880.                if (j <= (h - 1)) goto zero;
  881.             }
  882.             zero:
  883.             runningOrder[j] = vv;
  884.          }
  885.       } while (h != 1);
  886.    }
  887.  
  888.    /*--
  889.       The main sorting loop.
  890.    --*/
  891.  
  892.    numQSorted = 0;
  893.  
  894.    for (i = 0; i <= 255; i++) {
  895.  
  896.       /*--
  897.          Process big buckets, starting with the least full.
  898.          Basically this is a 3-step process in which we call
  899.          mainQSort3 to sort the small buckets [ss, j], but
  900.          also make a big effort to avoid the calls if we can.
  901.       --*/
  902.       ss = runningOrder[i];
  903.  
  904.       /*--
  905.          Step 1:
  906.          Complete the big bucket [ss] by quicksorting
  907.          any unsorted small buckets [ss, j], for j != ss.  
  908.          Hopefully previous pointer-scanning phases have already
  909.          completed many of the small buckets [ss, j], so
  910.          we don't have to sort them at all.
  911.       --*/
  912.       for (j = 0; j <= 255; j++) {
  913.          if (j != ss) {
  914.             sb = (ss << 8) + j;
  915.             if ( ! (ftab[sb] & SETMASK) ) {
  916.                Int32 lo = ftab[sb]   & CLEARMASK;
  917.                Int32 hi = (ftab[sb+1] & CLEARMASK) - 1;
  918.                if (hi > lo) {
  919.                   mainQSort3 ( 
  920.                      ptr, block, quadrant, nblock, 
  921.                      lo, hi, BZ_N_RADIX, budget 
  922.                   );   
  923.                   numQSorted += (hi - lo + 1);
  924.                   if (*budget < 0) return;
  925.                }
  926.             }
  927.             ftab[sb] |= SETMASK;
  928.          }
  929.       }
  930.  
  931.       AssertH ( !bigDone[ss], 1006 );
  932.  
  933.       /*--
  934.          Step 2:
  935.          Now scan this big bucket [ss] so as to synthesise the
  936.          sorted order for small buckets [t, ss] for all t,
  937.          including, magically, the bucket [ss,ss] too.
  938.          This will avoid doing Real Work in subsequent Step 1's.
  939.       --*/
  940.       {
  941.          for (j = 0; j <= 255; j++) {
  942.             copyStart[j] =  ftab[(j << 8) + ss]     & CLEARMASK;
  943.             copyEnd  [j] = (ftab[(j << 8) + ss + 1] & CLEARMASK) - 1;
  944.          }
  945.          for (j = ftab[ss << 8] & CLEARMASK; j < copyStart[ss]; j++) {
  946.             k = ptr[j]-1; if (k < 0) k += nblock;
  947.             c1 = block[k];
  948.             if (!bigDone[c1])
  949.                ptr[ copyStart[c1]++ ] = k;
  950.          }
  951.          for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) {
  952.             k = ptr[j]-1; if (k < 0) k += nblock;
  953.             c1 = block[k];
  954.             if (!bigDone[c1]) 
  955.                ptr[ copyEnd[c1]-- ] = k;
  956.          }
  957.       }
  958.  
  959.       AssertH ( copyStart[ss]-1 == copyEnd[ss], 1007 );
  960.  
  961.       for (j = 0; j <= 255; j++) ftab[(j << 8) + ss] |= SETMASK;
  962.  
  963.       /*--
  964.          Step 3:
  965.          The [ss] big bucket is now done.  Record this fact,
  966.          and update the quadrant descriptors.  Remember to
  967.          update quadrants in the overshoot area too, if
  968.          necessary.  The "if (i < 255)" test merely skips
  969.          this updating for the last bucket processed, since
  970.          updating for the last bucket is pointless.
  971.  
  972.          The quadrant array provides a way to incrementally
  973.          cache sort orderings, as they appear, so as to 
  974.          make subsequent comparisons in fullGtU() complete
  975.          faster.  For repetitive blocks this makes a big
  976.          difference (but not big enough to be able to avoid
  977.          the fallback sorting mechanism, exponential radix sort).
  978.  
  979.          The precise meaning is: at all times:
  980.  
  981.             for 0 <= i < nblock and 0 <= j <= nblock
  982.  
  983.             if block[i] != block[j], 
  984.  
  985.                then the relative values of quadrant[i] and 
  986.                     quadrant[j] are meaningless.
  987.  
  988.                else {
  989.                   if quadrant[i] < quadrant[j]
  990.                      then the string starting at i lexicographically
  991.                      precedes the string starting at j
  992.  
  993.                   else if quadrant[i] > quadrant[j]
  994.                      then the string starting at j lexicographically
  995.                      precedes the string starting at i
  996.  
  997.                   else
  998.                      the relative ordering of the strings starting
  999.                      at i and j has not yet been determined.
  1000.                }
  1001.       --*/
  1002.       bigDone[ss] = True;
  1003.  
  1004.       if (i < 255) {
  1005.          Int32 bbStart  = ftab[ss << 8] & CLEARMASK;
  1006.          Int32 bbSize   = (ftab[(ss+1) << 8] & CLEARMASK) - bbStart;
  1007.          Int32 shifts   = 0;
  1008.  
  1009.          while ((bbSize >> shifts) > 65534) shifts++;
  1010.  
  1011.          for (j = bbSize-1; j >= 0; j--) {
  1012.             Int32 a2update     = ptr[bbStart + j];
  1013.             UInt16 qVal        = (UInt16)(j >> shifts);
  1014.             quadrant[a2update] = qVal;
  1015.             if (a2update < BZ_N_OVERSHOOT)
  1016.                quadrant[a2update + nblock] = qVal;
  1017.          }
  1018.          AssertH ( ((bbSize-1) >> shifts) <= 65535, 1002 );
  1019.       }
  1020.  
  1021.    }
  1022. }
  1023.  
  1024. #undef BIGFREQ
  1025. #undef SETMASK
  1026. #undef CLEARMASK
  1027.  
  1028.  
  1029. /*---------------------------------------------*/
  1030. /* Pre:
  1031.       nblock > 0
  1032.       arr2 exists for [0 .. nblock-1 +N_OVERSHOOT]
  1033.       ((UChar*)arr2)  [0 .. nblock-1] holds block
  1034.       arr1 exists for [0 .. nblock-1]
  1035.  
  1036.    Post:
  1037.       ((UChar*)arr2) [0 .. nblock-1] holds block
  1038.       All other areas of block destroyed
  1039.       ftab [ 0 .. 65536 ] destroyed
  1040.       arr1 [0 .. nblock-1] holds sorted order
  1041. */
  1042. void BZ2_blockSort ( EState* s )
  1043. {
  1044.    UInt32* ptr    = s->ptr; 
  1045.    UChar*  block  = s->block;
  1046.    UInt32* ftab   = s->ftab;
  1047.    Int32   nblock = s->nblock;
  1048.    Int32   wfact  = s->workFactor;
  1049.    UInt16* quadrant;
  1050.    Int32   budget;
  1051.    Int32   budgetInit;
  1052.    Int32   i;
  1053.  
  1054.    if (nblock < 10000) {
  1055.       fallbackSort ( s->arr1, s->arr2, ftab, nblock );
  1056.    } else {
  1057.       /* Calculate the location for quadrant, remembering to get
  1058.          the alignment right.  Assumes that &(block[0]) is at least
  1059.          2-byte aligned -- this should be ok since block is really
  1060.          the first section of arr2.
  1061.       */
  1062.       i = nblock+BZ_N_OVERSHOOT;
  1063.       if (i & 1) i++;
  1064.       quadrant = (UInt16*)(&(block[i]));
  1065.  
  1066.       /* (wfact-1) / 3 puts the default-factor-30
  1067.          transition point at very roughly the same place as 
  1068.          with v0.1 and v0.9.0.  
  1069.          Not that it particularly matters any more, since the
  1070.          resulting compressed stream is now the same regardless
  1071.          of whether or not we use the main sort or fallback sort.
  1072.       */
  1073.       if (wfact < 1  ) wfact = 1;
  1074.       if (wfact > 100) wfact = 100;
  1075.       budgetInit = nblock * ((wfact-1) / 3);
  1076.       budget = budgetInit;
  1077.  
  1078.       mainSort ( ptr, block, quadrant, ftab, nblock, &budget );
  1079.       if (budget < 0) {
  1080.          fallbackSort ( s->arr1, s->arr2, ftab, nblock );
  1081.       }
  1082.    }
  1083.  
  1084.    s->origPtr = -1;
  1085.    for (i = 0; i < s->nblock; i++)
  1086.       if (ptr[i] == 0)
  1087.          { s->origPtr = i; break; };
  1088.  
  1089.    AssertH( s->origPtr != -1, 1003 );
  1090. }
  1091.  
  1092.  
  1093. /*-------------------------------------------------------------*/
  1094. /*--- end                                       blocksort.c ---*/
  1095. /*-------------------------------------------------------------*/
  1096.  
  1097. #endif