Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
3 days ago bd039d1e92813358c5c5a1e346b49074baf513f2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
/*-------------------------------------------------------------------------
 * cfs_compress.c
 *    Compressed File Store (CFS) page-level compress/decompress helpers.
 *
 * Implements CfsCompressPage() and CfsDecompressPage(), which form the
 * core of the CFS I/O layer.  All CRC-32C checksums are computed with
 * PostgreSQL's standard pg_crc32c machinery.
 *
 * Scratch buffer layout used by CfsCompressPage():
 *
 *   [ CfsCompressedBlockHeader (fixed, CFS_BLOCK_HEADER_SIZE bytes) ]
 *   [ compressed payload    (variable, up to compress_bound)     ]
 *   [ alignment padding     (0–7 bytes, to reach CFS_BLOCK_ALIGN)]
 *
 * The header is filled last so that data_crc and hdr_crc can be
 * computed after compression completes.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *    src/backend/storage/cfs/cfs_compress.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include <string.h>
 
#include "port/pg_crc32c.h"
#include "storage/cfs/cfs.h"
#include "storage/cfs/cfs_codec.h"
#include "storage/cfs/cfs_compress.h"
 
/* ----------------------------------------------------------------
 * Internal helpers
 * ---------------------------------------------------------------- */
 
/*
 * cfs_crc32c_of
 *      Compute CRC-32C over a byte range.
 */
static inline pg_crc32c
cfs_crc32c_of(const void *data, size_t len)
{
    pg_crc32c   crc;
 
    INIT_CRC32C(crc);
    COMP_CRC32C(crc, data, len);
    FIN_CRC32C(crc);
    return crc;
}
 
uint32
CfsCrc32cPayload(const void *payload, size_t payload_size)
{
    return (uint32) cfs_crc32c_of(payload, payload_size);
}
 
/*
 * cfs_header_crc
 *      Compute the CRC-32C over all fields of *hdr* except hdr_crc itself.
 *      The hdr_crc field must be the last member of CfsCompressedBlockHeader.
 */
static inline pg_crc32c
cfs_header_crc(const CfsCompressedBlockHeader *hdr)
{
    /*
     * Cover everything up to (but not including) the hdr_crc field.
     * StaticAssertStmt would be cleaner but offsetof is available here.
     */
    size_t      covered = offsetof(CfsCompressedBlockHeader, hdr_crc);
 
    return cfs_crc32c_of(hdr, covered);
}
 
uint32
CfsCrc32cHeader(const CfsCompressedBlockHeader *hdr)
{
    return (uint32) cfs_header_crc(hdr);
}
 
/*
 * cfs_bytes_all_zero
 *      Return true when every byte in the range [p, p + len) is zero.
 *      Used to validate on-disk padding that no CRC covers.
 */
static bool
cfs_bytes_all_zero(const unsigned char *p, size_t len)
{
    size_t      i;
 
    for (i = 0; i < len; i++)
    {
        if (p[i] != 0)
            return false;
    }
    return true;
}
 
/*
 * CfsFillBlockHeader
 *      Populate a CfsCompressedBlockHeader and compute all three CRCs.
 *
 * Parameters:
 *   hdr             - destination header (caller-supplied)
 *   algorithm       - compression algorithm used
 *   compressed_data - pointer to the compressed payload
 *   compressed_size - byte count of the compressed payload
 *   original_data   - pointer to the original uncompressed page
 *   original_size   - byte count of the original page
 */
void
CfsFillBlockHeader(CfsCompressedBlockHeader *hdr,
                   CfsAlgorithm algorithm,
                   const void *compressed_data,
                   uint32 compressed_size,
                   const void *original_data,
                   uint32 original_size)
{
    hdr->magic = CFS_BLOCK_MAGIC;
    hdr->version = CFS_FORMAT_VERSION;
    hdr->algorithm = (uint8) algorithm;
    hdr->compressed_size = compressed_size;
    hdr->original_size = original_size;
 
    /* Compute CRC over the original uncompressed page. */
    hdr->orig_crc = CfsCrc32cPayload(original_data, original_size);
    hdr->data_crc = CfsCrc32cPayload(compressed_data, compressed_size);
    hdr->hdr_crc = CfsCrc32cHeader(hdr);
}
 
 
/* ----------------------------------------------------------------
 * Public API: CfsCompressPage.
 * ---------------------------------------------------------------- */
 
