-
Notifications
You must be signed in to change notification settings - Fork 19
/
lzav.h
1991 lines (1627 loc) · 49.2 KB
/
lzav.h
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
/**
* @file lzav.h
*
* @version 4.5
*
* @brief The inclusion file for the "LZAV" in-memory data compression and
* decompression algorithms.
*
* Description is available at https://github.com/avaneev/lzav
*
* E-mail: [email protected] or [email protected]
*
* LICENSE:
*
* Copyright (c) 2023-2024 Aleksey Vaneev
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*/
#ifndef LZAV_INCLUDED
#define LZAV_INCLUDED
#include <stdint.h>
#include <string.h>
#include <stdlib.h>
#define LZAV_API_VER 0x106 ///< API version, unrelated to code's version.
#define LZAV_VER_STR "4.5" ///< LZAV source code version string.
#if !defined( LZAV_FMT_MIN )
#define LZAV_FMT_MIN 1 ///< Minimal stream format id supported by the
///< decompressor. You may set here (or define via compile options) a
///< value of 2, to reduce decompressor's code size.
#endif // !defined( LZAV_FMT_MIN )
// Decompression error codes:
#define LZAV_E_PARAMS -1 ///< Incorrect function parameters.
#define LZAV_E_SRCOOB -2 ///< Source buffer OOB.
#define LZAV_E_DSTOOB -3 ///< Destination buffer OOB.
#define LZAV_E_REFOOB -4 ///< Back-reference OOB.
#define LZAV_E_DSTLEN -5 ///< Decompressed length mismatch.
#define LZAV_E_UNKFMT -6 ///< Unknown stream format.
// NOTE: all macros defined below are for internal use, do not change.
#define LZAV_WIN_LEN ( 1 << 23 ) ///< LZ77 window length, in bytes.
#define LZAV_REF_MIN 6 ///< Min reference length, in bytes.
#define LZAV_REF_LEN ( LZAV_REF_MIN + 15 + 255 + 254 ) ///< Max ref length.
#define LZAV_LIT_FIN 6 ///< The number of literals required at finish.
#define LZAV_FMT_CUR 2 ///< Stream format identifier used by the compressor.
/**
* @def LZAV_LITTLE_ENDIAN
* @brief Endianness definition macro, can be used as a logical constant.
*/
#if defined( __LITTLE_ENDIAN__ ) || defined( __LITTLE_ENDIAN ) || \
defined( _LITTLE_ENDIAN ) || defined( _WIN32 ) || defined( i386 ) || \
defined( __i386 ) || defined( __i386__ ) || defined( __x86_64__ ) || \
( defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ )
#define LZAV_LITTLE_ENDIAN 1
#elif defined( __BIG_ENDIAN__ ) || defined( __BIG_ENDIAN ) || \
defined( _BIG_ENDIAN ) || defined( __SYSC_ZARCH__ ) || \
defined( __zarch__ ) || defined( __s390x__ ) || defined( __sparc ) || \
defined( __sparc__ ) || \
( defined( __BYTE_ORDER__ ) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ )
#define LZAV_LITTLE_ENDIAN 0
#else // defined( __BIG_ENDIAN__ )
#warning LZAV: cannot determine endianness, assuming little-endian.
#define LZAV_LITTLE_ENDIAN 1
#endif // defined( __BIG_ENDIAN__ )
/**
* @def LZAV_ARCH64
* @brief Macro that denotes availability of 64-bit instructions.
*/
#if defined( _WIN64 ) || defined( __x86_64__ ) || defined( __ia64__ ) || \
defined( __aarch64__ ) || defined( __arm64 ) || defined( __PPC64__ ) || \
defined( __powerpc64__ ) || defined( __LP64__ ) || defined( _LP64 )
#define LZAV_ARCH64
#endif // 64-bit availability check
/**
* @def LZAV_GCC_BUILTINS
* @brief Macro that denotes availability of GCC-style built-in functions.
*/
#if defined( __GNUC__ ) || defined( __clang__ ) || \
defined( __IBMC__ ) || defined( __IBMCPP__ ) || defined( __COMPCERT__ )
#define LZAV_GCC_BUILTINS
#endif // GCC built-ins check
/**
* @def LZAV_IEC16( x )
* @brief In-place endianness-correction macro, for singular 16-bit variables.
* @param x Value to correct in-place.
*/
/**
* @def LZAV_IEC32( x )
* @brief In-place endianness-correction macro, for singular 32-bit variables.
* @param x Value to correct in-place.
*/
/**
* @def LZAV_IEC64( x )
* @brief In-place endianness-correction macro, for singular 64-bit variables.
* @param x Value to correct in-place.
*/
#if LZAV_LITTLE_ENDIAN
#define LZAV_IEC16( x )
#define LZAV_IEC32( x )
#define LZAV_IEC64( x )
#else // LZAV_LITTLE_ENDIAN
#if defined( LZAV_GCC_BUILTINS )
#define LZAV_IEC16( x ) x = __builtin_bswap16( x )
#define LZAV_IEC32( x ) x = __builtin_bswap32( x )
#elif defined( _MSC_VER )
#define LZAV_IEC16( x ) x = _byteswap_ushort( x )
#define LZAV_IEC32( x ) x = _byteswap_ulong( x )
#else // defined( _MSC_VER )
#define LZAV_IEC16( x ) x = (uint16_t) ( x >> 8 | x << 8 )
#define LZAV_IEC32( x ) x = (uint32_t) ( \
x >> 24 | \
( x & 0x00FF0000 ) >> 8 | \
( x & 0x0000FF00 ) << 8 | \
x << 24 )
#endif // defined( _MSC_VER )
#define LZAV_IEC64( x ) { \
const uint64_t sw = x >> 32 | ( x & 0xFFFFFFFF ) << 32; \
const uint64_t sw2 = ( sw & 0xFFFF0000FFFF0000 ) >> 16 | \
( sw & 0x0000FFFF0000FFFF ) << 16; \
x = ( sw2 & 0xFF00FF00FF00FF00 ) >> 8 | \
( sw2 & 0x00FF00FF00FF00FF ) << 8; }
#endif // LZAV_LITTLE_ENDIAN
/**
* @def LZAV_LIKELY( x )
* @brief Likelihood macro that is used for manually-guided
* micro-optimization.
* @param x Expression that is likely to be evaluated to 1.
*/
/**
* @def LZAV_UNLIKELY( x )
* @brief Unlikelihood macro that is used for manually-guided
* micro-optimization.
* @param x Expression that is unlikely to be evaluated to 1.
*/
#if defined( LZAV_GCC_BUILTINS ) && \
!( defined( __aarch64__ ) && defined( __APPLE__ ))
#define LZAV_LIKELY( x ) __builtin_expect( x, 1 )
#define LZAV_UNLIKELY( x ) __builtin_expect( x, 0 )
#else // Likelihood macros
#define LZAV_LIKELY( x ) ( x )
#define LZAV_UNLIKELY( x ) ( x )
#endif // Likelihood macros
#if defined( _MSC_VER ) && !defined( LZAV_GCC_BUILTINS )
#include <intrin.h> // For _BitScanForwardX and _byteswap_X.
#endif // defined( _MSC_VER ) && !defined( LZAV_GCC_BUILTINS )
/**
* @brief Data match length finding function.
*
* Function finds the number of continuously-matching leading bytes between
* two buffers. This function is well-optimized for a wide variety of
* compilers and platforms.
*
* @param p1 Pointer to buffer 1.
* @param p2 Pointer to buffer 2.
* @param ml Maximal number of bytes to match.
* @return The number of matching leading bytes.
*/
static inline size_t lzav_match_len( const uint8_t* p1, const uint8_t* p2,
const size_t ml )
{
const uint8_t* const p1s = p1;
const uint8_t* const p1e = p1 + ml;
#if defined( LZAV_ARCH64 )
while( LZAV_LIKELY( p1 + 7 < p1e ))
{
uint64_t v1, v2, vd;
memcpy( &v1, p1, 8 );
memcpy( &v2, p2, 8 );
vd = v1 ^ v2;
if( vd != 0 )
{
#if defined( LZAV_GCC_BUILTINS )
#if LZAV_LITTLE_ENDIAN
return( p1 - p1s + ( __builtin_ctzll( vd ) >> 3 ));
#else // LZAV_LITTLE_ENDIAN
return( p1 - p1s + ( __builtin_clzll( vd ) >> 3 ));
#endif // LZAV_LITTLE_ENDIAN
#else // defined( LZAV_GCC_BUILTINS )
#if defined( _MSC_VER )
unsigned long i;
_BitScanForward64( &i, (unsigned __int64) vd );
return( p1 - p1s + ( i >> 3 ));
#else // defined( _MSC_VER )
LZAV_IEC64( vd );
const uint64_t m = 0x0101010101010101;
return( p1 - p1s +
(((( vd ^ ( vd - 1 )) & ( m - 1 )) * m ) >> 56 ));
#endif // defined( _MSC_VER )
#endif // defined( LZAV_GCC_BUILTINS )
}
p1 += 8;
p2 += 8;
}
// At most 7 bytes left.
if( LZAV_LIKELY( p1 + 3 < p1e ))
{
#else // defined( LZAV_ARCH64 )
while( LZAV_LIKELY( p1 + 3 < p1e ))
{
#endif // defined( LZAV_ARCH64 )
uint32_t v1, v2, vd;
memcpy( &v1, p1, 4 );
memcpy( &v2, p2, 4 );
vd = v1 ^ v2;
if( vd != 0 )
{
#if defined( LZAV_GCC_BUILTINS )
#if LZAV_LITTLE_ENDIAN
return( p1 - p1s + ( __builtin_ctz( vd ) >> 3 ));
#else // LZAV_LITTLE_ENDIAN
return( p1 - p1s + ( __builtin_clz( vd ) >> 3 ));
#endif // LZAV_LITTLE_ENDIAN
#else // defined( LZAV_GCC_BUILTINS )
#if defined( _MSC_VER )
unsigned long i;
_BitScanForward( &i, (unsigned long) vd );
return( p1 - p1s + ( i >> 3 ));
#else // defined( _MSC_VER )
LZAV_IEC32( vd );
const uint32_t m = 0x01010101;
return( p1 - p1s +
(((( vd ^ ( vd - 1 )) & ( m - 1 )) * m ) >> 24 ));
#endif // defined( _MSC_VER )
#endif // defined( LZAV_GCC_BUILTINS )
}
p1 += 4;
p2 += 4;
}
// At most 3 bytes left.
if( p1 < p1e )
{
if( *p1 != p2[ 0 ])
{
return( p1 - p1s );
}
if( ++p1 < p1e )
{
if( *p1 != p2[ 1 ])
{
return( p1 - p1s );
}
if( ++p1 < p1e )
{
if( *p1 != p2[ 2 ])
{
return( p1 - p1s );
}
}
}
}
return( ml );
}
/**
* @brief Data match length finding function, reverse direction.
*
* @param p1 Origin pointer to buffer 1.
* @param p2 Origin pointer to buffer 2.
* @param ml Maximal number of bytes to back-match.
* @return The number of matching prior bytes, not including origin position.
*/
static inline size_t lzav_match_len_r( const uint8_t* p1, const uint8_t* p2,
const size_t ml )
{
if( LZAV_UNLIKELY( ml == 0 ))
{
return( 0 );
}
if( p1[ -1 ] != p2[ -1 ])
{
return( 0 );
}
if( LZAV_UNLIKELY( ml != 1 ))
{
const uint8_t* const p1s = p1;
const uint8_t* p1e = p1 - ml + 1;
p1--;
p2--;
while( LZAV_UNLIKELY( p1 > p1e ))
{
uint16_t v1, v2;
memcpy( &v1, p1 - 2, 2 );
memcpy( &v2, p2 - 2, 2 );
const uint32_t vd = v1 ^ v2;
if( vd != 0 )
{
#if LZAV_LITTLE_ENDIAN
return( p1s - p1 + (( vd & 0xFF00 ) == 0 ));
#else // LZAV_LITTLE_ENDIAN
return( p1s - p1 + (( vd & 0x00FF ) == 0 ));
#endif // LZAV_LITTLE_ENDIAN
}
p1 -= 2;
p2 -= 2;
}
p1e--;
if( p1 > p1e && p1[ -1 ] != p2[ -1 ])
{
return( p1s - p1 );
}
}
return( ml );
}
/**
* @brief Internal LZAV block header writing function (stream format 2).
*
* Internal function writes a block to the output buffer. This function can be
* used in custom compression algorithms.
*
* Stream format 2.
*
* "Raw" compressed stream consists of any quantity of unnumerated "blocks".
* A block starts with a header byte, followed by several optional bytes.
* Bits 4-5 of the header specify block's type.
*
* CC00LLLL: literal block (1-6 bytes). `LLLL` is literal length.
* OO01RRRR: 10-bit offset block (2-4 bytes). `RRRR` is reference length.
* OO10RRRR: 18-bit offset block (3-5 bytes).
* OO11RRRR: 23-bit offset block (4-6 bytes).
*
* If `LLLL` or `RRRR` equals 0, a value of 16 is assumed, and an additional
* length byte follows. If in a literal block this additional byte's highest
* bit is 1, one more length byte follows that defines higher bits of length
* (up to 4 bytes). In a reference block, additional 1-2 length bytes follow
* the offset bytes. `CC` is a reference offset carry value (additional 2
* lowest bits of offset of the next reference block). Block type 3 includes 3
* carry bits (highest bits of 4th byte).
*
* The overall compressed data is prefixed with a byte whose lower 4 bits
* contain minimal reference length (mref), and the highest 4 bits contain
* stream format identifier. Compressed data always finishes with
* `LZAV_LIT_FIN` literals. The lzav_write_fin_2() function should be used to
* finalize compression.
*
* Except the last block, a literal block is always followed by a reference
* block.
*
* @param op Output buffer pointer.
* @param lc Literal length, in bytes.
* @param rc Reference length, in bytes, not lesser than mref.
* @param d Reference offset, in bytes. Should be lesser than `LZAV_WIN_LEN`,
* and not lesser than `rc` since fast copy on decompression cannot provide
* consistency of copying of data that is not in the output yet.
* @param ipa Literals anchor pointer.
* @param cbpp Pointer to the pointer to the latest offset carry block header.
* Cannot be 0, but the contained pointer can be 0 (initial value).
* @param cshp Pointer to offset carry shift.
* @param mref Minimal reference length, in bytes, used by the compression
* algorithm.
* @return Incremented output buffer pointer.
*/
static inline uint8_t* lzav_write_blk_2( uint8_t* op, size_t lc, size_t rc,
size_t d, const uint8_t* ipa, uint8_t** const cbpp, int* const cshp,
const size_t mref )
{
// Perform offset carry to a previous block (`csh` may be zero).
const int csh = *cshp;
rc = rc + 1 - mref;
**cbpp |= (uint8_t) (( d << 8 ) >> csh );
d >>= csh;
if( LZAV_UNLIKELY( lc != 0 ))
{
// Write a literal block.
size_t cv; // Offset carry value in literal block.
cv = ( d & 3 ) << 6;
d >>= 2;
if( LZAV_LIKELY( lc < 9 ))
{
*op = (uint8_t) ( cv | lc );
op++;
memcpy( op, ipa, 8 );
op += lc;
}
else
if( LZAV_LIKELY( lc < 16 ))
{
*op = (uint8_t) ( cv | lc );
op++;
memcpy( op, ipa, 16 );
op += lc;
}
else
if( LZAV_LIKELY( lc < 16 + 128 ))
{
#if LZAV_LITTLE_ENDIAN
uint16_t ov = (uint16_t) (( lc - 16 ) << 8 | cv );
#else // LZAV_LITTLE_ENDIAN
uint16_t ov = (uint16_t) ( cv << 8 | ( lc - 16 ));
#endif // LZAV_LITTLE_ENDIAN
memcpy( op, &ov, 2 );
op += 2;
memcpy( op, ipa, 16 );
memcpy( op + 16, ipa + 16, 16 );
if( lc < 33 )
{
op += lc;
}
else
{
ipa += 32;
op += 32;
lc -= 32;
do
{
*op = *ipa;
ipa++;
op++;
} while( --lc != 0 );
}
}
else
{
*op = (uint8_t) cv;
op++;
size_t lcw = lc - 16;
while( lcw > 127 )
{
*op = (uint8_t) ( 0x80 | lcw );
lcw >>= 7;
op++;
}
*op = (uint8_t) lcw;
op++;
memcpy( op, ipa, lc );
op += lc;
}
}
// Write a reference block.
static const int ocsh[ 4 ] = { 0, 0, 0, 3 };
const size_t bt = 1 + ( d > ( 1 << 10 ) - 1 ) + ( d > ( 1 << 18 ) - 1 );
if( LZAV_LIKELY( rc < 16 ))
{
uint32_t ov = (uint32_t) ( d << 6 | bt << 4 | rc );
LZAV_IEC32( ov );
memcpy( op, &ov, 4 );
op += bt;
*cshp = ocsh[ bt ];
*cbpp = op;
return( op + 1 );
}
uint32_t ov = (uint32_t) ( d << 6 | bt << 4 );
LZAV_IEC32( ov );
memcpy( op, &ov, 4 );
op += bt;
*cshp = ocsh[ bt ];
*cbpp = op;
if( LZAV_LIKELY( rc < 16 + 255 ))
{
op[ 1 ] = (uint8_t) ( rc - 16 );
return( op + 2 );
}
op[ 1 ] = (uint8_t) 255;
op[ 2 ] = (uint8_t) ( rc - 16 - 255 );
return( op + 3 );
}
/**
* @brief Internal LZAV finishing function (stream format 2).
*
* Internal function writes finishing literal block(s) to the output buffer.
* This function can be used in custom compression algorithms.
*
* Stream format 2.
*
* @param op Output buffer pointer.
* @param lc Literal length, in bytes. Not less than `LZAV_LIT_FIN`.
* @param ipa Literals anchor pointer.
* @return Incremented output buffer pointer.
*/
static inline uint8_t* lzav_write_fin_2( uint8_t* op, size_t lc,
const uint8_t* ipa )
{
if( lc < 16 )
{
*op = (uint8_t) lc;
op++;
}
else
{
*op = 0;
op++;
size_t lcw = lc - 16;
while( lcw > 127 )
{
*op = (uint8_t) ( 0x80 | lcw );
lcw >>= 7;
op++;
}
*op = (uint8_t) lcw;
op++;
}
memcpy( op, ipa, lc );
return( op + lc );
}
/**
* @brief Function returns buffer size required for LZAV compression.
*
* @param srcl The length of the source data to be compressed.
* @return The required allocation size for destination compression buffer.
* Always a positive value.
*/
static inline int lzav_compress_bound( const int srcl )
{
if( srcl <= 0 )
{
return( 16 );
}
const int k = 16 + 127 + 1;
const int l2 = srcl / ( k + 6 );
return(( srcl - l2 * 6 + k - 1 ) / k * 2 - l2 + srcl + 16 );
}
/**
* @brief Function returns buffer size required for the higher-ratio LZAV
* compression.
*
* @param srcl The length of the source data to be compressed.
* @return The required allocation size for destination compression buffer.
* Always a positive value.
*/
static inline int lzav_compress_bound_hi( const int srcl )
{
if( srcl <= 0 )
{
return( 16 );
}
const int l2 = srcl / ( 16 + 5 );
return(( srcl - l2 * 5 + 15 ) / 16 * 2 - l2 + srcl + 16 );
}
/**
* @brief LZAV compression function, with external buffer option.
*
* Function performs in-memory data compression using the LZAV compression
* algorithm and stream format. The function produces a "raw" compressed data,
* without a header containing data length nor identifier nor checksum.
*
* Note that compression algorithm and its output on the same source data may
* differ between LZAV versions, and may differ between big- and little-endian
* systems. However, the decompression of a compressed data produced by any
* prior compressor version will remain possible.
*
* @param[in] src Source (uncompressed) data pointer, can be 0 if `srcl`
* equals 0. Address alignment is unimportant.
* @param[out] dst Destination (compressed data) buffer pointer. The allocated
* size should be at least lzav_compress_bound() bytes large. Address
* alignment is unimportant. Should be different to `src`.
* @param srcl Source data length, in bytes, can be 0: in this case the
* compressed length is assumed to be 0 as well.
* @param dstl Destination buffer's capacity, in bytes.
* @param ext_buf External buffer to use for hash-table, set to 0 for the
* function to manage memory itself (via standard `malloc`). Supplying a
* pre-allocated buffer is useful if compression is performed during
* application's operation often: this reduces memory allocation overhead and
* fragmentation. Note that the access to the supplied buffer is not
* implicitly thread-safe. Buffer's address must be aligned to 32 bits.
* @param ext_bufl The capacity of the `ext_buf`, in bytes, should be a
* power-of-2 value. Set to 0 if `ext_buf` is 0. The capacity should not be
* lesser than 4 x `srcl`, and for default compression ratio should not be
* greater than 1 MiB. Same `ext_bufl` value can be used for any smaller
* source data. Using smaller `ext_bufl` values reduces the compression ratio
* and, at the same time, increases compression speed. This aspect can be
* utilized on memory-constrained and low-performance processors.
* @return The length of compressed data, in bytes. Returns 0 if `srcl` is
* lesser or equal to 0, or if `dstl` is too small, or if buffer pointers are
* invalid, or if not enough memory.
*/
static inline int lzav_compress( const void* const src, void* const dst,
const int srcl, const int dstl, void* const ext_buf, const int ext_bufl )
{
if(( srcl <= 0 ) | ( src == 0 ) | ( dst == 0 ) | ( src == dst ) |
( dstl < lzav_compress_bound( srcl )))
{
return( 0 );
}
uint8_t* op = (uint8_t*) dst; // Destination (compressed data) pointer.
*op = LZAV_FMT_CUR << 4 | LZAV_REF_MIN; // Write prefix byte.
op++;
if( srcl < 16 )
{
// Handle a very short source data.
*op = (uint8_t) srcl;
op++;
memcpy( op, src, srcl );
if( srcl > LZAV_LIT_FIN - 1 )
{
return( 2 + srcl );
}
memset( op + srcl, 0, LZAV_LIT_FIN - srcl );
return( 2 + LZAV_LIT_FIN );
}
uint32_t stack_buf[ 4096 ]; // On-stack hash-table.
void* alloc_buf = 0; // Hash-table allocated on heap.
uint8_t* ht = (uint8_t*) stack_buf; // The actual hash-table pointer.
size_t htsize; // Hash-table's size in bytes (power-of-2).
htsize = ( 1 << 7 ) * sizeof( uint32_t ) * 4;
if( ext_buf == 0 )
{
while( htsize != ( 1 << 20 ) && ( htsize >> 2 ) < (size_t) srcl )
{
htsize <<= 1;
}
if( htsize > sizeof( stack_buf ))
{
alloc_buf = malloc( htsize );
if( alloc_buf == 0 )
{
return( 0 );
}
ht = (uint8_t*) alloc_buf;
}
}
else
{
size_t htsizem;
if( ext_bufl > (int) sizeof( stack_buf ))
{
htsizem = (size_t) ext_bufl;
ht = (uint8_t*) ext_buf;
}
else
{
htsizem = sizeof( stack_buf );
}
while(( htsize >> 2 ) < (size_t) srcl )
{
const size_t htsize2 = htsize << 1;
if( htsize2 > htsizem )
{
break;
}
htsize = htsize2;
}
}
const uint32_t hmask = (uint32_t) (( htsize - 1 ) ^ 15 ); // Hash mask.
const uint8_t* ip = (const uint8_t*) src; // Source data pointer.
const uint8_t* const ipe = ip + srcl - LZAV_LIT_FIN; // End pointer.
const uint8_t* const ipet = ipe - 9; // Hashing threshold, avoids I/O OOB.
const uint8_t* ipa = ip; // Literals anchor pointer.
uint8_t* cbp = op; // Pointer to the latest offset carry block header.
int csh = 0; // Offset carry shift.
intptr_t mavg = 100 << 21; // Running average of hash match rate (*2^15).
// Two-factor average: success (0-64) by average reference length.
uint32_t rndb = 0; // PRNG bit derived from the non-matching offset.
ip += 16; // Skip source bytes, to avoid OOB in back-match.
// Initialize the hash-table. Each hash-table item consists of 2 tuples
// (4 initial match bytes; 32-bit source data offset). Set source data
// offset to avoid OOB in back-match.
uint32_t initv[ 2 ] = { 0, 16 };
if( LZAV_LIKELY( ip < ipet ))
{
memcpy( initv, ip, 4 );
}
uint32_t* ht32 = (uint32_t*) ht;
uint32_t* const ht32e = (uint32_t*) ( ht + htsize );
while( ht32 != ht32e )
{
ht32[ 0 ] = initv[ 0 ];
ht32[ 1 ] = initv[ 1 ];
ht32 += 2;
}
while( LZAV_LIKELY( ip < ipet ))
{
// Hash source data (endianness is unimportant for compression
// efficiency). Hash is based on the "komihash" math construct, see
// https://github.com/avaneev/komihash for details.
uint32_t iw1;
uint16_t iw2, ww2;
memcpy( &iw1, ip, 4 );
const uint32_t Seed1 = 0x243F6A88 ^ iw1;
memcpy( &iw2, ip + 4, 2 );
const uint64_t hm = (uint64_t) Seed1 * (uint32_t) ( 0x85A308D3 ^ iw2 );
const uint32_t hval = (uint32_t) hm ^ (uint32_t) ( hm >> 32 );
// Hash-table access.
uint32_t* const hp = (uint32_t*) ( ht + ( hval & hmask ));
const uint32_t ipo = (uint32_t) ( ip - (const uint8_t*) src );
const uint32_t hw1 = hp[ 0 ]; // Tuple 1's match word.
const uint8_t* wp; // At window pointer.
size_t d, ml, rc, lc;
// Find source data in hash-table tuples.
if( LZAV_LIKELY( iw1 != hw1 ))
{
if( LZAV_LIKELY( iw1 != hp[ 2 ]))
{
goto _no_match;
}
wp = (const uint8_t*) src + hp[ 3 ];
memcpy( &ww2, wp + 4, 2 );
if( LZAV_UNLIKELY( iw2 != ww2 ))
{
goto _no_match;
}
}
else
{
wp = (const uint8_t*) src + hp[ 1 ];
memcpy( &ww2, wp + 4, 2 );
if( LZAV_UNLIKELY( iw2 != ww2 ))
{
if( LZAV_LIKELY( iw1 != hp[ 2 ]))
{
goto _no_match;
}
wp = (const uint8_t*) src + hp[ 3 ];
memcpy( &ww2, wp + 4, 2 );
if( LZAV_UNLIKELY( iw2 != ww2 ))
{
goto _no_match;
}
}
}
d = ip - wp; // Reference offset (distance).
if( LZAV_UNLIKELY(( d < 8 ) | ( d > LZAV_WIN_LEN - 1 )))
{
// Small offsets may be inefficient.
goto _d_oob;
}
// Source data and hash-table entry match.
// Disallow reference copy overlap by using `d` as max match length.
ml = ( d > LZAV_REF_LEN ? LZAV_REF_LEN : d );
if( LZAV_UNLIKELY( ip + ml > ipe ))
{
// Make sure `LZAV_LIT_FIN` literals remain on finish.
ml = ipe - ip;
}
if( LZAV_LIKELY( d > 273 ))
{
// Update a matching entry which is not inside max reference
// length's range. Otherwise, source data consisting of same-byte
// runs won't compress well.
if( LZAV_LIKELY( iw1 == hw1 )) // Replace tuple, or insert.
{
hp[ 1 ] = ipo;
}
else
{
hp[ 2 ] = hw1;
hp[ 3 ] = hp[ 1 ];
hp[ 0 ] = iw1;
hp[ 1 ] = ipo;
}
}
rc = LZAV_REF_MIN + lzav_match_len( ip + LZAV_REF_MIN,
wp + LZAV_REF_MIN, ml - LZAV_REF_MIN );
lc = ip - ipa;
if( LZAV_UNLIKELY( lc != 0 ))
{
// Try to consume literals by finding a match at a back-position.
ml -= rc;
size_t bmc = ( lc > 16 ? 16 : lc );
if( LZAV_LIKELY( ml > bmc ))
{
ml = bmc;
}
bmc = lzav_match_len_r( ip, wp, ml );
if( LZAV_UNLIKELY( bmc != 0 ))
{
rc += bmc;
ip -= bmc;
lc -= bmc;
}
}
op = lzav_write_blk_2( op, lc, rc, d, ipa, &cbp, &csh, LZAV_REF_MIN );
ip += rc;
ipa = ip;
mavg += ( (intptr_t) ( rc << 21 ) - mavg ) >> 10;
continue;
_d_oob:
ip++;
if( LZAV_LIKELY( d < LZAV_WIN_LEN ))
{
continue;
}
hp[ 1 + ( iw1 != hw1 ) * 2 ] = ipo;
continue;
_no_match:
hp[ 2 ] = iw1;
hp[ 3 ] = ipo;
mavg -= mavg >> 11;
if( mavg < ( 200 << 14 ) && ip != ipa ) // Speed-up threshold.
{
// Compression speed-up technique that keeps the number of hash
// evaluations around 45% of compressed data length. In some cases
// reduces the number of blocks by several percent.
ip += 1 + rndb; // Use PRNG bit to dither match positions.
rndb = ipo & 1; // Delay to decorrelate from current match.
if( LZAV_UNLIKELY( mavg < ( 130 << 14 )))
{
ip++;
if( LZAV_UNLIKELY( mavg < ( 100 << 14 )))
{
ip += 100 - ( mavg >> 14 ); // Gradually faster.
}
}
}
ip++;
}
if( alloc_buf != 0 )