~ubuntu-branches/ubuntu/hardy/postgresql-8.4/hardy-backports

« back to all changes in this revision

Viewing changes to src/backend/utils/adt/pg_lzcompress.c

  • Committer: Bazaar Package Importer
  • Author(s): Martin Pitt
  • Date: 2009-03-20 12:00:13 UTC
  • Revision ID: james.westby@ubuntu.com-20090320120013-hogj7egc5mjncc5g
Tags: upstream-8.4~0cvs20090328
ImportĀ upstreamĀ versionĀ 8.4~0cvs20090328

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
/* ----------
 
2
 * pg_lzcompress.c -
 
3
 *
 
4
 *              This is an implementation of LZ compression for PostgreSQL.
 
5
 *              It uses a simple history table and generates 2-3 byte tags
 
6
 *              capable of backward copy information for 3-273 bytes with
 
7
 *              a max offset of 4095.
 
8
 *
 
9
 *              Entry routines:
 
10
 *
 
11
 *                      bool
 
12
 *                      pglz_compress(const char *source, int32 slen, PGLZ_Header *dest,
 
13
 *                                                const PGLZ_Strategy *strategy);
 
14
 *
 
15
 *                              source is the input data to be compressed.
 
16
 *
 
17
 *                              slen is the length of the input data.
 
18
 *
 
19
 *                              dest is the output area for the compressed result.
 
20
 *                                      It must be at least as big as PGLZ_MAX_OUTPUT(slen).
 
21
 *
 
22
 *                              strategy is a pointer to some information controlling
 
23
 *                                      the compression algorithm. If NULL, the compiled
 
24
 *                                      in default strategy is used.
 
25
 *
 
26
 *                              The return value is TRUE if compression succeeded,
 
27
 *                              FALSE if not; in the latter case the contents of dest
 
28
 *                              are undefined.
 
29
 *
 
30
 *                      void
 
31
 *                      pglz_decompress(const PGLZ_Header *source, char *dest)
 
32
 *
 
33
 *                              source is the compressed input.
 
34
 *
 
35
 *                              dest is the area where the uncompressed data will be
 
36
 *                                      written to. It is the callers responsibility to
 
37
 *                                      provide enough space. The required amount can be
 
38
 *                                      obtained with the macro PGLZ_RAW_SIZE(source).
 
39
 *
 
40
 *                                      The data is written to buff exactly as it was handed
 
41
 *                                      to pglz_compress(). No terminating zero byte is added.
 
42
 *
 
43
 *              The decompression algorithm and internal data format:
 
44
 *
 
45
 *                      PGLZ_Header is defined as
 
46
 *
 
47
 *                              typedef struct PGLZ_Header {
 
48
 *                                      int32           vl_len_;
 
49
 *                                      int32           rawsize;
 
50
 *                              }
 
51
 *
 
52
 *                      The header is followed by the compressed data itself.
 
53
 *
 
54
 *                      The data representation is easiest explained by describing
 
55
 *                      the process of decompression.
 
56
 *
 
57
 *                      If VARSIZE(x) == rawsize + sizeof(PGLZ_Header), then the data
 
58
 *                      is stored uncompressed as plain bytes. Thus, the decompressor
 
59
 *                      simply copies rawsize bytes from the location after the
 
60
 *                      header to the destination.
 
61
 *
 
62
 *                      Otherwise the first byte after the header tells what to do
 
63
 *                      the next 8 times. We call this the control byte.
 
64
 *
 
65
 *                      An unset bit in the control byte means, that one uncompressed
 
66
 *                      byte follows, which is copied from input to output.
 
67
 *
 
68
 *                      A set bit in the control byte means, that a tag of 2-3 bytes
 
69
 *                      follows. A tag contains information to copy some bytes, that
 
70
 *                      are already in the output buffer, to the current location in
 
71
 *                      the output. Let's call the three tag bytes T1, T2 and T3. The
 
72
 *                      position of the data to copy is coded as an offset from the
 
73
 *                      actual output position.
 
74
 *
 
75
 *                      The offset is in the upper nibble of T1 and in T2.
 
76
 *                      The length is in the lower nibble of T1.
 
77
 *
 
78
 *                      So the 16 bits of a 2 byte tag are coded as
 
79
 *
 
80
 *                              7---T1--0  7---T2--0
 
81
 *                              OOOO LLLL  OOOO OOOO
 
82
 *
 
83
 *                      This limits the offset to 1-4095 (12 bits) and the length
 
84
 *                      to 3-18 (4 bits) because 3 is always added to it. To emit
 
85
 *                      a tag of 2 bytes with a length of 2 only saves one control
 
86
 *                      bit. But we lose one byte in the possible length of a tag.
 
87
 *
 
88
 *                      In the actual implementation, the 2 byte tag's length is
 
89
 *                      limited to 3-17, because the value 0xF in the length nibble
 
90
 *                      has special meaning. It means, that the next following
 
91
 *                      byte (T3) has to be added to the length value of 18. That
 
92
 *                      makes total limits of 1-4095 for offset and 3-273 for length.
 
93
 *
 
94
 *                      Now that we have successfully decoded a tag. We simply copy
 
95
 *                      the output that occurred <offset> bytes back to the current
 
96
 *                      output location in the specified <length>. Thus, a
 
97
 *                      sequence of 200 spaces (think about bpchar fields) could be
 
98
 *                      coded in 4 bytes. One literal space and a three byte tag to
 
99
 *                      copy 199 bytes with a -1 offset. Whow - that's a compression
 
100
 *                      rate of 98%! Well, the implementation needs to save the
 
101
 *                      original data size too, so we need another 4 bytes for it
 
102
 *                      and end up with a total compression rate of 96%, what's still
 
103
 *                      worth a Whow.
 
104
 *
 
105
 *              The compression algorithm
 
106
 *
 
107
 *                      The following uses numbers used in the default strategy.
 
108
 *
 
109
 *                      The compressor works best for attributes of a size between
 
110
 *                      1K and 1M. For smaller items there's not that much chance of
 
111
 *                      redundancy in the character sequence (except for large areas
 
112
 *                      of identical bytes like trailing spaces) and for bigger ones
 
113
 *                      our 4K maximum look-back distance is too small.
 
114
 *
 
115
 *                      The compressor creates a table for 8192 lists of positions.
 
116
 *                      For each input position (except the last 3), a hash key is
 
117
 *                      built from the 4 next input bytes and the position remembered
 
118
 *                      in the appropriate list. Thus, the table points to linked
 
119
 *                      lists of likely to be at least in the first 4 characters
 
120
 *                      matching strings. This is done on the fly while the input
 
121
 *                      is compressed into the output area.  Table entries are only
 
122
 *                      kept for the last 4096 input positions, since we cannot use
 
123
 *                      back-pointers larger than that anyway.
 
124
 *
 
125
 *                      For each byte in the input, it's hash key (built from this
 
126
 *                      byte and the next 3) is used to find the appropriate list
 
127
 *                      in the table. The lists remember the positions of all bytes
 
128
 *                      that had the same hash key in the past in increasing backward
 
129
 *                      offset order. Now for all entries in the used lists, the
 
130
 *                      match length is computed by comparing the characters from the
 
131
 *                      entries position with the characters from the actual input
 
132
 *                      position.
 
133
 *
 
134
 *                      The compressor starts with a so called "good_match" of 128.
 
135
 *                      It is a "prefer speed against compression ratio" optimizer.
 
136
 *                      So if the first entry looked at already has 128 or more
 
137
 *                      matching characters, the lookup stops and that position is
 
138
 *                      used for the next tag in the output.
 
139
 *
 
140
 *                      For each subsequent entry in the history list, the "good_match"
 
141
 *                      is lowered by 10%. So the compressor will be more happy with
 
142
 *                      short matches the farer it has to go back in the history.
 
143
 *                      Another "speed against ratio" preference characteristic of
 
144
 *                      the algorithm.
 
145
 *
 
146
 *                      Thus there are 3 stop conditions for the lookup of matches:
 
147
 *
 
148
 *                              - a match >= good_match is found
 
149
 *                              - there are no more history entries to look at
 
150
 *                              - the next history entry is already too far back
 
151
 *                                to be coded into a tag.
 
152
 *
 
153
 *                      Finally the match algorithm checks that at least a match
 
154
 *                      of 3 or more bytes has been found, because thats the smallest
 
155
 *                      amount of copy information to code into a tag. If so, a tag
 
156
 *                      is omitted and all the input bytes covered by that are just
 
157
 *                      scanned for the history add's, otherwise a literal character
 
158
 *                      is omitted and only his history entry added.
 
159
 *
 
160
 *              Acknowledgements:
 
161
 *
 
162
 *                      Many thanks to Adisak Pochanayon, who's article about SLZ
 
163
 *                      inspired me to write the PostgreSQL compression this way.
 
164
 *
 
165
 *                      Jan Wieck
 
166
 *
 
167
 * Copyright (c) 1999-2009, PostgreSQL Global Development Group
 
168
 *
 
169
 * $PostgreSQL$
 
170
 * ----------
 
171
 */
 