/*
 * CfsCompressScratchSize
 *      Return the minimum scratch buffer size needed by CfsCompressPage().
 *
 * We need room for:
 *   - one CfsCompressedBlockHeader
 *   - the maximum possible compressed output for any supported algorithm
 *     (worst case is LZ4CompressBound, which exceeds ZstdCompressBound
 *      for typical page sizes)
 *   - CFS_BLOCK_ALIGN bytes of padding
 */
size_t
CfsCompressScratchSize(size_t page_size)
{
    size_t      max_bound = 0;
    size_t      bound;
    int         i;
 
    for (i = 0; i < CFS_ALGORITHM_COUNT; i++)
    {
        const CfsCodec *codec = CfsCodecTable[i];
 
        if (codec == NULL || codec->compress_bound == NULL)
            continue;
        bound = codec->compress_bound(page_size);
        if (bound > max_bound)
            max_bound = bound;
    }
 
    /*
     * Header + worst-case payload + alignment slop.
     */
    return CFS_BLOCK_HEADER_SIZE + max_bound + CFS_BLOCK_ALIGN;
}
 
/*
 * CfsCompressPage / CfsCompressPageNoCopy — compress one PostgreSQL page
 * and format the result as a CfsCompressedBlockHeader + payload blob in
 * the caller's scratch buffer.
 *
 * If the chosen algorithm fails to shrink the data by at least
 * opts->min_gain_bytes, the page is stored RAW (verbatim copy) and
 * result->is_raw is set to true.
 *
 * The two entry points share one decision core and differ only in how a
 * RAW result is presented:
 *
 *   CfsCompressPage       — the contiguous contract every pre-D4 consumer
 *                           relies on: the payload is copied into the
 *                           scratch buffer and result_data spans the whole
 *                           record (payload_external stays false).
 *
 *   CfsCompressPageNoCopy — the D4 write-path form: a RAW result is NOT
 *                           copied; only the 28-byte header is built in
 *                           the scratch buffer, payload_data points at the
 *                           caller's original page and the append path
 *                           writes [header][page][zero padding] with
 *                           cfs_pwritev_all().  The on-disk record is
 *                           byte-identical to the copied form.  Compressed
 *                           results are always contiguous in both forms.
 */
