Исходный код СУБД RuDB — свободной СУБД с открытым исходным кодом на базе PostgreSQL
rudb
2 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
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
/*-------------------------------------------------------------------------
 *
 * cfs_codec.c
 *    Compressed File Store (CFS) codec dispatch table implementation.
 *
 * Provides concrete implementations of the CfsCodec vtable for:
 *   - RAW    (identity pass-through, no library required)
 *   - LZ4    (requires liblz4, guarded by USE_LZ4)
 *   - Zstd   (requires libzstd, guarded by USE_ZSTD)
 *
 * Per-backend state (Zstd contexts) is cached in a static array indexed
 * by CfsAlgorithm so that we avoid repeated allocation on the I/O hot path.
 *
 * Copyright (c) 2026, Kirillov Vyacheslav by AI, QDB Development Group
 *
 * IDENTIFICATION
 *    src/backend/storage/cfs/cfs_codec.c
 *
 *-------------------------------------------------------------------------
 */
#include "postgres.h"
 
#include <string.h>
 
#ifdef USE_LZ4
#include <lz4.h>
#include <lz4hc.h>
#endif
 
#ifdef USE_ZSTD
#include <zstd.h>
#include <zstd_errors.h>
#endif
 
#include "storage/cfs/cfs.h"
#include "storage/cfs/cfs_codec.h"
#include "storage/cfs/cfs_guc.h"
#include "utils/memutils.h"
 
StaticAssertDecl(CFS_BLCKSZ == BLCKSZ,
                 "CFS_BLCKSZ must match PostgreSQL BLCKSZ");
 
/* ----------------------------------------------------------------
 * Opaque per-backend state
 * ---------------------------------------------------------------- */
struct CfsCodecState
{
#ifdef USE_ZSTD
    ZSTD_CCtx  *zstd_cctx;      /* compression context   */
    ZSTD_DCtx  *zstd_dctx;      /* decompression context */
#endif
    /* LZ4 block API is stateless, so no context is needed. */
    int         _dummy;         /* keep struct non-empty if no libs */
};
 
/*
 * One cached state per algorithm per backend.
 * Initialised lazily by CfsCodecStateCreate().
 */
static CfsCodecState *backend_states[CFS_ALGORITHM_COUNT];
 
 
/* ================================================================
 * RAW codec (identity, no compression)
 * ================================================================ */
 
static CfsCodecState *
raw_state_create(void)
{
    CfsCodecState *s = palloc0(sizeof(CfsCodecState));
 
    ereport(DEBUG1,
            (errmsg(("CFS: initialized RAW codec state"))));
    return s;
}
 
static void
raw_state_destroy(CfsCodecState *state)
{
    if (state)
        pfree(state);
}
 
static CfsCodecResult
raw_compress(CfsCodecState *state,
             const void *src, size_t src_size,
             void *dst, size_t dst_size,
             int level, size_t *out_size)
{
    if (dst_size < src_size)
        return CFS_CODEC_OVERFLOW;
    memcpy(dst, src, src_size);
    *out_size = src_size;
    return CFS_CODEC_OK;
}
 
static CfsCodecResult
raw_decompress(CfsCodecState *state,
               const void *src, size_t src_size,
               void *dst, size_t dst_size,
               size_t expected_size, size_t *out_size)
{
    if (src_size > dst_size)
        return CFS_CODEC_CORRUPT;
    memcpy(dst, src, src_size);
    *out_size = src_size;
    return CFS_CODEC_OK;
}
 
static size_t
raw_compress_bound(size_t src_size)
{
    return src_size;
}
 
static bool
raw_available(void)
{
    return true;
}
 
static const CfsCodec cfs_codec_raw = {
    .algorithm = CFS_ALGORITHM_RAW,
    .state_create = raw_state_create,
    .state_destroy = raw_state_destroy,
    .compress = raw_compress,
    .decompress = raw_decompress,
    .compress_bound = raw_compress_bound,
    .available = raw_available,
};
 
 
/* ================================================================
 * LZ4 codec
 * ================================================================ */
 