172
#include "postgres.h"
 
173
 
 
174
#include <limits.h>
 
175
 
 
176
#include "utils/pg_lzcompress.h"
 
177
 
 
178
 
 
179
/* ----------
 
180
 * Local definitions
 
181
 * ----------
 
182
 */
 
183
#define PGLZ_HISTORY_LISTS              8192    /* must be power of 2 */
 
184
#define PGLZ_HISTORY_MASK               (PGLZ_HISTORY_LISTS - 1)
 
185
#define PGLZ_HISTORY_SIZE               4096
 
186
#define PGLZ_MAX_MATCH                  273
 
187
 
 
188
 
 
189
/* ----------
 
190
 * PGLZ_HistEntry -
 
191
 *
 
192
 *              Linked list for the backward history lookup
 
193
 *
 
194
 * All the entries sharing a hash key are linked in a doubly linked list.
 
195
 * This makes it easy to remove an entry when it's time to recycle it
 
196
 * (because it's more than 4K positions old).
 
197
 * ----------
 
198
 */
 
199
typedef struct PGLZ_HistEntry
 
200
{
 
201
        struct PGLZ_HistEntry *next;    /* links for my hash key's list */
 
202
        struct PGLZ_HistEntry *prev;
 
203
        int                     hindex;                 /* my current hash key */
 
204
        const char *pos;                        /* my input position */
 
205
} PGLZ_HistEntry;
 