static void
compress_page_core(const void *page,
                   size_t page_size,
                   const CfsCompressOptions *opts,
                   void *scratch,
                   size_t scratch_sz,
                   bool raw_nocopy,
                   CfsCompressResult *result)
{
    const CfsCodec *codec;
    CfsCodecState *state;
    CfsCompressedBlockHeader *hdr;
    void       *payload_buf;
    size_t      payload_capacity;
    size_t      compressed_size;
    CfsCodecResult codec_rc;
    bool        store_raw;
    bool        payload_verbatim;
    bool        allow_raw_fallback;
    CfsAlgorithm actual_algorithm;
 
    Assert(page != NULL);
    Assert(opts != NULL);
    Assert(scratch != NULL);
    Assert(result != NULL);
 
    if (page_size != CFS_BLCKSZ)
    {
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("CFS: page_size %zu is not CFS_BLCKSZ %d",
                        page_size, CFS_BLCKSZ)));
    }
 
    /* Verify scratch buffer is large enough. */
    if (scratch_sz < CfsCompressScratchSize(page_size))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INTERNAL_ERROR),
                 errmsg("CFS: scratch buffer too small: need %zu, got %zu",
                        CfsCompressScratchSize(page_size), scratch_sz)));
    }
 
    /* Layout: [header][payload ...] inside scratch */
    hdr = (CfsCompressedBlockHeader *) scratch;
    payload_buf = (char *) scratch + CFS_BLOCK_HEADER_SIZE;
    payload_capacity = scratch_sz - CFS_BLOCK_HEADER_SIZE - CFS_BLOCK_ALIGN;
 
    store_raw = false;
    payload_verbatim = false;
    allow_raw_fallback = opts->allow_raw_fallback || !opts->explicit_algorithm;
    actual_algorithm = opts->algorithm;
    codec_rc = CFS_CODEC_NOOP;  /* assume no compression initially */
 
    /*
     * The no-copy form never runs the RAW codec (whose whole job is to
     * memcpy the page into the payload): the record is written straight
     * from the caller's page below, byte-identical to the copied form.
     */
    if (raw_nocopy && opts->algorithm == CFS_ALGORITHM_RAW)
        store_raw = true;
 
    codec = CfsCodecLookup(opts->algorithm);
    if (codec == NULL || !codec->available())
    {
        if (opts->explicit_algorithm || !allow_raw_fallback)
            ereport(ERROR,
                    (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                     errmsg("CFS: algorithm %d not available",
                            (int) opts->algorithm),
                     errhint("Select an available algorithm or enable RAW fallback.")));
        ereport(DEBUG1,
                (errmsg("CFS: algorithm %d not available, falling back to RAW",
                        (int) opts->algorithm)));
        store_raw = true;
    }
    else if (!store_raw)
    {
        state = CfsCodecStateCreate(opts->algorithm);
        if (state == NULL)
        {
            if (opts->explicit_algorithm || !allow_raw_fallback)
                ereport(ERROR,
                        (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
                         errmsg("CFS: could not create codec state for algorithm %d",
                                (int) opts->algorithm)));
            ereport(DEBUG1,
                    (errmsg("CFS: could not create codec state for algorithm %d, falling back to RAW",
                            (int) opts->algorithm)));
            store_raw = true;
        }
        else
        {
            codec_rc = codec->compress(state,
                                       page, page_size,
                                       payload_buf, payload_capacity,
                                       opts->level,
                                       &compressed_size);
 
            /*
             * A successful RAW compression already left the verbatim page in
             * the payload, so the store_raw path below must not copy again.
             */
            if (codec_rc == CFS_CODEC_OK &&
                opts->algorithm == CFS_ALGORITHM_RAW)
                payload_verbatim = true;
        }
    }
 
    /*
     * Decide whether to accept the compressed form or fall back to RAW.
     * Conditions for RAW: (a) codec is unavailable, or (b) codec returned
     * OVERFLOW / NOOP, or (c) compressed output is not small enough
     * (min_gain_bytes).  A RAW page always lands here because its gain is
     * zero.
     */
    if (!store_raw)
    {
        if (codec_rc == CFS_CODEC_OK)
        {
            /* Check minimum gain requirement */
            if (page_size > compressed_size &&
                (page_size - compressed_size) >= opts->min_gain_bytes)
            {
                /* Accept compressed form, nothing more to do. */
            }
            else
            {
                /* Not worth compressing */
                store_raw = true;
            }
        }
        else if (codec_rc == CFS_CODEC_NOOP || codec_rc == CFS_CODEC_OVERFLOW)
        {
            if (!allow_raw_fallback)
                ereport(ERROR,
                        (errcode(ERRCODE_INTERNAL_ERROR),
                         errmsg("CFS: compression did not produce a storable compressed block")));
            store_raw = true;
        }
        else
        {
            /* Unexpected codec error */
            if (!allow_raw_fallback)
                ereport(ERROR,
                        (errcode(ERRCODE_INTERNAL_ERROR),
                         errmsg("CFS: compression failed (algorithm=%d, rc=%d)",
                                (int) opts->algorithm, (int) codec_rc)));
            ereport(DEBUG1,
                    (errmsg("CFS: compression error (algorithm=%d, rc=%d), falling back to RAW",
                            (int) opts->algorithm, (int) codec_rc)));
            store_raw = true;
        }
    }
 
    if (store_raw)
    {
        compressed_size = (uint32) page_size;
        actual_algorithm = CFS_ALGORITHM_RAW;
 
        /*
         * Contiguous form: copy the page verbatim into the payload region
         * of the scratch buffer (the pre-D4 contract every consumer of
         * result_data relies on), unless a successful RAW codec already
         * left the verbatim page there.
         */
        if (!raw_nocopy && !payload_verbatim)
            memcpy(payload_buf, page, page_size);
 
        /*
         * The no-copy form leaves the payload at the caller's page — no
         * 8 KiB memcpy into the scratch buffer.  Only the 28-byte header
         * is built here; the record is written as [header][page][zero
         * padding] by cfs_pwritev_all(), byte-identical to the copied
         * form (the payload CRC below runs over the original page).
         */
    }
 
    /*
     * Make every on-disk byte of this record deterministic.  The scratch
     * buffer is allocated with palloc() (not palloc0) and reused across
     * writes, so any byte that is neither explicitly assigned nor covered by
     * a CRC would otherwise carry stale backend memory to disk -- a silent
     * leak, since none of these bytes are covered by any CRC.  The header
     * MemSet also zeroes the two trailing alignment bytes of the header
     * struct that no field assigns; the scratch record tail below covers the
     * contiguous forms, while the external RAW tail is written from the
     * append path's zero buffer.
     */
    MemSet(hdr, 0, sizeof(CfsCompressedBlockHeader));
    {
        size_t      rec_size = CFS_RECORD_SIZE(compressed_size);
        size_t      rec_tail = rec_size - CFS_BLOCK_HEADER_SIZE - compressed_size;
        bool        payload_in_scratch = !(store_raw && raw_nocopy);
 
        if (payload_in_scratch && rec_tail > 0)
            MemSet((char *) payload_buf + compressed_size, 0, rec_tail);
    }
 
    /* Fill and checksum the header */
    CfsFillBlockHeader(hdr,
                       actual_algorithm,
                       (store_raw && raw_nocopy) ? page : payload_buf,
                       (uint32) compressed_size,
                       page, (uint32) page_size);
 
    /* Build result descriptor */
    result->result_data = scratch;
    result->total_size = CFS_RECORD_SIZE(compressed_size);
    result->compressed_size = (uint32) compressed_size;
    result->algorithm_used = actual_algorithm;
    result->is_raw = store_raw;
    result->payload_external = (store_raw && raw_nocopy);
    result->payload_data = result->payload_external ?
        (void *) page : payload_buf;
    result->padding_bytes = result->total_size - CFS_BLOCK_HEADER_SIZE -
        compressed_size;
 
    Assert(result->total_size <= scratch_sz);
    Assert(!result->payload_external ||
           result->padding_bytes < CFS_BLOCK_ALIGN);
}
 
