-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfc.c
More file actions
6245 lines (5940 loc) · 254 KB
/
Copy pathfc.c
File metadata and controls
6245 lines (5940 loc) · 254 KB
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* fc - Floating-Point Compressor
* Copyright (c) 2026 Praveen Vaddadi <thynktank@gmail.com>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define _POSIX_C_SOURCE 200112L
#include "fc.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>
#include <time.h>
#include <immintrin.h>
#define ALIGNSIZE (4 * 1024)
#define BITS_PER_BYTE 8
#define BITS_PER_U32 32
#define BITS_PER_U64 64
#define LZ_MIN_MATCH_LEN ((size_t)sizeof(uint32_t))
#define AVX2_REG_BYTES ((size_t)sizeof(__m256i))
#define AVX2_U64_LANES ((size_t)(sizeof(__m256i) / sizeof(uint64_t)))
enum {
M_PRED = 0, M_CONST = 1, M_STRIDE = 2, M_XORZ = 3, M_LZ = 4, M_RAW = 5,
M_FLOAT32 = 6, M_ORDERED_DELTA = 7, M_FUZZY_STRIDE = 8, M_ALP = 9,
M_TRAILING_ZERO_BP = 10, M_BYTE_TRANSPOSE = 11, M_XOR128 = 13,
M_LSB_STRIP = 15, M_LOOKBACK_DELTA = 16, M_FLOAT_MULT = 17, M_FCM_RLE = 18,
M_DICT = 19, M_DELTA2 = 20, M_BITPLANE = 21, M_INT_MULT = 22, M_CONV1 = 23,
M_PRED_TANS = 24, M_PRED2 = 25, M_PRED_ADAPTIVE = 26, M_VITERBI = 27,
M_DELTA_BINNED = 28, M_PRED_RC = 29, M_PRED_INTERLEAVED = 30, M_BWT = 31,
M_LZ_DICT = 32, M_CONV_N = 33, M_SIGN_CONV = 34, M_CONV_DOUBLE = 35,
M_MTF_LZ = 36, M_CONV_DOUBLE_BP = 37, M_CONV_N_BINNED = 38,
M_PRED_SIMD_INTERLEAVED = 39, M_FUZZY_STRIDE_ANS = 40, M_PAQ_MIXER = 41,
M_PAQ4_MIXER = 42, M_BWT_MTF_TANS = 43, M_PRED4 = 44, M_DELTA_DP_BINNED = 45,
M_CONV_N_DP_BINNED = 46, M_ELF = 47, M_LZ_SPLIT = 48, M_BWT_MTF_RC = 49
};
#define C_INTERLEAVE_LANES 4U
#define C_LZDICT_PREAMBLE_BYTES 320U
#define C_CONV_N_MAX_ORDER 32U
#define C_CONV_N_SCALE_LOG 9
/* Order≤32, Q.9 weights, y_bound 2^44: 32*w*y+bias < 2^60, fits int64. */
#define C_CONV_N_Y_BOUND ((int64_t)1 << 44)
#define C_CONV_N_W_BOUND ((int32_t)((1 << (C_CONV_N_SCALE_LOG + 2)) - 1))
#define C_CONV_DOUBLE_ORDER 4
#define C_ELF_DELTA_BITS 4
#define C_DP_BIN_MAX 8U
#define C_DP_WIDTH_BUCKETS 65U
#define C_PAQ4_MIX_LOG 13
#define C_PAQ4_MIX_ONE ((int64_t)1 << C_PAQ4_MIX_LOG)
#define C_PAQ4_LEARN_SHIFT 4
#define C_PAQ_MIX_LOG 15
#define C_PAQ_MIX_ONE ((int64_t)1 << C_PAQ_MIX_LOG)
#define C_PAQ_LEARN_SHIFT 5
#define C_BWT_MAX_BYTES (C_QUANTUM_MAX_BYTES)
#define C_DICT_MAX_ENTRIES 256U
#define C_DICT_HASH_SIZE 1024U
#define C_DICT_HASH_MASK (C_DICT_HASH_SIZE - 1U)
#define C_FCM_RLE_HASH_SIZE 4096U
#define C_FCM_RLE_HASH_MASK (C_FCM_RLE_HASH_SIZE - 1U)
#define C_FCM_RLE_RUN_MAX 127U
#define C_LOOKBACK_K_COUNT 15U
#define C_QUANTUM_BYTES (256 * 1024)
#define C_QUANTUM_MAX_BYTES (1 * 1024 * 1024)
#define C_ENTROPY_PROBE_BYTES (48 * 1024)
#define C_MAGIC 0x32434650U
#define ull unsigned long long
static inline ull load_u64_unaligned(const void *ptr){ull x;memcpy(&x,ptr,sizeof(x));return x;}
static inline void store_u64_unaligned(void *ptr,ull v){memcpy(ptr,&v,sizeof(v));}
static inline void st32_le(unsigned char *p,uint32_t v){p[0]=(unsigned char)v;p[1]=(unsigned char)(v>>8);p[2]=(unsigned char)(v>>16);p[3]=(unsigned char)(v>>24);}
static inline uint32_t ld32_le(const unsigned char *p){return (uint32_t)p[0]|((uint32_t)p[1]<<8)|((uint32_t)p[2]<<16)|((uint32_t)p[3]<<24);}
static inline void avx2_copy(void *dst, const void *src, size_t n)
{
unsigned char *d = (unsigned char *)dst;
const unsigned char *s = (const unsigned char *)src;
while (n >= AVX2_REG_BYTES) {
__m256i v = _mm256_loadu_si256((const __m256i *)s);
_mm256_storeu_si256((__m256i *)d, v);
s += AVX2_REG_BYTES;
d += AVX2_REG_BYTES;
n -= AVX2_REG_BYTES;
}
while (n-- > 0) *d++ = *s++;
}
static inline size_t clz64_nonzero(ull value){return (size_t)__builtin_clzll(value);}
static inline size_t ctz64_nonzero(ull value){return (size_t)__builtin_ctzll(value);}
static inline size_t fc_crc32_u64(ull value){return (size_t)_mm_crc32_u64(0x9e3779b97f4a7c15ULL, value);}
static inline ull float_ordered(ull b){return (b&0x8000000000000000ULL)?~b:(b^0x8000000000000000ULL);}
static inline ull float_unordered(ull b){return (b&0x8000000000000000ULL)?(b^0x8000000000000000ULL):~b;}
static inline ull zigzag64(long long v){return ((ull)v<<1)^(ull)(v>>63);}
static inline long long unzigzag64(ull v){return (long long)((v>>1)^(0ULL-(v&1ULL)));}
static size_t bits_required64(ull v){return v?BITS_PER_U64-clz64_nonzero(v):0U;}
typedef struct { unsigned char *buf; uint64_t pos, cap, acc_bits; ull acc; } bw_t;
typedef struct { const unsigned char *buf; uint64_t pos, bytes, acc_bits; ull acc; } br_t;
typedef struct {
uint64_t original_bytes;
uint32_t magic, quantum_bytes;
uint8_t predsizelg2, reserved[7];
} hdr_t;
typedef struct { uint32_t values, compressed_bytes; } bh_t;
typedef struct {
uint64_t in_value_offset, out_byte_offset, values, compressed_bytes;
unsigned char *compressed;
int ok;
} job_t;
typedef struct {
const ull *input;
const unsigned char *compressed_stream;
unsigned char *output;
job_t *jobs;
uint64_t job_count, next_job, predsizem1;
pthread_mutex_t lock;
} pctx_t;
static inline void bw_init(bw_t *bw, unsigned char *buf, size_t cap)
{
bw->buf = buf; bw->pos = 0; bw->cap = cap; bw->acc = 0; bw->acc_bits = 0;
}
static inline void bw_put(bw_t *bw, ull value, size_t bits)
{
if (bits == 0U) return;
if (bits < BITS_PER_U64) value &= ((ull)1U << bits) - 1ULL;
if ((bw->acc_bits + bits) < BITS_PER_U64) {
bw->acc = (bw->acc << bits) | value;
bw->acc_bits += bits;
return;
}
{
size_t free_bits = BITS_PER_U64 - bw->acc_bits;
ull acc_shifted = (free_bits >= BITS_PER_U64) ? 0ULL : (bw->acc << free_bits);
ull take_from_value = (bits == free_bits) ? value : (value >> (bits - free_bits));
ull head = acc_shifted | take_from_value;
size_t i;
for (i = 0; i < sizeof(ull); i++)
if (bw->pos < bw->cap)
bw->buf[bw->pos++] = (unsigned char)(head >> ((sizeof(ull) - 1U - i) * BITS_PER_BYTE));
bw->acc_bits = bits - free_bits;
bw->acc = (bw->acc_bits == 0) ? 0 : (value & (((ull)1U << bw->acc_bits) - 1ULL));
}
}
/* Batched pack for 4 same-width values: coalesce into one bw_put
* when 4*width ≤ 64; amortizes accumulator bookkeeping. */
static inline void bw_put4(bw_t *bw, ull v0, ull v1, ull v2, ull v3, size_t width)
{
if (width == 0U) return;
if ((width * 4U) <= BITS_PER_U64) {
ull mask = (width >= BITS_PER_U64) ? ~(ull)0 : (((ull)1U << width) - 1ULL);
ull combined = ((v0 & mask) << (3U * width))
| ((v1 & mask) << (2U * width))
| ((v2 & mask) << width)
| (v3 & mask);
bw_put(bw, combined, width * 4U);
} else {
bw_put(bw, v0, width);
bw_put(bw, v1, width);
bw_put(bw, v2, width);
bw_put(bw, v3, width);
}
}
static inline size_t bw_bytes(bw_t *bw)
{
if (bw->acc_bits > 0) {
size_t tail_bits = bw->acc_bits;
ull tail = bw->acc << (BITS_PER_U64 - tail_bits);
size_t byte_count = (tail_bits + 7U) >> 3;
size_t i;
for (i = 0; i < byte_count; i++)
if (bw->pos < bw->cap)
bw->buf[bw->pos++] = (unsigned char)(tail >> ((sizeof(ull) - 1U - i) * BITS_PER_BYTE));
bw->acc = 0;
bw->acc_bits = 0;
}
return bw->pos;
}
static inline void br_init(br_t *br, const unsigned char *buf, size_t bytes)
{
br->buf = buf; br->pos = 0; br->bytes = bytes; br->acc = 0; br->acc_bits = 0;
}
static inline ull br_get(br_t *br, size_t bits)
{
ull v = 0;
if (bits == 0U) return 0;
/* Drain accumulator first; never let acc_bits exceed 64 (overflow trap). */
if (br->acc_bits > 0U) {
size_t take = (bits < br->acc_bits) ? bits : br->acc_bits;
ull part = br->acc >> (br->acc_bits - take);
if (take < BITS_PER_U64) part &= ((ull)1U << take) - 1ULL;
v = part;
br->acc_bits -= take;
br->acc = (br->acc_bits == 0U) ? 0ULL : (br->acc & (((ull)1U << br->acc_bits) - 1ULL));
bits -= take;
}
while (bits >= BITS_PER_BYTE) {
unsigned char b = (br->pos < br->bytes) ? br->buf[br->pos++] : 0U;
v = (v << BITS_PER_BYTE) | (ull)b;
bits -= BITS_PER_BYTE;
}
if (bits > 0U) {
unsigned char b = (br->pos < br->bytes) ? br->buf[br->pos++] : 0U;
size_t rest = BITS_PER_BYTE - bits;
v = (v << bits) | (ull)((unsigned)b >> rest);
br->acc_bits = rest;
br->acc = (ull)b & (((ull)1U << rest) - 1ULL);
}
return v;
}
/* tANS, 8-bit symbols, table 1024, state in [1024,2048). LIFO at encode → bits
* stored reverse, decoded forward. Wire format:
* [0] num_syms - 1
* [1..N+1) which_syms[i] (u8)
* [N+1..3N+1) weights[i] (u16 LE)
* [3N+1..3N+5) final_state (u32 LE, in [1024,2048))
* [3N+5..3N+9) total_bits (u32 LE)
* [3N+9..) renorm bits, MSB-first. */
#define C_ANS_MAX_SYMS 256U
#define C_ANS_SIZE_LOG 10U
#define C_ANS_TABLE_SIZE (1U << C_ANS_SIZE_LOG)
typedef uint32_t fc_ans_state_t;
typedef uint16_t fc_ans_weight_t;
typedef struct {
fc_ans_state_t renorm_cutoff;
uint8_t min_renorm_bits;
uint16_t weight, cum;
} fc_ans_sym_info_t;
typedef struct {
fc_ans_sym_info_t infos[C_ANS_MAX_SYMS];
fc_ans_state_t next_states[C_ANS_TABLE_SIZE];
uint16_t num_syms;
} fc_ans_encoder_t;
typedef struct { uint16_t next_state_idx_base; uint8_t bits_to_read, symbol; } fc_ans_node_t;
typedef struct { fc_ans_node_t nodes[C_ANS_TABLE_SIZE]; } fc_ans_decoder_t;
static void fc_ans_spread(uint8_t *state_symbols, const fc_ans_weight_t *weights,
const uint8_t *which_syms, size_t num_syms)
{
uint32_t step = 0U, stride = (3U * C_ANS_TABLE_SIZE) / 5U;
size_t s;
fc_ans_weight_t w;
if ((stride & 1U) == 0U) stride++;
for (s = 0; s < num_syms; s++) {
uint8_t sym_id = which_syms[s];
for (w = 0; w < weights[s]; w++) {
uint32_t idx = (stride * step) & (C_ANS_TABLE_SIZE - 1U);
state_symbols[idx] = sym_id;
step++;
}
}
}
static int fc_ans_quantize(const uint32_t *counts, size_t num_syms, uint64_t total_count,
fc_ans_weight_t *weights_out)
{
size_t i;
fc_ans_weight_t weight_sum = 0U;
float multiplier, surplus_mult, desired_surplus[C_ANS_MAX_SYMS], total_desired = 0.0f;
size_t guard;
if (num_syms == 0U || num_syms > C_ANS_MAX_SYMS) return 0;
multiplier = (total_count > 0U) ? ((float)C_ANS_TABLE_SIZE / (float)total_count) : 0.0f;
for (i = 0; i < num_syms; i++) {
float v = (float)counts[i] * multiplier - 1.0f;
if (v < 0.0f) v = 0.0f;
desired_surplus[i] = v;
total_desired += v;
}
surplus_mult = (total_desired > 0.0f)
? ((float)((float)C_ANS_TABLE_SIZE - (float)num_syms) / total_desired)
: 0.0f;
for (i = 0; i < num_syms; i++) {
float w = 1.0f + desired_surplus[i] * surplus_mult;
fc_ans_weight_t qw;
qw = (fc_ans_weight_t)(w + 0.5f);
if (qw == 0U) qw = 1U;
weights_out[i] = qw;
}
for (i = 0; i < num_syms; i++) weight_sum = (fc_ans_weight_t)(weight_sum + weights_out[i]);
/* Adjust to hit table_size, with a guard against pathological loops. */
guard = num_syms * 8U + 16U;
i = 0;
while (weight_sum > C_ANS_TABLE_SIZE && guard > 0U) {
if (weights_out[i] > 1U) { weights_out[i]--; weight_sum--; }
i = (i + 1U) % num_syms;
guard--;
}
guard = num_syms * 8U + 16U;
i = 0;
while (weight_sum < C_ANS_TABLE_SIZE && guard > 0U) {
weights_out[i]++;
weight_sum++;
i = (i + 1U) % num_syms;
guard--;
}
return (weight_sum == C_ANS_TABLE_SIZE) ? 1 : 0;
}
static void fc_ans_encoder_init(fc_ans_encoder_t *enc, const fc_ans_weight_t *weights,
const uint8_t *which_syms, size_t num_syms,
const uint8_t *state_symbols)
{
size_t s;
uint32_t i;
uint16_t cum = 0U, fill_pos[C_ANS_MAX_SYMS];
enc->num_syms = (uint16_t)num_syms;
memset(enc->infos, 0, sizeof(enc->infos));
for (s = 0; s < num_syms; s++) {
fc_ans_weight_t w = weights[s];
uint8_t sym_id = which_syms[s];
uint32_t max_xs = (w > 0U) ? (2U * (uint32_t)w - 1U) : 1U, log_max = 0U;
uint8_t mrb;
while ((max_xs >> log_max) > 1U) log_max++;
mrb = (uint8_t)((uint32_t)C_ANS_SIZE_LOG - log_max);
enc->infos[sym_id].renorm_cutoff = (fc_ans_state_t)((uint32_t)w * 2U) << mrb;
enc->infos[sym_id].min_renorm_bits = mrb;
enc->infos[sym_id].weight = w;
enc->infos[sym_id].cum = cum;
fill_pos[s] = cum;
cum = (uint16_t)(cum + w);
}
for (i = 0; i < C_ANS_TABLE_SIZE; i++) {
uint8_t sym_id = state_symbols[i];
size_t slot = 0U;
while (slot < num_syms && which_syms[slot] != sym_id) slot++;
enc->next_states[fill_pos[slot]++] = C_ANS_TABLE_SIZE + i;
}
}
static void fc_ans_decoder_init(fc_ans_decoder_t *dec, const fc_ans_weight_t *weights,
const uint8_t *which_syms, size_t num_syms,
const uint8_t *state_symbols)
{
fc_ans_state_t symbol_xs[C_ANS_MAX_SYMS];
size_t s;
uint32_t i;
for (i = 0; i < C_ANS_MAX_SYMS; i++) symbol_xs[i] = 0U;
for (s = 0; s < num_syms; s++) symbol_xs[which_syms[s]] = (fc_ans_state_t)weights[s];
for (i = 0; i < C_ANS_TABLE_SIZE; i++) {
uint8_t sym_id = state_symbols[i];
fc_ans_state_t base = symbol_xs[sym_id];
uint32_t bits = 0U;
uint32_t a = (base != 0U) ? (uint32_t)__builtin_clz(base) : 31U;
uint32_t b = (uint32_t)__builtin_clz(C_ANS_TABLE_SIZE);
bits = a - b;
dec->nodes[i].next_state_idx_base = (uint16_t)((base << bits) - C_ANS_TABLE_SIZE);
dec->nodes[i].bits_to_read = (uint8_t)bits;
dec->nodes[i].symbol = sym_id;
symbol_xs[sym_id]++;
}
}
/* Reverse-order (LIFO) bit emission: we record each (low, bits) pair as we
encode in reverse symbol order, then write them to the stream in reverse
so the decoder reading forward can reconstruct the original symbol order. */
typedef struct { uint16_t low; uint8_t bits; } fc_ans_bit_pair_t;
static size_t fc_ans_encode_bytes(const uint8_t *src, size_t src_len,
const uint32_t *counts, size_t num_distinct,
const uint8_t *which_syms,
unsigned char *out, size_t out_cap)
{
fc_ans_weight_t weights[C_ANS_MAX_SYMS];
uint8_t state_symbols[C_ANS_TABLE_SIZE];
fc_ans_encoder_t enc;
fc_ans_state_t state = C_ANS_TABLE_SIZE;
fc_ans_bit_pair_t *pairs;
size_t header_bytes = 1U + num_distinct + (num_distinct * 2U) + 4U + 4U;
size_t i, total_bits = 0U, byte_pos;
uint64_t total_count = 0U;
bw_t bw;
if (num_distinct == 0U || num_distinct > C_ANS_MAX_SYMS) return (size_t)-1;
if (header_bytes > out_cap) return (size_t)-1;
for (i = 0; i < num_distinct; i++) total_count += counts[i];
if (!fc_ans_quantize(counts, num_distinct, total_count, weights)) return (size_t)-1;
fc_ans_spread(state_symbols, weights, which_syms, num_distinct);
fc_ans_encoder_init(&enc, weights, which_syms, num_distinct, state_symbols);
static __thread fc_ans_bit_pair_t *g_ans_pairs = NULL;
static __thread size_t g_ans_pairs_cap = 0U;
if (g_ans_pairs_cap < src_len) {
size_t new_cap = src_len < 4096U ? 4096U : src_len;
fc_ans_bit_pair_t *np = (fc_ans_bit_pair_t *)realloc(g_ans_pairs, new_cap * sizeof(*g_ans_pairs));
if (!np) return (size_t)-1;
g_ans_pairs = np; g_ans_pairs_cap = new_cap;
}
pairs = g_ans_pairs;
for (i = src_len; i > 0U; i--) {
uint8_t sym = src[i - 1U];
fc_ans_sym_info_t *info = &enc.infos[sym];
uint8_t renorm_bits;
uint32_t low;
fc_ans_state_t shifted, next_state;
if (info->weight == 0U) return (size_t)-1;
renorm_bits = (uint8_t)(info->min_renorm_bits + (state >= info->renorm_cutoff ? 1U : 0U));
low = (renorm_bits == 0U) ? 0U : (state & ((1U << renorm_bits) - 1U));
shifted = state >> renorm_bits;
next_state = enc.next_states[info->cum + (shifted - info->weight)];
pairs[src_len - i].low = (uint16_t)low;
pairs[src_len - i].bits = renorm_bits;
total_bits += renorm_bits;
state = next_state;
}
out[0] = (uint8_t)(num_distinct - 1U);
for (i = 0; i < num_distinct; i++) out[1U + i] = which_syms[i];
byte_pos = 1U + num_distinct;
for (i = 0; i < num_distinct; i++) {
out[byte_pos] = (uint8_t)(weights[i] & 0xffU);
out[byte_pos + 1] = (uint8_t)((weights[i] >> 8) & 0xffU);
byte_pos += 2;
}
st32_le(out + byte_pos, (uint32_t)state); byte_pos += 4;
st32_le(out + byte_pos, (uint32_t)total_bits); byte_pos += 4;
/* Reverse encoding order so decoder reads forward. */
bw_init(&bw, out + byte_pos, out_cap - byte_pos);
for (i = src_len; i > 0U; i--) {
fc_ans_bit_pair_t p = pairs[i - 1U];
if (p.bits > 0U) bw_put(&bw, (ull)p.low, p.bits);
}
return byte_pos + bw_bytes(&bw);
}
static size_t fc_ans_decode_bytes(const unsigned char *in, size_t in_bytes, size_t expected_len,
uint8_t *out_buf)
{
size_t num_distinct;
uint8_t which_syms[C_ANS_MAX_SYMS], state_symbols[C_ANS_TABLE_SIZE];
fc_ans_weight_t weights[C_ANS_MAX_SYMS];
fc_ans_decoder_t dec;
fc_ans_state_t state;
size_t byte_pos, i;
br_t br;
if (in_bytes < 1U) return 0U;
num_distinct = (size_t)in[0] + 1U;
byte_pos = 1U;
if (in_bytes < (1U + num_distinct + num_distinct * 2U + 8U)) return 0U;
for (i = 0; i < num_distinct; i++) which_syms[i] = in[byte_pos + i];
byte_pos += num_distinct;
for (i = 0; i < num_distinct; i++) {
weights[i] = (fc_ans_weight_t)((uint32_t)in[byte_pos] | ((uint32_t)in[byte_pos + 1] << 8));
byte_pos += 2;
}
state = (fc_ans_state_t)ld32_le(in + byte_pos); byte_pos += 4;
byte_pos += 4;
fc_ans_spread(state_symbols, weights, which_syms, num_distinct);
fc_ans_decoder_init(&dec, weights, which_syms, num_distinct, state_symbols);
br_init(&br, in + byte_pos, in_bytes - byte_pos);
for (i = 0; i < expected_len; i++) {
fc_ans_node_t *node = &dec.nodes[state - C_ANS_TABLE_SIZE];
ull bits = (node->bits_to_read == 0U) ? 0ULL : br_get(&br, node->bits_to_read);
out_buf[i] = node->symbol;
state = (fc_ans_state_t)(C_ANS_TABLE_SIZE + node->next_state_idx_base) + (fc_ans_state_t)bits;
}
return expected_len;
}
/* Binary range coder. 12-bit fractional probabilities, shift-rate
* 5 adaptive update. Probabilities are P(bit==0) in [0, 4096]. */
typedef struct {
uint64_t low, cache_size;
uint32_t range;
size_t op, cap;
unsigned char *out;
unsigned char cache;
} fc_rc_enc_t;
typedef struct {
const unsigned char *in;
size_t ip, in_bytes;
uint32_t range, code;
} fc_rc_dec_t;
static void rc_enc_init(fc_rc_enc_t *rc, unsigned char *out, size_t cap)
{
rc->low = 0U; rc->range = 0xffffffffU; rc->out = out;
rc->op = 0U; rc->cap = cap; rc->cache = 0U; rc->cache_size = 1U;
}
/* Renormalize: when high 8 bits stable (or carry), flush cache + queued FFs.
* Caller guarantees out_cap >= upper-bound on encoded bytes so the bounds check
* is unnecessary on the per-byte hot path. */
static __attribute__((always_inline)) inline void rc_enc_shift_low(fc_rc_enc_t *rc)
{
if (rc->low < 0xff000000ULL || rc->low >= 0x100000000ULL) {
unsigned char carry = (unsigned char)(rc->low >> 32);
rc->out[rc->op++] = (unsigned char)(rc->cache + carry);
while (--rc->cache_size > 0U) rc->out[rc->op++] = (unsigned char)(0xffU + carry);
rc->cache = (unsigned char)((rc->low >> 24) & 0xffU);
rc->cache_size = 1U;
} else rc->cache_size++;
rc->low = (rc->low << 8) & 0xffffffffULL;
}
static __attribute__((always_inline)) inline void rc_enc_bit(fc_rc_enc_t *rc, int bit, uint16_t *prob)
{
uint32_t new_bound = (rc->range >> 12) * (uint32_t)(*prob);
if (bit == 0) {
rc->range = new_bound;
*prob = (uint16_t)(*prob + ((4096U - *prob) >> 5));
} else {
rc->low += new_bound;
rc->range -= new_bound;
*prob = (uint16_t)(*prob - (*prob >> 5));
}
while (rc->range < 0x01000000U) { rc->range <<= 8; rc_enc_shift_low(rc); }
}
static size_t rc_enc_finish(fc_rc_enc_t *rc)
{
size_t k;
for (k = 0; k < 5U; k++) rc_enc_shift_low(rc);
return rc->op;
}
static void rc_dec_init(fc_rc_dec_t *rc, const unsigned char *in, size_t in_bytes)
{
size_t i;
rc->in = in; rc->ip = 0U; rc->in_bytes = in_bytes;
rc->range = 0xffffffffU; rc->code = 0U;
/* Read 5 bytes; first is always 0 from encoder's cache and is discarded. */
for (i = 0; i < 5U; i++) rc->code = (rc->code << 8) | ((rc->ip < rc->in_bytes) ? rc->in[rc->ip++] : 0U);
}
static __attribute__((always_inline)) inline int rc_dec_bit(fc_rc_dec_t *rc, uint16_t *prob)
{
uint32_t new_bound = (rc->range >> 12) * (uint32_t)(*prob);
int bit;
if (rc->code < new_bound) {
rc->range = new_bound;
*prob = (uint16_t)(*prob + ((4096U - *prob) >> 5));
bit = 0;
} else {
rc->code -= new_bound;
rc->range -= new_bound;
*prob = (uint16_t)(*prob - (*prob >> 5));
bit = 1;
}
while (rc->range < 0x01000000U) {
/* Caller guarantees ≥16 zero-padded bytes past encoded_len; no bounds check needed. */
unsigned char b = rc->in[rc->ip];
rc->ip++;
rc->range <<= 8;
rc->code = (rc->code << 8) | b;
}
return bit;
}
/* Range-coded byte stream: 64 contexts indexed by
* (prev_3_bits << 3) | bit_pos. Wire: [encoded_len:u32 LE][rc bits].
* Refuses if encoded_len ≥ src_len. */
#define C_RC_HIST_BITS 3
#define C_RC_HIST_MASK ((1U << C_RC_HIST_BITS) - 1U)
#define C_RC_NUM_CONTEXTS (8U << C_RC_HIST_BITS)
static size_t fc_rc_compress_bytes(const uint8_t *src, size_t src_len,
unsigned char *out, size_t out_cap)
{
uint16_t probs[C_RC_NUM_CONTEXTS];
fc_rc_enc_t rc;
size_t header_bytes = 4U, i, b, encoded_len;
unsigned int hist = 0U;
if (src_len < 32U) return (size_t)-1;
/* Need cap >= src_len + small constant so the inner bounds-free hot path can write without
* overflow. Binary RC encoded size <= src_len + ~5 in absolute worst case. */
if (out_cap < header_bytes + src_len + 16U) return (size_t)-1;
for (i = 0; i < C_RC_NUM_CONTEXTS; i++) probs[i] = 2048U;
rc_enc_init(&rc, out + header_bytes, out_cap - header_bytes);
for (i = 0; i < src_len; i++) {
uint8_t byte_val = src[i];
for (b = 0; b < 8U; b++) {
int bit = (byte_val >> b) & 1;
size_t ctx = (size_t)((hist & C_RC_HIST_MASK) << 3) | b;
rc_enc_bit(&rc, bit, &probs[ctx]);
hist = (hist << 1) | (unsigned int)bit;
}
}
encoded_len = rc_enc_finish(&rc);
if (encoded_len >= src_len) return (size_t)-1;
st32_le(out, (uint32_t)encoded_len);
return header_bytes + encoded_len;
}
static __thread unsigned char *g_rc_pad_buf = NULL;
static __thread size_t g_rc_pad_cap = 0U;
static __thread int g_rc_pad_atexit_registered = 0;
static void fc_rc_pad_free(void){if(g_rc_pad_buf){free(g_rc_pad_buf);g_rc_pad_buf=NULL;g_rc_pad_cap=0U;}}
static size_t fc_rc_decompress_bytes(const unsigned char *in, size_t in_bytes,
size_t expected_len, uint8_t *out_buf)
{
uint16_t probs[C_RC_NUM_CONTEXTS];
fc_rc_dec_t rc;
size_t header_bytes = 4U, encoded_len, i, b;
unsigned int hist = 0U;
if (in_bytes < header_bytes) return 0U;
encoded_len = (size_t)ld32_le(in);
if ((header_bytes + encoded_len) > in_bytes) return 0U;
for (i = 0; i < C_RC_NUM_CONTEXTS; i++) probs[i] = 2048U;
/* Fast path: if there's ≥16 bytes of buffer past the encoded segment, we can
* read past the boundary safely (those bytes feed renorm but never influence
* any decoded output bit). Otherwise pad-copy via thread-local scratch. */
const unsigned char *rc_in;
size_t rc_bytes;
if (in_bytes - header_bytes - encoded_len >= 16U) {
rc_in = in + header_bytes;
rc_bytes = in_bytes - header_bytes;
} else {
if (g_rc_pad_cap < encoded_len + 16U) {
size_t new_cap = encoded_len + 16U;
if (new_cap < 4096U) new_cap = 4096U;
unsigned char *nb = (unsigned char *)realloc(g_rc_pad_buf, new_cap);
if (!nb) return 0U;
g_rc_pad_buf = nb; g_rc_pad_cap = new_cap;
if (!g_rc_pad_atexit_registered) { atexit(fc_rc_pad_free); g_rc_pad_atexit_registered = 1; }
}
memcpy(g_rc_pad_buf, in + header_bytes, encoded_len);
memset(g_rc_pad_buf + encoded_len, 0, 16U);
rc_in = g_rc_pad_buf;
rc_bytes = encoded_len + 16U;
}
rc_dec_init(&rc, rc_in, rc_bytes);
for (i = 0; i < expected_len; i++) {
uint8_t byte_val = 0U;
for (b = 0; b < 8U; b++) {
size_t ctx = (size_t)((hist & C_RC_HIST_MASK) << 3) | b;
int bit = rc_dec_bit(&rc, &probs[ctx]);
byte_val |= (uint8_t)(bit << b);
hist = (hist << 1) | (unsigned int)bit;
}
out_buf[i] = byte_val;
}
return expected_len;
}
/* High-level wrapper: compress a byte buffer via tANS using its full 256-bin
histogram, returning encoded size or (size_t)-1 on failure / non-improvement.
Only writes if the encoded bytes are strictly fewer than src_len. */
static size_t fc_ans_compress_bytes(const uint8_t *src, size_t src_len,
unsigned char *out, size_t out_cap)
{
uint32_t hist[C_ANS_MAX_SYMS];
uint8_t which_syms[C_ANS_MAX_SYMS];
uint32_t counts[C_ANS_MAX_SYMS];
size_t num_distinct = 0U, i, encoded;
if (src_len < 16U) return (size_t)-1;
memset(hist, 0, sizeof(hist));
for (i = 0; i < src_len; i++) hist[src[i]]++;
for (i = 0; i < C_ANS_MAX_SYMS; i++) {
if (hist[i] > 0U) {
which_syms[num_distinct] = (uint8_t)i;
counts[num_distinct] = hist[i];
num_distinct++;
}
}
if (num_distinct < 2U) return (size_t)-1;
encoded = fc_ans_encode_bytes(src, src_len, counts, num_distinct, which_syms, out, out_cap);
if (encoded == (size_t)-1 || encoded >= src_len) return (size_t)-1;
return encoded;
}
static size_t pred_enc(const ull *input, size_t num, size_t predsizem1,
ull *fcm, ull *dfcm, unsigned char *out);
static void pred_dec(const unsigned char *in, size_t in_bytes, size_t num,
size_t predsizem1, ull *fcm, ull *dfcm, ull *out);
static void fc_sample_unique(uint64_t seed, size_t n, size_t k,
uint8_t *visited_bits, size_t *out_indices);
static double fc_im_significance_threshold(int g, double target_concentration);
static int fc_bcode(ull x);
static void fc_mtf_forward(const unsigned char *src, size_t n, unsigned char *dst);
static void fc_mtf_inverse(const unsigned char *src, size_t n, unsigned char *dst);
static inline float fc_fast_log2f(float x);
/* PRED_TANS: predictor output [tags|payload], tags re-coded via tANS.
* Wire: [tans_size:u32 LE][tANS tags][raw predictor payload]. Refuses if
* tans_size >= num (i.e. tANS doesn't beat raw tags). */
static size_t lz_enc(const unsigned char *input, size_t n,
unsigned char *out, size_t out_cap);
static void lz_dec(const unsigned char *in, size_t in_bytes,
unsigned char *out, size_t out_bytes);
static void byte_transpose8(const unsigned char *src, size_t values, unsigned char *dst);
static void byte_untranspose8(const unsigned char *src, size_t values, unsigned char *dst);
/* SA-IS linear-time suffix array. Sentinel at position n (smaller than any
* real char); sa[] has length n+1, sa[0]=n, sa[1..n]=sorted suffixes.
* Recursion depth O(log n) — uses C call stack. */
typedef struct {
const uint8_t *src8;
const int *src32;
int is_int, n, alpha;
} sais_in_t;
static inline int sais_get(const sais_in_t *in, int i)
{
if (i >= in->n) return -1; /* virtual sentinel = -1 (smaller than all) */
return in->is_int ? in->src32[i] : (int)in->src8[i];
}
#define SAIS_S_TYPE 1
#define SAIS_L_TYPE 0
static void sais_classify(const sais_in_t *in, uint8_t *t)
{
int i, n = in->n;
if (n == 0) return;
t[n - 1] = SAIS_L_TYPE;
for (i = n - 2; i >= 0; i--) {
int a = sais_get(in, i), b = sais_get(in, i + 1);
if (a < b) t[i] = SAIS_S_TYPE;
else if (a > b) t[i] = SAIS_L_TYPE;
else t[i] = t[i + 1];
}
}
/* LMS (Leftmost-S): i > 0 && t[i] == S && t[i-1] == L. */
static int sais_is_lms(const uint8_t *t, int i)
{
return i > 0 && t[i] == SAIS_S_TYPE && t[i - 1] == SAIS_L_TYPE;
}
static void sais_get_buckets(const sais_in_t *in, int *bucket, int end)
{
int n = in->n, alpha = in->alpha, i, sum = 0;
for (i = 0; i < alpha; i++) bucket[i] = 0;
for (i = 0; i < n; i++) bucket[sais_get(in, i)]++;
for (i = 0; i < alpha; i++) { sum += bucket[i]; bucket[i] = end ? sum : sum - bucket[i]; }
}
static void sais_induce_l(const sais_in_t *in, int *sa, const uint8_t *t, int *bucket)
{
int n = in->n, i;
sais_get_buckets(in, bucket, 0);
for (i = 0; i < n; i++) {
int j = sa[i] - 1;
if (j >= 0 && t[j] == SAIS_L_TYPE) sa[bucket[sais_get(in, j)]++] = j;
}
}
static void sais_induce_s(const sais_in_t *in, int *sa, const uint8_t *t, int *bucket)
{
int n = in->n, i;
sais_get_buckets(in, bucket, 1);
for (i = n - 1; i >= 0; i--) {
int j = sa[i] - 1;
if (j >= 0 && t[j] == SAIS_S_TYPE) sa[--bucket[sais_get(in, j)]] = j;
}
}
/* Compare two LMS-substrings starting at p and q. */
static int sais_lms_eq(const sais_in_t *in, const uint8_t *t, int p, int q)
{
int n = in->n, i;
if (p == q) return 1;
if (p >= n || q >= n) return 0;
for (i = 0;; i++) {
int pa = (p + i < n) ? sais_get(in, p + i) : -1;
int qa = (q + i < n) ? sais_get(in, q + i) : -1;
int p_lms = sais_is_lms(t, p + i), q_lms = sais_is_lms(t, q + i);
if (i > 0 && p_lms && q_lms) return 1;
if (pa != qa || p_lms != q_lms) return 0;
}
}
static void sais_compute(const sais_in_t *in, int *sa)
{
int n = in->n, alpha = in->alpha, i, n1 = 0, name = 0, prev = -1, alpha2 = 0;
uint8_t *t = NULL;
int *bucket = NULL;
if (n == 0) return;
if (n == 1) { sa[0] = 0; return; }
t = (uint8_t *)malloc((size_t)n);
bucket = (int *)malloc((size_t)alpha * sizeof(int));
if (t == NULL || bucket == NULL) goto cleanup;
sais_classify(in, t);
/* Stage 1: bucket-place LMS suffixes at end of buckets, then induce. */
for (i = 0; i < n; i++) sa[i] = -1;
sais_get_buckets(in, bucket, 1);
for (i = n - 1; i >= 0; i--) if (sais_is_lms(t, i)) sa[--bucket[sais_get(in, i)]] = i;
sais_induce_l(in, sa, t, bucket);
sais_induce_s(in, sa, t, bucket);
/* Stage 2: compact LMS-suffix order in SA[0..n1), assign names to LMS-substrings. */
n1 = 0;
for (i = 0; i < n; i++) if (sa[i] > 0 && sais_is_lms(t, sa[i])) sa[n1++] = sa[i];
for (i = n1; i < n; i++) sa[i] = -1;
prev = -1;
name = 0;
for (i = 0; i < n1; i++) {
int pos = sa[i];
if (prev == -1 || !sais_lms_eq(in, t, prev, pos)) name++;
prev = pos;
sa[n1 + (pos / 2)] = name - 1;
}
{
int j = n - 1;
for (i = n - 1; i >= n1; i--) if (sa[i] >= 0) sa[j--] = sa[i];
}
alpha2 = name;
/* Stage 3: recurse if names not unique, else SA1 is trivial. */
if (name < n1) {
sais_in_t rec_in = { NULL, sa + (n - n1), 1, n1, alpha2 };
sais_compute(&rec_in, sa);
} else {
int *s1 = sa + (n - n1);
for (i = 0; i < n1; i++) sa[s1[i]] = i;
}
/* Stage 4: induced sort with sorted SA1. */
{
int *lms_positions = (int *)malloc((size_t)n1 * sizeof(int));
int *temp_lms;
int j = 0;
if (!lms_positions) goto cleanup;
for (i = 0; i < n; i++) if (sais_is_lms(t, i)) lms_positions[j++] = i;
for (i = 0; i < n1; i++) sa[i] = lms_positions[sa[i]];
for (i = n1; i < n; i++) sa[i] = -1;
sais_get_buckets(in, bucket, 1);
temp_lms = (int *)malloc((size_t)n1 * sizeof(int));
if (!temp_lms) { free(lms_positions); goto cleanup; }
for (i = 0; i < n1; i++) temp_lms[i] = sa[i];
for (i = 0; i < n; i++) sa[i] = -1;
for (i = n1 - 1; i >= 0; i--) { int pos = temp_lms[i]; sa[--bucket[sais_get(in, pos)]] = pos; }
free(temp_lms);
sais_induce_l(in, sa, t, bucket);
sais_induce_s(in, sa, t, bucket);
free(lms_positions);
}
cleanup:
free(t); free(bucket);
}
/* SA-IS byte entry: sa[] of length n holds suffix positions sorted lex. */
static void sais_byte(const uint8_t *src, int n, int *sa)
{
sais_in_t in = { src, NULL, 0, n, 256 };
sais_compute(&in, sa);
}
/* Cyclic BWT via doubled-buffer SA-IS on src++src; entries <n are the cyclic order. */
static int sais_cyclic_bwt(const uint8_t *src, int n, uint8_t *bwt_out)
{
int *sa_full;
uint8_t *dbl;
int primary = -1, i, filt = 0;
if (n <= 0) return -1;
dbl = (uint8_t *)malloc((size_t)n * 2U);
sa_full = (int *)malloc((size_t)n * 2U * sizeof(int));
if (!dbl || !sa_full) { free(dbl); free(sa_full); return -1; }
memcpy(dbl, src, (size_t)n);
memcpy(dbl + n, src, (size_t)n);
sais_byte(dbl, 2 * n, sa_full);
for (i = 0; i < 2 * n; i++) {
int s = sa_full[i];
if (s < n) {
bwt_out[filt] = (s == 0) ? src[n - 1] : src[s - 1];
if (s == 0) primary = filt;
filt++;
}
}
free(dbl);
free(sa_full);
return primary;
}
/* BWT: doubling-SA forward (O(n log²n)), L→F inverse (O(n)). */
static __thread int *g_bwt_sa_rank;
static __thread int g_bwt_sa_k;
static __thread int g_bwt_sa_n;
static int bwt_sa_compare(const void *pa, const void *pb)
{
int a = *(const int *)pa, b = *(const int *)pb;
int ra = g_bwt_sa_rank[a], rb = g_bwt_sa_rank[b], idx_a, idx_b, ra2, rb2;
if (ra != rb) return (ra < rb) ? -1 : 1;
idx_a = a + g_bwt_sa_k; idx_b = b + g_bwt_sa_k;
if (idx_a >= g_bwt_sa_n) idx_a -= g_bwt_sa_n;
if (idx_b >= g_bwt_sa_n) idx_b -= g_bwt_sa_n;
ra2 = g_bwt_sa_rank[idx_a]; rb2 = g_bwt_sa_rank[idx_b];
if (ra2 != rb2) return (ra2 < rb2) ? -1 : 1;
return 0;
}
static int bwt_build_sa(const uint8_t *src, int n, int *sa, int *rank, int *new_rank)
{
int i, k;
if (n <= 0) return 0;
for (i = 0; i < n; i++) { sa[i] = i; rank[i] = (int)src[i]; }
for (k = 1; k <= n; k *= 2) {
int r = 0;
g_bwt_sa_rank = rank; g_bwt_sa_k = k; g_bwt_sa_n = n;
qsort(sa, (size_t)n, sizeof(int), bwt_sa_compare);
new_rank[sa[0]] = 0;
for (i = 1; i < n; i++) {
if (bwt_sa_compare(&sa[i - 1], &sa[i]) != 0) r++;
new_rank[sa[i]] = r;
}
memcpy(rank, new_rank, (size_t)n * sizeof(int));
if (r == n - 1) break;
}
return 1;
}
static int bwt_encode(const uint8_t *src, int n, uint8_t *out, int *primary_out,
int *sa, int *rank, int *new_rank)
{
int i;
if (!bwt_build_sa(src, n, sa, rank, new_rank)) return 0;
*primary_out = -1;
for (i = 0; i < n; i++) {
int s = sa[i];
out[i] = (s == 0) ? src[n - 1] : src[s - 1];
if (s == 0) *primary_out = i;
}
return (*primary_out >= 0) ? 1 : 0;
}
static void bwt_decode(const uint8_t *L, int n, int primary, uint8_t *out, int *T)
{
int count[256];
int cum[257];
int occ[256];
int i;
int c, idx;
memset(count, 0, sizeof(count));
memset(occ, 0, sizeof(occ));
for (i = 0; i < n; i++) count[L[i]]++;
cum[0] = 0;
for (c = 1; c < 257; c++) cum[c] = cum[c - 1] + count[c - 1];
for (i = 0; i < n; i++) { T[i] = cum[L[i]] + occ[L[i]]; occ[L[i]]++; }
/* Walk: T^k[primary] = row index of rotation k; L of that row = original[k-1]. */
idx = primary;
for (i = 0; i < n; i++) { idx = T[idx]; out[i] = L[idx]; }
}
/* M_BWT: byte-transpose, BWT, LZ. SA-IS used above C_BWT_DOUBLING_THRESHOLD.
* Wire: [primary_index:i32 LE][bwt_size:u32 LE][lz_size:u32 LE][lz payload]. */
#define C_BWT_DOUBLING_THRESHOLD (8U * 1024U)
static size_t bwt_enc(const ull *input, size_t num, unsigned char *transposed, unsigned char *bwt_buf,
int *sa, int *rank, int *new_rank, unsigned char *out, size_t out_cap)
{
size_t bytes = num * sizeof(ull), header_bytes = 12U, lz_size;
int primary;
if (bytes < 256U || bytes > C_BWT_MAX_BYTES) return (size_t)-1;
if ((header_bytes + bytes) > out_cap) return (size_t)-1;
byte_transpose8((const unsigned char *)(const void *)input, num, transposed);
if (bytes <= C_BWT_DOUBLING_THRESHOLD) {
if (!bwt_encode(transposed, (int)bytes, bwt_buf, &primary, sa, rank, new_rank)) return (size_t)-1;
} else {
primary = sais_cyclic_bwt(transposed, (int)bytes, bwt_buf);
if (primary < 0) return (size_t)-1;
}
lz_size = lz_enc(bwt_buf, bytes, out + header_bytes, out_cap - header_bytes);
if (lz_size > bytes || (header_bytes + lz_size) > out_cap) return (size_t)-1;
st32_le(out, (uint32_t)primary);
st32_le(out + 4, (uint32_t)bytes);
st32_le(out + 8, (uint32_t)lz_size);
return header_bytes + lz_size;
}
static void bwt_dec(const unsigned char *in, size_t in_bytes, size_t num, ull *out)
{
size_t header_bytes = 12U, bwt_size, lz_size, bytes;
int primary, *T;
unsigned char *bwt_buf, *transposed;
if (in_bytes < header_bytes) return;
primary = (int)ld32_le(in);
bwt_size = (size_t)ld32_le(in + 4);
lz_size = (size_t)ld32_le(in + 8);
bytes = num * sizeof(ull);
if (bwt_size != bytes || lz_size > in_bytes - header_bytes) return;
bwt_buf = (unsigned char *)malloc(bytes);
transposed = (unsigned char *)malloc(bytes);
T = (int *)malloc(bytes * sizeof(int));