206
 
 
207
 
 
208
/* ----------
 
209
 * The provided standard strategies
 
210
 * ----------
 
211
 */
 
212
static const PGLZ_Strategy strategy_default_data = {
 
213
        32,                             /* Data chunks less than 32 bytes are not compressed */
 
214
        INT_MAX,                /* No upper limit on what we'll try to compress */
 
215
        25,                             /* Require 25% compression rate, or not worth it */
 
216
        1024,                   /* Give up if no compression in the first 1KB */
 
217
        128,                    /* Stop history lookup if a match of 128 bytes is found */
 
218
        10                              /* Lower good match size by 10% at every loop iteration */
 
219
};
 
220
const PGLZ_Strategy *const PGLZ_strategy_default = &strategy_default_data;
 
221
 
 
222
 
 
223
static const PGLZ_Strategy strategy_always_data = {
 
224
        0,                              /* Chunks of any size are compressed */
 
225
        INT_MAX,
 
226
        0,                              /* It's enough to save one single byte */
 
227
        INT_MAX,                /* Never give up early */
 
228
        128,                    /* Stop history lookup if a match of 128 bytes is found */
 
229
        6                               /* Look harder for a good match */
 
230
};
 
231
const PGLZ_Strategy *const PGLZ_strategy_always = &strategy_always_data;
 
232
 
 
233
 
 
234
/* ----------
 
235
 * Statically allocated work arrays for history
 
236
 * ----------
 
237
 */
 
238
static PGLZ_HistEntry *hist_start[PGLZ_HISTORY_LISTS];
 