/*
 * The two public entry points (see the contract comment above the core).
 */
void
CfsCompressPage(const void *page,
                size_t page_size,
                const CfsCompressOptions *opts,
                void *scratch,
                size_t scratch_sz,
                CfsCompressResult *result)
{
    compress_page_core(page, page_size, opts, scratch, scratch_sz,
                       false, result);
}
 
void
CfsCompressPageNoCopy(const void *page,
                      size_t page_size,
                      const CfsCompressOptions *opts,
                      void *scratch,
                      size_t scratch_sz,
                      CfsCompressResult *result)
{
    compress_page_core(page, page_size, opts, scratch, scratch_sz,
                       true, result);
}
 
 
/* ----------------------------------------------------------------
 * Public API: CfsDecompressPage.
 * ---------------------------------------------------------------- */
 
/*
 * CfsVerifyBlockHeader
 *      Validate magic, version, and CRC of a CfsCompressedBlockHeader.
 *      Returns true on success, false on any mismatch.
 */
bool
CfsVerifyBlockHeader(const CfsCompressedBlockHeader *hdr)
{
    pg_crc32c   expected_crc;
 
    if (hdr->magic != CFS_BLOCK_MAGIC)
    {
        ereport(WARNING,
                (errmsg("CFS: bad magic in block header: 0x%08X (expected 0x%08X)",
                        hdr->magic, CFS_BLOCK_MAGIC)));
        return false;
    }
 
    if (hdr->version != CFS_FORMAT_VERSION)
    {
        ereport(WARNING,
                (errmsg("CFS: unsupported block header version %u (expected %u)",
                        (unsigned) hdr->version, (unsigned) CFS_FORMAT_VERSION)));
        return false;
    }
 
    if (!CFS_ALGORITHM_VALID((CfsAlgorithm) hdr->algorithm))
    {
        ereport(WARNING,
                (errmsg("CFS: unknown algorithm %u in block header",
                        (unsigned) hdr->algorithm)));
        return false;
    }
 
    expected_crc = (pg_crc32c) cfs_header_crc(hdr);
    if (!EQ_CRC32C(expected_crc, (pg_crc32c) hdr->hdr_crc))
    {
        ereport(WARNING,
                (errmsg("CFS: header CRC mismatch: computed 0x%08X, stored 0x%08X",
                        (unsigned) expected_crc, (unsigned) hdr->hdr_crc)));
        return false;
    }
 
    return true;
}
 