static CfsCodecState *
lz4_state_create(void)
{
#ifndef USE_LZ4
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("CFS compression algorithm \"lz4\" is not available in this build"),
             errhint("Rebuild the server with --with-lz4.")));
    return NULL;
#else
    CfsCodecState *s = palloc0(sizeof(CfsCodecState));
 
    /* LZ4 block API is stateless, so nothing else is initialized. */
    ereport(DEBUG1,
            (errmsg(("CFS: initialized LZ4 codec state"))));
    return s;
#endif
}
 
static void
lz4_state_destroy(CfsCodecState *state)
{
    if (state)
        pfree(state);
}
 
static CfsCodecResult
lz4_compress(CfsCodecState *state,
             const void *src, size_t src_size,
             void *dst, size_t dst_size,
             int level, size_t *out_size)
{
#ifndef USE_LZ4
    return CFS_CODEC_UNAVAIL;
#else
    int         compressed;
    int         dst_capacity;
 
    /*
     * LZ4 API uses int for sizes; guard against overflow on hypothetical huge
     * pages (BLCKSZ is 8 kB, so this is just future-proofing).
     */
    if (dst_size > (size_t) PG_INT32_MAX)
        return CFS_CODEC_OVERFLOW;
    dst_capacity = (int) dst_size;
 
    Assert(level >= CFS_COMPRESS_LEVEL_MIN && level <= CFS_LZ4_LEVEL_MAX);
 
    /*
     * Clamp defensively, mirroring zstd_compress(): release builds have no
     * Assert, and liblz4 silently treats any level above LZ4HC_CLEVEL_MAX as
     * that maximum.  The Assert stays above the clamp so a debug build still
     * flags a caller that violates the contract.
     */
    if (level > CFS_LZ4_LEVEL_MAX)
        level = CFS_LZ4_LEVEL_MAX;
 
    if (level <= 2)
    {
        /*
         * Fast mode: levels 1..2 select two accelerations (2 and 1), so level
         * 2 is a touch slower and compresses a touch better.
         */
        compressed = LZ4_compress_fast((const char *) src,
                                       (char *) dst,
                                       (int) src_size,
                                       dst_capacity,
                                       3 - level);
    }
    else
    {
        /*
         * LZ4_compress_HC offers better ratio at the cost of speed; levels
         * 3..12 map 1:1 to the LZ4 HC levels.
         */
        compressed = LZ4_compress_HC((const char *) src,
                                     (char *) dst,
                                     (int) src_size,
                                     dst_capacity,
                                     level);
    }
 
    if (compressed <= 0)
        return CFS_CODEC_OVERFLOW;  /* output didn't fit or library error */
 
    *out_size = (size_t) compressed;
    return CFS_CODEC_OK;
#endif
}
 
static CfsCodecResult
lz4_decompress(CfsCodecState *state,
               const void *src, size_t src_size,
               void *dst, size_t dst_size,
               size_t expected_size, size_t *out_size)
{
#ifndef USE_LZ4
    return CFS_CODEC_UNAVAIL;
#else
    int         decompressed;
 
    if (expected_size > dst_size)
        return CFS_CODEC_CORRUPT;
 
    decompressed = LZ4_decompress_safe((const char *) src,
                                       (char *) dst,
                                       (int) src_size,
                                       (int) expected_size);
    if (decompressed < 0)
        return CFS_CODEC_CORRUPT;
 
    if ((size_t) decompressed != expected_size)
        return CFS_CODEC_CORRUPT;
 
    *out_size = (size_t) decompressed;
    return CFS_CODEC_OK;
#endif
}
 
static size_t
lz4_compress_bound(size_t src_size)
{
#ifndef USE_LZ4
    return src_size + src_size / 4 + 16;    /* conservative fallback */
#else
    return (size_t) LZ4_compressBound((int) src_size);
#endif
}
 