239
static PGLZ_HistEntry hist_entries[PGLZ_HISTORY_SIZE];
 
240
 
 
241
 
 
242
/* ----------
 
243
 * pglz_hist_idx -
 
244
 *
 
245
 *              Computes the history table slot for the lookup by the next 4
 
246
 *              characters in the input.
 
247
 *
 
248
 * NB: because we use the next 4 characters, we are not guaranteed to
 
249
 * find 3-character matches; they very possibly will be in the wrong
 
250
 * hash list.  This seems an acceptable tradeoff for spreading out the
 
251
 * hash keys more.
 
252
 * ----------
 
253
 */
 
254
#define pglz_hist_idx(_s,_e) (                                                                                          \
 
255
                        ((((_e) - (_s)) < 4) ? (int) (_s)[0] :                                                  \
 
256
                         (((_s)[0] << 9) ^ ((_s)[1] << 6) ^                                                             \
 
257
                          ((_s)[2] << 3) ^ (_s)[3])) & (PGLZ_HISTORY_MASK)                              \
 
258
                )
 
259
 
 
260
 
 
261
/* ----------
 
262
 * pglz_hist_add -
 
263
 *
 
264
 *              Adds a new entry to the history table.
 
265
 *
 
266
 * If _recycle is true, then we are recycling a previously used entry,
 
267
 * and must first delink it from its old hashcode's linked list.
 
268
 *
 
269
 * NOTE: beware of multiple evaluations of macro's arguments, and note that
 
270
 * _hn and _recycle are modified in the macro.
 
271
 * ----------
 
272
 */
 
273
#define pglz_hist_add(_hs,_he,_hn,_recycle,_s,_e) \
 
274
do {                                                                    \
 
275
                        int __hindex = pglz_hist_idx((_s),(_e));                                                \
 
276
                        PGLZ_HistEntry **__myhsp = &(_hs)[__hindex];                                    \
 
277
                        PGLZ_HistEntry *__myhe = &(_he)[_hn];                                                   \
 
278
                        if (_recycle) {                                                                                                 \
 
279
                                if (__myhe->prev == NULL)                                                                       \
 
280
                                        (_hs)[__myhe->hindex] = __myhe->next;                                   \
 
281
                                else                                                                                                            \
 
282
                                        __myhe->prev->next = __myhe->next;                                              \
 
283
                                if (__myhe->next != NULL)                                                                       \
 
284
                                        __myhe->next->prev = __myhe->prev;                                              \
 
285
                        }                                                                                                                               \
 
286
                        __myhe->next = *__myhsp;                                                                                \
 
287
                        __myhe->prev = NULL;                                                                                    \
 
288
                        __myhe->hindex = __hindex;                                                                              \
 
289
                        __myhe->pos  = (_s);                                                                                    \
 
290
                        if (*__myhsp != NULL)                                                                                   \
 
291
                                (*__myhsp)->prev = __myhe;                                                                      \
 
292
                        *__myhsp = __myhe;                                                                                              \
 
293
                        if (++(_hn) >= PGLZ_HISTORY_SIZE) {                                                             \
 
294
                                (_hn) = 0;                                                                                                      \
 
295
                                (_recycle) = true;                                                                                      \
 
296
                        }                                                                                                                               \
 
297
} while (0)
 
298
 
 
299
 
 
300
/* ----------
 
301
 * pglz_out_ctrl -
 
302
 *
 
303
 *              Outputs the last and allocates a new control byte if needed.
 
304
 * ----------
 
305
 */
 
306
#define pglz_out_ctrl(__ctrlp,__ctrlb,__ctrl,__buf) \
 
307
do { \
 
308
        if ((__ctrl & 0xff) == 0)                                                                                               \
 
309
        {                                                                                                                                               \
 
310
                *(__ctrlp) = __ctrlb;                                                                                           \
 
311
                __ctrlp = (__buf)++;                                                                                            \
 
312
                __ctrlb = 0;                                                                                                            \
 
313
                __ctrl = 1;                                                                                                                     \
 
314
        }                                                                                                                                               \
 
315
} while (0)
 