/*
 * CfsDecompressPage
 *      Decompress a .cfp record back into a full uncompressed page,
 *      verifying all three CRC-32C checksums.
 */
CfsDecompressStatus
CfsDecompressPage(const void *compressed_data,
                  size_t data_size,
                  void *out_page,
                  size_t out_page_size,
                  CfsDecompressResult *result)
{
    const CfsCompressedBlockHeader *hdr;
    const void *payload;
    size_t      payload_size;
    const CfsCodec *codec;
    CfsCodecState *state;
    pg_crc32c   computed_crc;
    CfsCodecResult codec_rc;
    size_t      decompressed_size;
 
    Assert(compressed_data != NULL);
    Assert(out_page != NULL);
 
    if (data_size < CFS_BLOCK_HEADER_SIZE)
    {
        ereport(WARNING,
                (errmsg("CFS: compressed_data too small for header: %zu bytes",
                        data_size)));
        return CFS_DECOMPRESS_BAD_HDR;
    }
 
    hdr = (const CfsCompressedBlockHeader *) compressed_data;
 
    /* Validate header magic, version, and checksum. */
    if (!CfsVerifyBlockHeader(hdr))
        return CFS_DECOMPRESS_BAD_HDR;
 
    /* Every record stores a full 8 kB page. */
    if (hdr->original_size != CFS_BLCKSZ)
    {
        ereport(WARNING,
                (errmsg("CFS: original_size %u is not CFS_BLCKSZ %d",
                        (unsigned) hdr->original_size, CFS_BLCKSZ)));
        return CFS_DECOMPRESS_BAD_HDR;
    }
 
    payload = (const char *) compressed_data + CFS_BLOCK_HEADER_SIZE;
    payload_size = hdr->compressed_size;
 
    /* Check that payload fits within data_size. */
    if (CFS_BLOCK_HEADER_SIZE + payload_size > data_size)
    {
        ereport(WARNING,
                (errmsg("CFS: payload_size %u exceeds available data %zu",
                        hdr->compressed_size,
                        data_size - CFS_BLOCK_HEADER_SIZE)));
        return CFS_DECOMPRESS_BAD_HDR;
    }
 
    /* Verify payload (compressed data) CRC. */
    computed_crc = (pg_crc32c) cfs_crc32c_of(payload, payload_size);
    if (!EQ_CRC32C(computed_crc, (pg_crc32c) hdr->data_crc))
    {
        ereport(WARNING,
                (errmsg("CFS: payload CRC mismatch: computed 0x%08X, stored 0x%08X",
                        (unsigned) computed_crc, (unsigned) hdr->data_crc)));
        return CFS_DECOMPRESS_BAD_DATA;
    }
 
    /*
     * Record tail padding ([header + compressed_size,
     * CFS_RECORD_SIZE(compressed_size))) is written to disk but covered by no
     * CRC; it must always be zero.  Only bytes actually present within
     * data_size are checked.
     */
    {
        size_t      rec_size = CFS_RECORD_SIZE(payload_size);
        size_t      available = data_size - CFS_BLOCK_HEADER_SIZE;
        size_t      pad_end = Min(rec_size - CFS_BLOCK_HEADER_SIZE, available);
 
        if (pad_end > payload_size &&
            !cfs_bytes_all_zero((const unsigned char *) payload + payload_size,
                                pad_end - payload_size))
        {
            ereport(WARNING,
                    (errmsg("CFS: nonzero byte in record tail padding")));
            return CFS_DECOMPRESS_BAD_DATA;
        }
    }
 
    /* Ensure output buffer is large enough. */
    if (out_page_size < hdr->original_size)
    {
        ereport(WARNING,
                (errmsg("CFS: output buffer too small: need %u, got %zu",
                        hdr->original_size, out_page_size)));
        return CFS_DECOMPRESS_ERROR;
    }
 
    /* Decompress through the codec table (RAW is a codec too). */
    codec = CfsCodecLookup((CfsAlgorithm) hdr->algorithm);
    if (codec == NULL || !codec->available())
    {
        ereport(WARNING,
                (errmsg("CFS: algorithm %u not available in this build, cannot decompress page",
                        (unsigned) hdr->algorithm),
                 errhint("Rebuild with --with-lz4 or --with-zstd to enable this codec.")));
        return CFS_DECOMPRESS_ERROR;
    }
 
    state = CfsCodecStateCreate((CfsAlgorithm) hdr->algorithm);
    if (state == NULL)
    {
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("CFS: could not create codec state for algorithm %u",
                        (unsigned) hdr->algorithm)));
        return CFS_DECOMPRESS_ERROR;    /* unreachable */
    }
 
    codec_rc = codec->decompress(state,
                                 payload, payload_size,
                                 out_page, out_page_size,
                                 hdr->original_size,
                                 &decompressed_size);
    if (codec_rc != CFS_CODEC_OK)
    {
        ereport(WARNING,
                (errmsg("CFS: decompression failed (algorithm=%u, rc=%d)",
                        (unsigned) hdr->algorithm, (int) codec_rc)));
        return CFS_DECOMPRESS_CORRUPT;
    }
 
    /* The codec must reproduce exactly the original page size. */
    if (decompressed_size != hdr->original_size)
    {
        ereport(WARNING,
                (errmsg("CFS: decompressed size %zu != original_size %u",
                        decompressed_size, hdr->original_size)));
        return CFS_DECOMPRESS_CORRUPT;
    }
 
    /* Verify original page CRC after decompression. */
    computed_crc = (pg_crc32c) cfs_crc32c_of(out_page, decompressed_size);
    if (!EQ_CRC32C(computed_crc, (pg_crc32c) hdr->orig_crc))
    {
        ereport(WARNING,
                (errmsg("CFS: original page CRC mismatch after decompression: computed 0x%08X, stored 0x%08X",
                        (unsigned) computed_crc, (unsigned) hdr->orig_crc)));
        return CFS_DECOMPRESS_BAD_ORIG;
    }
 
    if (result != NULL)
    {
        result->decompressed_size = decompressed_size;
        result->algorithm_used = (CfsAlgorithm) hdr->algorithm;
        result->is_raw = (hdr->algorithm == CFS_ALGORITHM_RAW);
    }
 
    return CFS_DECOMPRESS_OK;
}
 