static bool
lz4_available(void)
{
#ifdef USE_LZ4
    /* Debug fault injection: pretend the library was not compiled in. */
    if (cfs_debug_disable_codecs & (1 << CFS_ALGORITHM_LZ4))
        return false;
    return true;
#else
    return false;
#endif
}
 
static const CfsCodec cfs_codec_lz4 = {
    .algorithm = CFS_ALGORITHM_LZ4,
    .state_create = lz4_state_create,
    .state_destroy = lz4_state_destroy,
    .compress = lz4_compress,
    .decompress = lz4_decompress,
    .compress_bound = lz4_compress_bound,
    .available = lz4_available,
};
 
 
/* ================================================================
 * Zstd codec
 * ================================================================ */
 
static CfsCodecState *
zstd_state_create(void)
{
#ifndef USE_ZSTD
    ereport(ERROR,
            (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
             errmsg("CFS compression algorithm \"zstd\" is not available in this build"),
             errhint("Rebuild the server with --with-zstd.")));
    return NULL;
#else
    CfsCodecState *s = palloc0(sizeof(CfsCodecState));
 
 
    s->zstd_cctx = ZSTD_createCCtx();
    if (s->zstd_cctx == NULL)
    {
        pfree(s);
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("could not create Zstd compression context")));
    }
 
    s->zstd_dctx = ZSTD_createDCtx();
    if (s->zstd_dctx == NULL)
    {
        ZSTD_freeCCtx(s->zstd_cctx);
        pfree(s);
        ereport(ERROR,
                (errcode(ERRCODE_OUT_OF_MEMORY),
                 errmsg("could not create Zstd decompression context")));
    }
 
    ereport(DEBUG1,
            (errmsg(("CFS: initialized Zstd codec state"))));
    return s;
#endif
}
 
static void
zstd_state_destroy(CfsCodecState *state)
{
    if (!state)
        return;
#ifdef USE_ZSTD
    if (state->zstd_cctx)
        ZSTD_freeCCtx(state->zstd_cctx);
    if (state->zstd_dctx)
        ZSTD_freeDCtx(state->zstd_dctx);
#endif
    pfree(state);
}
 
static CfsCodecResult
zstd_compress(CfsCodecState *state,
              const void *src, size_t src_size,
              void *dst, size_t dst_size,
              int level, size_t *out_size)
{
#ifndef USE_ZSTD
    return CFS_CODEC_UNAVAIL;
#else
    size_t      result;
    int         zstd_level;
 
    /* Clamp to Zstd's [1, ZSTD_maxCLevel()] range */
    zstd_level = (level < 1) ? 1 : level;
    if (zstd_level > ZSTD_maxCLevel())
        zstd_level = ZSTD_maxCLevel();
 
    result = ZSTD_compressCCtx(state->zstd_cctx,
                               dst, dst_size,
                               src, src_size,
                               zstd_level);
 
    if (ZSTD_isError(result))
    {
        if (ZSTD_getErrorCode(result) == ZSTD_error_dstSize_tooSmall)
            return CFS_CODEC_OVERFLOW;
        ereport(WARNING,
                (errmsg("Zstd compression error: %s",
                        ZSTD_getErrorName(result))));
        return CFS_CODEC_ERROR;
    }
 
    *out_size = result;
    return CFS_CODEC_OK;
#endif
}
 
static CfsCodecResult
zstd_decompress(CfsCodecState *state,
                const void *src, size_t src_size,
                void *dst, size_t dst_size,
                size_t expected_size, size_t *out_size)
{
#ifndef USE_ZSTD
    return CFS_CODEC_UNAVAIL;
#else
    size_t      result;
 
    result = ZSTD_decompressDCtx(state->zstd_dctx,
                                 dst, dst_size,
                                 src, src_size);
 
    if (ZSTD_isError(result))
    {
        ereport(WARNING,
                (errmsg("Zstd decompression error: %s",
                        ZSTD_getErrorName(result))));
        return CFS_CODEC_CORRUPT;
    }
 
    if (result != expected_size)
    {
        ereport(WARNING,
                (errmsg("Zstd decompressed %zu bytes, expected %zu",
                        result, expected_size)));
        return CFS_CODEC_CORRUPT;
    }
 
    *out_size = result;
    return CFS_CODEC_OK;
#endif
}
 