316
 
 
317
 
 
318
/* ----------
 
319
 * pglz_out_literal -
 
320
 *
 
321
 *              Outputs a literal byte to the destination buffer including the
 
322
 *              appropriate control bit.
 
323
 * ----------
 
324
 */
 
325
#define pglz_out_literal(_ctrlp,_ctrlb,_ctrl,_buf,_byte) \
 
326
do { \
 
327
        pglz_out_ctrl(_ctrlp,_ctrlb,_ctrl,_buf);                                                                \
 
328
        *(_buf)++ = (unsigned char)(_byte);                                                                             \
 
329
        _ctrl <<= 1;                                                                                                                    \
 
330
} while (0)
 
331
 
 
332
 
 
333
/* ----------
 
334
 * pglz_out_tag -
 
335
 *
 
336
 *              Outputs a backward reference tag of 2-4 bytes (depending on
 
337
 *              offset and length) to the destination buffer including the
 
338
 *              appropriate control bit.
 
339
 * ----------
 
340
 */
 
341
#define pglz_out_tag(_ctrlp,_ctrlb,_ctrl,_buf,_len,_off) \
 
342
do { \
 
343
        pglz_out_ctrl(_ctrlp,_ctrlb,_ctrl,_buf);                                                                \
 
344
        _ctrlb |= _ctrl;                                                                                                                \
 
345
        _ctrl <<= 1;                                                                                                                    \
 
346
        if (_len > 17)                                                                                                                  \
 
347
        {                                                                                                                                               \
 
348
                (_buf)[0] = (unsigned char)((((_off) & 0xf00) >> 4) | 0x0f);            \
 
349
                (_buf)[1] = (unsigned char)(((_off) & 0xff));                                           \
 
350
                (_buf)[2] = (unsigned char)((_len) - 18);                                                       \
 
351
                (_buf) += 3;                                                                                                            \
 
352
        } else {                                                                                                                                \
 
353
                (_buf)[0] = (unsigned char)((((_off) & 0xf00) >> 4) | ((_len) - 3)); \
 
354
                (_buf)[1] = (unsigned char)((_off) & 0xff);                                                     \
 
355
                (_buf) += 2;                                                                                                            \
 
356
        }                                                                                                                                               \
 
357
} while (0)
 
358
 
 
359
 
 
360
/* ----------
 
361
 * pglz_find_match -
 
362
 *
 
363
 *              Lookup the history table if the actual input stream matches
 
364
 *              another sequence of characters, starting somewhere earlier
 
365
 *              in the input buffer.
 
366
 * ----------
 
367
 */
 
368
static inline int
 
369
pglz_find_match(PGLZ_HistEntry **hstart, const char *input, const char *end,
 
370
                                int *lenp, int *offp, int good_match, int good_drop)
 