CfsAlgorithm
CfsAlgorithmFromName(const char *name)
{
    int         i;
 
    if (name == NULL)
        return CFS_ALGORITHM_COUNT;
    for (i = 0; i < CFS_ALGORITHM_COUNT; i++)
    {
        if (pg_strcasecmp(name, CfsAlgorithmName[i]) == 0)
            return (CfsAlgorithm) i;
    }
    return CFS_ALGORITHM_COUNT;
}
 
const char *
CfsAlgorithmGetName(CfsAlgorithm algorithm)
{
    if (!CFS_ALGORITHM_VALID(algorithm))
        return "unknown";
    return CfsAlgorithmName[algorithm];
}
 
 
/* ----------------------------------------------------------------
 * Status string helpers
 * ---------------------------------------------------------------- */
 
const char *
CfsDecompressStatusString(CfsDecompressStatus status)
{
    switch (status)
    {
        case CFS_DECOMPRESS_OK:
            return "ok";
        case CFS_DECOMPRESS_BAD_HDR:
            return "bad header (magic/version/CRC mismatch)";
        case CFS_DECOMPRESS_BAD_DATA:
            return "compressed payload CRC mismatch";
        case CFS_DECOMPRESS_CORRUPT:
            return "decompression reported corrupt data";
        case CFS_DECOMPRESS_BAD_ORIG:
            return "original page CRC mismatch after decompression";
        case CFS_DECOMPRESS_ERROR:
            return "internal error";
        default:
            return "unknown";
    }
}