static size_t
zstd_compress_bound(size_t src_size)
{
#ifndef USE_ZSTD
    return src_size + src_size / 4 + 128;   /* conservative fallback */
#else
    return ZSTD_compressBound(src_size);
#endif
}
 
static bool
zstd_available(void)
{
#ifdef USE_ZSTD
    /* Debug fault injection: pretend the library was not compiled in. */
    if (cfs_debug_disable_codecs & (1 << CFS_ALGORITHM_ZSTD))
        return false;
    return true;
#else
    return false;
#endif
}
 
static const CfsCodec cfs_codec_zstd = {
    .algorithm = CFS_ALGORITHM_ZSTD,
    .state_create = zstd_state_create,
    .state_destroy = zstd_state_destroy,
    .compress = zstd_compress,
    .decompress = zstd_decompress,
    .compress_bound = zstd_compress_bound,
    .available = zstd_available,
};
 
 
/* ================================================================
 * Global dispatch table
 * ================================================================ */
 
 
/*
    * Demo compatibility adapters for the independently implemented codecs.
    * PGLZ is stateless; ZLIB owns pre-warmed backend-local streams.
    * Do not change existing RAW/LZ4/ZSTD on-disk algorithm values.
    */
extern bool cfs_codec_pglz_available(void);
extern Size cfs_codec_pglz_bound(Size);
extern CfsCodecResult cfs_codec_pglz_compress(const char *, Size, char *, Size, int, Size *);
extern CfsCodecResult cfs_codec_pglz_decompress(const char *, Size, char *, Size);
extern bool cfs_codec_zlib_available(void);
extern bool cfs_codec_zlib_prepare(void);
extern void cfs_codec_zlib_release(void);
extern Size cfs_codec_zlib_bound(Size);
extern CfsCodecResult cfs_codec_zlib_compress(const char *, Size, char *, Size, int, Size *);
extern CfsCodecResult cfs_codec_zlib_decompress(const char *, Size, char *, Size);
 
static CfsCodecResult
pglz_demo_compress(CfsCodecState *state, const void *src, size_t src_size,
                    void *dst, size_t dst_size, int level, size_t *out_size)
{
    (void) state;
    return cfs_codec_pglz_compress((const char *) src, src_size,
                                    (char *) dst, dst_size, level, out_size);
}
 
static CfsCodecResult
pglz_demo_decompress(CfsCodecState *state, const void *src, size_t src_size,
                        void *dst, size_t dst_size, size_t expected_size,
                        size_t *out_size)
{
    CfsCodecResult rc;
    (void) state;
    if (expected_size > dst_size)
        return CFS_CODEC_CORRUPT;
    rc = cfs_codec_pglz_decompress((const char *) src, src_size,
                                    (char *) dst, expected_size);
    if (rc == CFS_CODEC_OK)
        *out_size = expected_size;
    return rc;
}
 
static CfsCodecState *
zlib_demo_state_create(void)
{
    if (!cfs_codec_zlib_prepare())
        return NULL;
    return raw_state_create();
}
 
static void
zlib_demo_state_destroy(CfsCodecState *state)
{
    cfs_codec_zlib_release();
    raw_state_destroy(state);
}
 
static CfsCodecResult
zlib_demo_compress(CfsCodecState *state, const void *src, size_t src_size,
                    void *dst, size_t dst_size, int level, size_t *out_size)
{
    (void) state;
    return cfs_codec_zlib_compress((const char *) src, src_size,
                                    (char *) dst, dst_size, level, out_size);
}
 