371
{
 
372
        PGLZ_HistEntry *hent;
 
373
        int32           len = 0;
 
374
        int32           off = 0;
 
375
 
 
376
        /*
 
377
         * Traverse the linked history list until a good enough match is found.
 
378
         */
 
379
        hent = hstart[pglz_hist_idx(input, end)];
 
380
        while (hent)
 
381
        {
 
382
                const char *ip = input;
 
383
                const char *hp = hent->pos;
 
384
                int32           thisoff;
 
385
                int32           thislen;
 
386
 
 
387
                /*
 
388
                 * Stop if the offset does not fit into our tag anymore.
 
389
                 */
 
390
                thisoff = ip - hp;
 
391
                if (thisoff >= 0x0fff)
 
392
                        break;
 
393
 
 
394
                /*
 
395
                 * Determine length of match. A better match must be larger than the
 
396
                 * best so far. And if we already have a match of 16 or more bytes,
 
397
                 * it's worth the call overhead to use memcmp() to check if this match
 
398
                 * is equal for the same size. After that we must fallback to
 
399
                 * character by character comparison to know the exact position where
 
400
                 * the diff occurred.
 
401
                 */
 
402
                thislen = 0;
 
403
                if (len >= 16)
 
404
                {
 
405
                        if (memcmp(ip, hp, len) == 0)
 
406
                        {
 
407
                                thislen = len;
 
408
                                ip += len;
 
409
                                hp += len;
 
410
                                while (ip < end && *ip == *hp && thislen < PGLZ_MAX_MATCH)
 
411
                                {
 
412
                                        thislen++;
 
413
                                        ip++;
 
414
                                        hp++;
 
415
                                }
 
416
                        }
 
417
                }
 
418
                else
 
419
                {
 
420
                        while (ip < end && *ip == *hp && thislen < PGLZ_MAX_MATCH)
 
421
                        {
 
422
                                thislen++;
 
423
                                ip++;
 
424
                                hp++;
 
425
                        }
 
426
                }
 
427
 
 
428
                /*
 
429
                 * Remember this match as the best (if it is)
 
430
                 */
 
431
                if (thislen > len)
 
432
                {
 
433
                        len = thislen;
 
434
                        off = thisoff;
 
435
                }
 
436
 
 
437
                /*
 
438
                 * Advance to the next history entry
 
439
                 */
 
440
                hent = hent->next;
 
441
 
 
442
                /*
 
443
                 * Be happy with lesser good matches the more entries we visited. But
 
444
                 * no point in doing calculation if we're at end of list.
 
445
                 */
 
446
                if (hent)
 
447
                {
 
448
                        if (len >= good_match)
 
449
                                break;
 
450
                        good_match -= (good_match * good_drop) / 100;
 
451
                }
 
452
        }
 
453
 
 
454
        /*
 
455
         * Return match information only if it results at least in one byte
 
456
         * reduction.
 
457
         */
 
458
        if (len > 2)
 
459
        {
 
460
                *lenp = len;
 
461
                *offp = off;
 
462
                return 1;
 
463
        }
 
464
 
 
465
        return 0;
 
466
}
 
467
 
 
468
 
 
469
/* ----------
 
470
 * pglz_compress -
 
471
 *
 
472
 *              Compresses source into dest using strategy.
 
473
 * ----------
 
474
 */
 
475
bool
 
476
pglz_compress(const char *source, int32 slen, PGLZ_Header *dest,
 
477
                          const PGLZ_Strategy *strategy)
 
478
{
 
479
        unsigned char *bp = ((unsigned char *) dest) + sizeof(PGLZ_Header);
 
480
        unsigned char *bstart = bp;
 
481
        int                     hist_next = 0;
 
482
        bool            hist_recycle = false;
 
483
        const char *dp = source;
 
484
        const char *dend = source + slen;
 
485
        unsigned char ctrl_dummy = 0;
 
486
        unsigned char *ctrlp = &ctrl_dummy;
 
487
        unsigned char ctrlb = 0;
 
488
        unsigned char ctrl = 0;
 
489
        bool            found_match = false;
 
490
        int32           match_len;
 
491
        int32           match_off;
 
492
        int32           good_match;
 
493
        int32           good_drop;
 
494
        int32           result_size;
 
495
        int32           result_max;
 
496
        int32           need_rate;
 
497
 
 
498
        /*
 
499
         * Our fallback strategy is the default.
 
500
         */
 
501
        if (strategy == NULL)
 
502
                strategy = PGLZ_strategy_default;
 
503
 
 
504
        /*
 
505
         * If the strategy forbids compression (at all or if source chunk size
 
506
         * out of range), fail.
 
507
         */
 
508
        if (strategy->match_size_good <= 0 ||
 
509
                slen < strategy->min_input_size ||
 
510
                slen > strategy->max_input_size)
 
511
                return false;
 
512
 
 
513
        /*
 
514
         * Save the original source size in the header.
 
515
         */
 
516
        dest->rawsize = slen;
 
517
 
 
518
        /*
 
519
         * Limit the match parameters to the supported range.
 
520
         */
 
521
        good_match = strategy->match_size_good;
 
522
        if (good_match > PGLZ_MAX_MATCH)
 
523
                good_match = PGLZ_MAX_MATCH;
 
524
        else if (good_match < 17)
 
525
                good_match = 17;
 
526
 
 
527
        good_drop = strategy->match_size_drop;
 
528
        if (good_drop < 0)
 
529
                good_drop = 0;
 
530
        else if (good_drop > 100)
 
531
                good_drop = 100;
 
532
 
 
533
        need_rate = strategy->min_comp_rate;
 
534
        if (need_rate < 0)
 
535
                need_rate = 0;
 
536
        else if (need_rate > 99)
 
537
                need_rate = 99;
 
538
 
 
539
        /*
 
540
         * Compute the maximum result size allowed by the strategy, namely
 
541
         * the input size minus the minimum wanted compression rate.  This had
 
542
         * better be <= slen, else we might overrun the provided output buffer.
 
543
         */
 
544
        if (slen > (INT_MAX/100))
 
545
        {
 
546
                /* Approximate to avoid overflow */
 
547
                result_max = (slen / 100) * (100 - need_rate);
 
548
        }
 
549
        else
 
550
                result_max = (slen * (100 - need_rate)) / 100;
 
551
 
 
552
        /*
 
553
         * Initialize the history lists to empty.  We do not need to zero the
 
554
         * hist_entries[] array; its entries are initialized as they are used.
 
555
         */
 
556
        memset(hist_start, 0, sizeof(hist_start));
 
557
 
 
558
        /*
 
559
         * Compress the source directly into the output buffer.
 
560
         */
 
561
        while (dp < dend)
 
562
        {
 
563
                /*
 
564
                 * If we already exceeded the maximum result size, fail.
 
565
                 *
 
566
                 * We check once per loop; since the loop body could emit as many as 4
 
567
                 * bytes (a control byte and 3-byte tag), PGLZ_MAX_OUTPUT() had better
 
568
                 * allow 4 slop bytes.
 
569
                 */
 
570
                if (bp - bstart >= result_max)
 
571
                        return false;
 
572
 
 
573
                /*
 
574
                 * If we've emitted more than first_success_by bytes without finding
 
575
                 * anything compressible at all, fail.  This lets us fall out
 
576
                 * reasonably quickly when looking at incompressible input (such as
 
577
                 * pre-compressed data).
 
578
                 */
 
579
                if (!found_match && bp - bstart >= strategy->first_success_by)
 
580
                        return false;
 
581
 
 
582
                /*
 
583
                 * Try to find a match in the history
 
584
                 */
 
585
                if (pglz_find_match(hist_start, dp, dend, &match_len,
 
586
                                                        &match_off, good_match, good_drop))
 
587
                {
 
588
                        /*
 
589
                         * Create the tag and add history entries for all matched
 
590
                         * characters.
 
591
                         */
 
592
                        pglz_out_tag(ctrlp, ctrlb, ctrl, bp, match_len, match_off);
 
593
                        while (match_len--)
 
594
                        {
 
595
                                pglz_hist_add(hist_start, hist_entries,
 
596
                                                          hist_next, hist_recycle,
 
597
                                                          dp, dend);
 
598
                                dp++;                   /* Do not do this ++ in the line above! */
 
599
                                /* The macro would do it four times - Jan.      */
 
600
                        }
 
601
                        found_match = true;
 
602
                }
 
603
                else
 
604
                {
 
605
                        /*
 
606
                         * No match found. Copy one literal byte.
 
607
                         */
 
608
                        pglz_out_literal(ctrlp, ctrlb, ctrl, bp, *dp);
 
609
                        pglz_hist_add(hist_start, hist_entries,
 
610
                                                  hist_next, hist_recycle,
 
611
                                                  dp, dend);
 
612
                        dp++;                           /* Do not do this ++ in the line above! */
 
613
                        /* The macro would do it four times - Jan.      */
 
614
                }
 
615
        }
 
616
 
 
617
        /*
 
618
         * Write out the last control byte and check that we haven't overrun the
 
619
         * output size allowed by the strategy.
 
620
         */
 
621
        *ctrlp = ctrlb;
 
622
        result_size = bp - bstart;
 
623
        if (result_size >= result_max)
 
624
                return false;
 
625
 
 
626
        /*
 
627
         * Success - need only fill in the actual length of the compressed datum.
 
628
         */
 
629
        SET_VARSIZE_COMPRESSED(dest, result_size + sizeof(PGLZ_Header));
 
630
 
 
631
        return true;
 
632
}
 