static CfsCodecResult
zlib_demo_decompress(CfsCodecState *state, const void *src, size_t src_size,
                        void *dst, size_t dst_size, size_t expected_size,
                        size_t *out_size)
{
    CfsCodecResult rc;
    (void) state;
    if (expected_size > dst_size)
        return CFS_CODEC_CORRUPT;
    rc = cfs_codec_zlib_decompress((const char *) src, src_size,
                                    (char *) dst, expected_size);
    if (rc == CFS_CODEC_OK)
        *out_size = expected_size;
    return rc;
}
 
static const CfsCodec cfs_codec_pglz_demo = {
    .algorithm = CFS_ALGORITHM_PGLZ,
    .state_create = raw_state_create,
    .state_destroy = raw_state_destroy,
    .compress = pglz_demo_compress,
    .decompress = pglz_demo_decompress,
    .compress_bound = cfs_codec_pglz_bound,
    .available = cfs_codec_pglz_available,
};
 
static const CfsCodec cfs_codec_zlib_demo = {
    .algorithm = CFS_ALGORITHM_ZLIB,
    .state_create = zlib_demo_state_create,
    .state_destroy = zlib_demo_state_destroy,
    .compress = zlib_demo_compress,
    .decompress = zlib_demo_decompress,
    .compress_bound = cfs_codec_zlib_bound,
    .available = cfs_codec_zlib_available,
};
 
const CfsCodec *CfsCodecTable[CFS_ALGORITHM_COUNT] = {
    [CFS_ALGORITHM_RAW] = &cfs_codec_raw,
    [CFS_ALGORITHM_LZ4] = &cfs_codec_lz4,
    [CFS_ALGORITHM_ZSTD] = &cfs_codec_zstd,
    [CFS_ALGORITHM_PGLZ] = &cfs_codec_pglz_demo,
    [CFS_ALGORITHM_ZLIB] = &cfs_codec_zlib_demo,
};
 
 
/* ================================================================
 * Per-algorithm native level ceiling
 * ================================================================ */
 
/*
 * CfsCodecMaxLevel
 *      Return the native maximum compression level of the given algorithm.
 *      See the declaration in cfs_codec.h.
 */
int
CfsCodecMaxLevel(CfsAlgorithm algorithm)
{
    switch (algorithm)
    {
        case CFS_ALGORITHM_LZ4:
            return CFS_LZ4_LEVEL_MAX;
        case CFS_ALGORITHM_PGLZ:
            return 1;
        case CFS_ALGORITHM_ZLIB:
            return 9;
        case CFS_ALGORITHM_ZSTD:
#ifdef USE_ZSTD
 
            /*
             * The library's ceiling is a runtime value (ZSTD_maxCLevel());
             * CFS_ZSTD_LEVEL_MAX is only the format's upper bound.  Clamp
             * here so DDL validation and the resolvers' defense check reject
             * a level the codec could never honour, instead of silently
             * clamping it on the write path.
             */
            return Min(CFS_ZSTD_LEVEL_MAX, ZSTD_maxCLevel());
#else
            return CFS_ZSTD_LEVEL_MAX;
#endif
        default:
            return CFS_COMPRESS_LEVEL_MAX;
    }
}
 
 
/* ================================================================
 * Initialisation
 * ================================================================ */
 
/*
 * CfsCodecInit
 *      Called once at subsystem startup (from CfsSubsystemInit) to verify
 *      the codec dispatch table is consistent.  A broken table is a coding
 *      error and PANICs.
 */
void
CfsCodecInit(void)
{
    int         i;
 
    ereport(DEBUG1,
            (errmsg(("CFS: initializing codec dispatch table"))));
 
    /* Verify table consistency, every slot must be non-NULL. */
    for (i = 0; i < CFS_ALGORITHM_COUNT; i++)
    {
        if (CfsCodecTable[i] == NULL)
            ereport(PANIC,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("CfsCodecTable[%d] is NULL", i),
                     errdetail("CFS codec dispatch table was not initialised."),
                     errhint("This is a coding error, please report it.")));
        if ((int) CfsCodecTable[i]->algorithm != i)
            ereport(PANIC,
                    (errcode(ERRCODE_INTERNAL_ERROR),
                     errmsg("CfsCodecTable[%d] has wrong algorithm %d",
                            i, (int) CfsCodecTable[i]->algorithm),
                     errdetail("CFS codec dispatch table is inconsistent."),
                     errhint("This is a coding error, please report it.")));
    }
}
 
 
/* ================================================================
 * Per-backend state cache
 * ================================================================ */
 