633
 
 
634
 
 
635
/* ----------
 
636
 * pglz_decompress -
 
637
 *
 
638
 *              Decompresses source into dest.
 
639
 * ----------
 
640
 */
 
641
void
 
642
pglz_decompress(const PGLZ_Header *source, char *dest)
 
643
{
 
644
        const unsigned char *sp;
 
645
        const unsigned char *srcend;
 
646
        unsigned char *dp;
 
647
        unsigned char *destend;
 
648
 
 
649
        sp = ((const unsigned char *) source) + sizeof(PGLZ_Header);
 
650
        srcend = ((const unsigned char *) source) + VARSIZE(source);
 
651
        dp = (unsigned char *) dest;
 
652
        destend = dp + source->rawsize;
 
653
 
 
654
        while (sp < srcend && dp < destend)
 
655
        {
 
656
                /*
 
657
                 * Read one control byte and process the next 8 items (or as many
 
658
                 * as remain in the compressed input).
 
659
                 */
 
660
                unsigned char ctrl = *sp++;
 
661
                int             ctrlc;
 
662
 
 
663
                for (ctrlc = 0; ctrlc < 8 && sp < srcend; ctrlc++)
 
664
                {
 
665
                        if (ctrl & 1)
 
666
                        {
 
667
                                /*
 
668
                                 * Otherwise it contains the match length minus 3 and the
 
669
                                 * upper 4 bits of the offset. The next following byte
 
670
                                 * contains the lower 8 bits of the offset. If the length is
 
671
                                 * coded as 18, another extension tag byte tells how much
 
672
                                 * longer the match really was (0-255).
 
673
                                 */
 
674
                                int32           len;
 
675
                                int32           off;
 
676
 
 
677
                                len = (sp[0] & 0x0f) + 3;
 
678
                                off = ((sp[0] & 0xf0) << 4) | sp[1];
 
679
                                sp += 2;
 
680
                                if (len == 18)
 
681
                                        len += *sp++;
 
682
 
 
683
                                /*
 
684
                                 * Check for output buffer overrun, to ensure we don't
 
685
                                 * clobber memory in case of corrupt input.  Note: we must
 
686
                                 * advance dp here to ensure the error is detected below
 
687
                                 * the loop.  We don't simply put the elog inside the loop
 
688
                                 * since that will probably interfere with optimization.
 
689
                                 */
 
690
                                if (dp + len > destend)
 
691
                                {
 
692
                                        dp += len;
 
693
                                        break;
 
694
                                }
 
695
 
 
696
                                /*
 
697
                                 * Now we copy the bytes specified by the tag from OUTPUT to
 
698
                                 * OUTPUT. It is dangerous and platform dependent to use
 
699
                                 * memcpy() here, because the copied areas could overlap
 
700
                                 * extremely!
 
701
                                 */
 
702
                                while (len--)
 
703
                                {
 
704
                                        *dp = dp[-off];
 
705
                                        dp++;
 
706
                                }
 
707
                        }
 
708
                        else
 
709
                        {
 
710
                                /*
 
711
                                 * An unset control bit means LITERAL BYTE. So we just copy
 
712
                                 * one from INPUT to OUTPUT.
 
713
                                 */
 
714
                                if (dp >= destend)      /* check for buffer overrun */
 
715
                                        break;                  /* do not clobber memory */
 
716
 
 
717
                                *dp++ = *sp++;
 
718
                        }
 
719
 
 
720
                        /*
 
721
                         * Advance the control bit
 
722
                         */
 
723
                        ctrl >>= 1;
 
724
                }
 
725
        }
 
726
 
 
727
        /*
 
728
         * Check we decompressed the right amount.
 
729
         */
 
730
        if (dp != destend || sp != srcend)
 
731
                elog(ERROR, "compressed data is corrupt");
 
732
 
 
733
        /*
 
734
         * That's it.
 
735
         */
 
736
}