/*
 * CfsCodecStateCreate(algorithm)
 *      Return (creating if necessary) a per-backend CfsCodecState for
 *      the requested algorithm.  Returns NULL if the algorithm is not
 *      available in this build.
 *
 *      The state is allocated in TopMemoryContext so that it survives for
 *      the lifetime of the backend.  This is critical: backend_states[] is
 *      a plain static array whose pointers persist across queries, but the
 *      first compress/decompress call can happen while CurrentMemoryContext
 *      is a short-lived query/portal context (e.g. MessageContext, which is
 *      reset at the top of every query cycle).  Allocating the state in that
 *      transient context and then dereferencing the cached pointer from a
 *      later query is a use-after-free.
 *
 *      The use-after-free is silent for the RAW and LZ4 codecs (their
 *      compress/decompress entry points do not dereference the state
 *      struct — LZ4's block API is stateless), but ZSTD stores live
 *      ZSTD_CCtx / ZSTD_DCtx pointers inside CfsCodecState, and
 *      ZSTD_decompressDCtx(state->zstd_dctx, ...) dereferences them.  Once
 *      the freed CfsCodecState slot is reused by an unrelated allocation,
 *      the dangling zstd_dctx read yields a garbage pointer and the library
 *      dereferences it -> SIGSEGV.  This is the C5 defect.
 */
CfsCodecState *
CfsCodecStateCreate(CfsAlgorithm algorithm)
{
    const CfsCodec *codec;
 
    if (!CFS_ALGORITHM_VALID(algorithm))
    {
        ereport(ERROR,
                (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
                 errmsg("invalid CFS algorithm %d", (int) algorithm)));
    }
 
    codec = CfsCodecTable[(int) algorithm];
    Assert(codec != NULL);
 
    if (!codec->available())
        return NULL;
 
    if (backend_states[(int) algorithm] == NULL)
    {
        MemoryContext oldcontext;
 
        /*
         * Allocate the cached state (and any subordinate pallocs done by
         * state_create) in TopMemoryContext so it outlives query/portal
         * resets.  ZSTD_createCCtx/DCtx use malloc internally and are
         * unaffected by the MemoryContext choice; only the CfsCodecState
         * struct itself (which holds the pointers the hot path reads) must
         * live in a context that is not reset between queries.
         */
        oldcontext = MemoryContextSwitchTo(TopMemoryContext);
        backend_states[(int) algorithm] = codec->state_create();
        MemoryContextSwitchTo(oldcontext);
    }
 
    return backend_states[(int) algorithm];
}
 
/*
 * CfsCodecStateDestroy(algorithm)
 *      Release cached per-backend state for one algorithm.
 */
void
CfsCodecStateDestroy(CfsAlgorithm algorithm)
{
    if (!CFS_ALGORITHM_VALID(algorithm))
        return;
 
    if (backend_states[(int) algorithm] != NULL)
    {
        const CfsCodec *codec = CfsCodecTable[(int) algorithm];
 
        codec->state_destroy(backend_states[(int) algorithm]);
        backend_states[(int) algorithm] = NULL;
    }
}
 
/*
 * CfsCodecStateDestroyAll()
 *      Release all cached per-backend states.  Called from CfsAtProcExit at
 *      backend exit.
 */
void
CfsCodecStateDestroyAll(void)
{
    int         i;
 
    for (i = 0; i < CFS_ALGORITHM_COUNT; i++)
        CfsCodecStateDestroy((CfsAlgorithm) i);
}