-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmlh.d
More file actions
1948 lines (1603 loc) · 59.8 KB
/
Copy pathmlh.d
File metadata and controls
1948 lines (1603 loc) · 59.8 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
/*multi-level huffman & lzw
Author: Ryan Cecil
Date: Jan 06 2013
Last Updated: Jan 08 2013
Description: Incorporates useage of BitArray with LZ77 and huffman compression.
Currently in development and API will likely change and be refactored.
Highly Verbose for debugging, lacks full documentation and unittests.
MLH (Multi-level-Huffman) lacks tree save/load functions.
Be warned, it may look a little ugly...
Compiler: Win32 dmd 2.061
LZ Usage:
---
//rather than hello world, forces compression. Borrowed from zlib
string helloString = "Hello Hello";
void[] compressed = lzCompress(helloString);
writeln(compressed); //raw compressed state
string uncompressed = cast(string) lzDeCompress(compressed);
writeln(uncompressed);
assert(helloString == uncompressed);
---
MLH Usage:
---
string fox = "The quick red fox jumps over the lazy dog";
//allows multiple scans
//order 0/no levels. regular huffman.
//higher orders greatly increases compression,
//but tree overhead greatly increases too
BitArray compressed;
auto huffCode = huffmanScan(fox, 0);
makeBitCodes(huffCode); //make scan usable for compress/decompress
mlhWrite(compressed, huffCode); //save tree
mlhCompress(compressed, huffCode, fox, 0); //compress data
writeln(compressed); //encoded is BitArray. Raw saved data.
//reverse, decode & decompress
int offset;
huffCode = mlhRead(compressed, offset);
auto compressedText = compressed[offset .. $];
auto decoded = cast(string) mlhDecompress(huffCode, compressedText);
assert(fox == decoded);
writeln(decoded);
---
Updates:
2/10/2013 - Removed most of uneeded outputs, removed 'w' from lz tag since it's
misleading.
2/26/2013 - Removed templates required using LZ, instead uses BitArray's intWrite.
Added a partial LMZA implimentation, called LZE
TODO: Add more documentation, Remove explicit level requirement for mlhCompress.
Change names to better reflect actual purpose and intent.
Update raw characters (multiple level) to use intWrite instead.
Add more unittests.
Add LZW alternative that allows any size for LZW struct (BitArray)
Reorganize most mlh functions into struct
Add constructors for mlh.
Re-work functions to use ranges instead of const array & offset
Remove debugging writeln's scattered throughout the code.
*/
module mlh;
import std.algorithm;
import std.stdio;
import bitmanip; //std. missing for local test copy.
import std.conv;
//lz77 implimentation. Not fully tested.
//for BitArray constants mostly
struct LZ {
enum windowMin = 1;
enum rawMin = 1;
//settings
int windowBits = 11;
int lengthBits = 4;
int rawBits = 7;
//modifyable
int windowPos; //going back
int length;
///determine max window size (behind) that it can search
int windowMax() const pure @property @safe {
return (1 << windowBits) - windowMin;
}
///minimum length for any compression possible.
int lengthMin() const pure @property @safe {
//if it's equal by bytes, 1 byte more
//otherwise extra bits to the rounding of the byte is enough.
return ((windowBits + lengthBits + 7) / 8) + 1;
}
///maximum length this can support based on settings
int lengthMax() const pure @property @safe {
return (1 << lengthBits) + lengthMin - 1;
}
int rawMax() const pure @property @safe {
return 1 << rawBits;
}
//any illegal data is 'raw'.
bool isRaw() const pure @property @safe {
return (windowPos < windowMin) || (windowPos > windowMax) ||
(length < lengthMin) || (length > lengthMax);
}
void clear() pure @safe{ windowPos = length = 0; }
void print() {
writeln("windowMax: ", windowMax);
writeln("lengthMin: ", lengthMin);
writeln("lengthMax: ", lengthMax);
writeln("windowPos: ", windowPos);
writeln("rawMax: ", this.rawMax);
writeln("length: ", length);
writeln("isRaw: ", this.isRaw);
}
}
unittest {
LZ lz;
assert(lz.isRaw);
lz.windowPos = 1;
assert(lz.isRaw);
lz.length = 1;
assert(lz.isRaw); //should be wrong until length is 3
lz.length = 2;
assert(lz.isRaw);
lz.length = 3;
assert(!lz.isRaw); //should be wrong until length is 3
assert(lz.rawMax == 128);
lz.rawBits = 3;
assert(lz.rawMax == 8);
}
void[] lzCompress(const void[] rawInput,
int windowBits = 11, int lengthBits = 4, int rawBits = 7,
int maxBits = 16) {
return lzCompress(rawInput, null, windowBits, lengthBits, rawBits, maxBits);
}
///
void[] lzCompress(const void[] rawInput, SwiftSearch ss,
int windowBits = 11, int lengthBits = 4, int rawBits = 7,
int maxBits = 16)
in {
assert(windowBits <= maxBits, "window/distance has too many bits for signature");
assert(lengthBits <= maxBits, "length has too many bits for signature");
assert(rawBits < maxBits, "rawBits has too many bits for signature");
}
body {
BitArray ba_data;
LZ lz_data = LZ(windowBits, lengthBits, rawBits);
ubyte[] input = cast(ubyte[]) rawInput;
ubyte[] window;
int rawStart = 0;
ba_data.reserve(input.length * 10);
//1 byte information specifying bit lengths for window/length
//
ba_data.intWrite(windowBits, 1, maxBits);
ba_data.intWrite(lengthBits, 1, maxBits);
ba_data.intWrite(rawBits, 0, maxBits-1);
if (!ss)
ss = swiftSearchScan(input);
else
ss = ss.dup; //shallow copy
foreach(int position; rawStart .. input.length) {
if (position < rawStart)
continue;
lz_data = windowSearch(lz_data, ss, input, position);
if (lz_data.isRaw)
continue;
//uncompressed data
bulkRawWrite(lz_data, ba_data, input[rawStart .. position]);
debug { writeln("LZ: dist: ", lz_data.windowPos, ", len: ", lz_data.length); }
//window/compressed data
ba_data ~= false; //prefix
ba_data.intWrite(lz_data.windowPos, lz_data.windowMin, lz_data.windowMax);
ba_data.intWrite(lz_data.length, lz_data.lengthMin, lz_data.lengthMax);
rawStart = position + lz_data.length;
lz_data.clear();
}
//append last unused raw
bulkRawWrite(lz_data, ba_data, input[rawStart .. $]);
void[] buff;
ba_data.getBuffer(buff);
return buff[0 .. ((cast(int) ba_data.length + 7) / 8)];
}
//rough implimentations, scans the window area for the longest possible match
//returns the position & length, or isRaw
//minGain is how many bytes of compression so beyond the lengthMin
T windowSearch(T)(T lz, const ubyte[] input, int position, int minGain = int.max) {
lz.clear();
foreach(i; 0 .. position) {
//if within window length of the search, and meets the minimum length
if ((position-i) <= lz.windowMax && (position+lz.lengthMin) < input.length &&
input[i .. i+lz.lengthMin] == input[position .. position+lz.lengthMin]) {
int length = lz.lengthMin;
//continue further scan to see how long it is
//so long as the length doesn't exceed our max
while((length < lz.lengthMax) &&
((position+length) < input.length) &&
(input[i+length] == input[position+length])) {
length++;
}
if (length > lz.length) {
lz.length = length;
lz.windowPos = position - i;
}
}
//early quit when successfully finds 'long enough' match
if ((lz.length - lz.lengthMin) >= minGain || lz.length == lz.lengthMax)
break;
}
return lz;
}
alias uint[][] SwiftSearch;
//creates an array lookup of where 1-3 bytes matches are speeding up
//basic searches for window Search if included.
SwiftSearch swiftSearchScan(const ubyte[] input, int levels = 1) {
SwiftSearch ss;
assert(levels >= 1 && levels <= 3);
//32bit can only really handle 3 bytes, good for most matches of 3 bytes or larger needed.
ss.length = 1<<(levels * 8);
foreach(i, ub; input[0 .. $-(levels - 1)]) {
int val = 0;
auto t = input[i .. i+levels];
while (t.length) {
val <<= 8;
val |= t[0];
t = t[1 .. $];
}
ss[val] ~= i;
}
return ss;
}
//a bit of duplication from here with windowSearch, likely to be more.
//Will be refactored later once I'm satisfied with a good working model
//rough implimentations, scans the window area for the longest possible match
//returns the position & length, or isRaw. dontChange is for slicing the
//now unreachable sections, so they aren't constantly rescanned as we progress
T windowSearch(T)(T lz, ref SwiftSearch ss, const ubyte[] input, int position, bool dontChange = false, int minGain = int.max) {
lz.clear();
if (!ss.length)
return windowSearch(lz, input, position);
uint[] scanArray;
int offset;
switch(ss.length) {
case 1<<8: offset = input[position]; break;
case 1<<16:
if ((input.length - position) < 2)
return lz;
offset = (input[position] << 8) |
input[position + 1];
break;
case 1<<24:
if ((input.length - position) < 3)
return lz;
offset = (input[position] << 16) |
(input[position + 1] << 8) |
input[position + 2];
break;
default:
}
//get the whole section matching 1-3 characters
scanArray = ss[offset];
debug { writeln(scanArray); }
while (scanArray.length && ((position - scanArray[0]) > lz.windowMax)) {
scanArray = scanArray[1 .. $]; //shorten off ones that can't qualify
continue;
}
//update to shorter array unless told otherwise
if (!dontChange)
ss[offset] = scanArray;
foreach(i; scanArray) {
if (i >= position)
break;
int minLength = lz.lengthMin;
if ((position+minLength) < input.length &&
input[i .. i + minLength] == input[position .. position + minLength]) {
int length = minLength;
//continue further scan to see how long it is
//so long as the length doesn't exceed our max
while(length < lz.lengthMax &&
(position+length) < input.length &&
input[i+length] == input[position+length]) {
length++;
}
if (length > lz.length) {
lz.length = length;
lz.windowPos = position - i;
}
}
//early quit when successfully finds 'long enough' match
if ((lz.length - minLength) >= minGain || lz.length == lz.lengthMax)
break;
}
debug { writeln("\nWindow Search: "); /*lz.print();*/ }
return lz;
}
//takes whole length of input and prepends a 'raw' LZ block.
//repeats until full raw data is written
void bulkRawWrite(LZ lz, ref BitArray ba, const(ubyte)[] input) {
//append last unused raw
while(input.length) {
lz.clear();
lz.length = min(input.length, lz.rawMax);
ba ~= true; //prepend 'raw' bit
ba.intWrite(lz.length, lz.rawMin, lz.rawMax);
debug { writeln("BRW - Raw: ", lz.length); }
foreach(i, ub; input) {
if (i >= lz.length)
break;
ba.rawWrite(ub);
debug { writeln(" ", ub); }
}
input = input[lz.length .. $];
}
}
void bulkRawWrite(LZE lz, ref BitArray ba, const(ubyte)[] input) {
//append last unused raw
while(input.length) {
lz.raw.value = min(lz.rawMax, input.length);
ba ~= false; //prepend 'raw' bit
lz.raw.encode(ba);
debug { writeln("BRW (lze) - Raw: ", lz.raw.value); writeln(ba);}
foreach(i, ub; input) {
if (i >= lz.raw.value)
break;
ba.rawWrite(ub);
debug { writeln(" ", ub); }
debug { writeln(ba); }
}
input = input[lz.raw.value .. $];
}
}
///
void[] lzDeCompress(const void[] input, int maxBits = 16) {
ubyte[] buffer;
const BitArray ba = BitArray(cast(void[]) input);
int window, length;
int offset;
bool isRaw;
LZ lz;
//16/16 limitation keeps down to 1 byte for data
offset += ba.intRead(lz.windowBits, offset, 1, maxBits);
offset += ba.intRead(lz.lengthBits, offset, 1, maxBits);
offset += ba.intRead(lz.rawBits, offset, 0, maxBits - 1);
int minSize = min(1 + lz.rawBits + 8, lz.windowBits + lz.lengthBits+1);
while((ba.length - offset) >= minSize) {
offset += ba.rawRead(isRaw, offset);
if (isRaw) {
offset += ba.intRead(lz.length, offset, lz.rawMin, lz.rawMax);
for(int i = lz.length; i; i--) {
ubyte ub;
offset += ba.rawRead(ub, offset);
buffer ~= ub;
}
} else {
offset += ba.intRead(lz.windowPos, offset, lz.windowMin, lz.windowMax);
offset += ba.intRead(lz.length, offset, lz.lengthMin, lz.lengthMax);
//overlapping copy, likely long string like "*****"
//can't have optimizations as they might not copy it right.screw it up.
if (lz.windowPos < lz.length) {
buffer.length = buffer.length + lz.length;
auto lhs = buffer[($-lz.windowPos-lz.length) .. $];
auto rhs = buffer[$-lz.length .. $];
/* memmove/memcpy failed with sections so close to eachother. likely 32bit copy used
import std.c.string;
memcpy(rhs.ptr, lhs.ptr, lz..length);
*/
foreach(i, ref b; rhs)
b = lhs[i];
} else
buffer ~= buffer[($-lz.windowPos) .. ($-lz.windowPos+lz.length)];
}
}
return cast(void[]) buffer;
}
unittest {
string s = "Hello Hello";
//2 byte struct sequence
void[] x = lzCompress(s);
writeln(x);
// writeln(cast(string) x);
// writeln(x.length);
string y = cast(string) lzDeCompress(x);
assert(y == s);
//one byte mini-compress
void[] x2 = lzCompress(s,4,3);
writeln(x2);
string y2 = cast(string) lzDeCompress(x2);
// writeln(cast(string)y);
// assert(x2.length < s.length);
assert(y2 == s);
string dups = "--------";
auto x3 = lzCompress(dups,4,3);
writeln(x3);
string y3 = cast(string) lzDeCompress(x3);
writeln(y3);
writeln(dups);
assert(y3 == dups);
string dups2 = "abcabcabc";
auto x4 = lzCompress(dups2,4,3);
writeln(x4);
string y4 = cast(string) lzDeCompress(x4);
assert(y4 == dups2);
string longBuffer = dups ~ dups ~ dups ~ dups;
x3 = lzCompress(longBuffer,4,3);
writeln(x3);
y3 = cast(string) lzDeCompress(x3);
assert(y3 == longBuffer);
//currently breaks
x3 = lzCompress(longBuffer);
writeln(x3);
y3 = cast(string) lzDeCompress(x3);
assert(y3 == longBuffer);
}
/*LZMA according to wikipedia using prefixes to optimize for different lengths/types
of data. Unfortunately the details on distance is lacking and this isn't dictionary
based so the length and a few details are borrowed and improvised.
This is LZE:
packed code (bit sequence), packet name, packet description
0 + byteCode LIT A single byte encoded
1 + len + dist MATCH A typical LZ77 sequence
The length is encoded as follows:
Length code (bit sequence) Description
0+ 3 bits The length encoded using 3 bits, gives the lengths range from 2 to 9.
1+0+ 3 bits The length encoded using 3 bits, gives the lengths range from 10 to 17.
1+1+ 8 bits The length encoded using 8 bits, gives the lengths range from 18 to 273.
Distance is lacking, so we'll do our own.
0 +4 bits Distance from 1-16
1+0 +6 bits Distance from 17-81
1+1 +11 bits Distance from 82-2130
Minimum code is 9 bits (raw) and 10 bits (short distance/length). No special EOF's
to worry about.
*/
/*handles encoding/decoding of prefixed values in a range.
This lets you put various combinations prefixes and the accumulated values
in order to save data better. Also will encode the data to a BitArray for you.
*/
struct PrefixCodes {
const(bool[])[] prefix;
const(int)[] bitSizes;
int rawMin; //adjusts as the min value before min/max figure it out
//accumulates from prevoius values. So...
int value;
int maxLevels() const @property pure @safe { return prefix.length; }
int minBits() const @property pure @safe {
int bits = int.max;
foreach(i, bs; bitSizes) {
bits = min(bits, prefix[i].length + bs);
}
return bits;
}
int maxBits() const @property pure @safe {
int bits;
foreach(i, bs; bitSizes) {
bits = max(bits, prefix[i].length + bs);
}
return bits;
}
static struct Calc {
int level, min, max;
}
//get encoding details based on value
Calc results() const pure @safe {
Calc val;
val.level = 0;
val.min = rawMin;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
while (((val.level+1) < bitSizes.length) && ((value < val.min) || (value > val.max))) {
val.level++;
val.min = val.max + 1;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
}
if (val.min > value || value > val.max)
val.level = -1;
return val;
}
//with the level known, gets details (for decoding)
Calc results(int levels) const pure @safe {
Calc val;
if (levels >= bitSizes.length)
return Calc(-1);
val.level = 0;
val.min = rawMin;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
while (val.level < levels) {
val.level++;
val.min = val.max + 1;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
}
return val;
}
//returns the min/max/level the level covers.
Calc resultsFrom(int checkValue) const pure @safe {
Calc val;
//check for out of range (Before the ranges)
if (checkValue < rawMin)
return Calc(-1);
val.level = 0;
val.min = rawMin;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
while ((val.min > checkValue) && ((val.level + 1) < maxLevels)) {
val.level++;
val.min = val.max + 1;
val.max = val.min + (1 << bitSizes[val.level]) - 1;
}
if ((val.min > checkValue) || (val.max < checkValue))
return Calc(-1);
return val;
}
//encodes sequence to bitarray
int encode(ref BitArray array) const {
auto prevLength = array.length;
Calc val = results();
if ((val.level < 0) || (val.level >= prefix.length))
return 0;
array ~= prefix[val.level];
array.intWrite(value, val.min, val.max);
return cast(int) (array.length - prevLength);
}
//decodes sequence to value, returns bits read.
int decode(const BitArray array) {
int length;
foreach(i, pre; prefix) {
if (array[0 .. pre.length] == pre) {
length = pre.length;
auto val = results(i);
length += array.intRead(value, length, val.min, val.max);
break;
}
}
return length;
}
unittest {
PrefixCodes pre = PrefixCodes( [[false],[true, false],[true, true]], [2,3,4], 1);
//0 1-4, - 3 bits
//1 5-12,- 5 bits
//2 13-28- 6 bits
//results
auto c = pre.results();
assert(c.level == -1); //0 not valid
int i=1;
while(i <= 4) {
pre.value = i;
c = pre.results();
assert(c.level == 0);
assert(c.min == 1);
assert(c.max == 4);
i++;
}
while(i <= 12) {
pre.value = i;
c = pre.results();
assert(c.level == 1);
assert(c.min == 5);
assert(c.max == 12);
i++;
}
while(i <= 28) {
pre.value = i;
c = pre.results();
assert(c.level == 2);
assert(c.min == 13);
assert(c.max == 28);
i++;
}
pre.value = i; //32
c = pre.results();
assert(c.level == -1); //0 not valid
//results(levels)
c = pre.results(0);
assert(c.level == 0);
assert(c.min == 1);
assert(c.max == 4);
c = pre.results(1);
assert(c.level == 1);
assert(c.min == 5);
assert(c.max == 12);
c = pre.results(2);
assert(c.level == 2);
assert(c.min == 13);
assert(c.max == 28);
c = pre.results(3);
assert(c.level == -1); //0 not valid
//encode
BitArray ba;
//level 0
pre.value = 3;
bool[] answer = [0,1,0];
int len = pre.encode(ba);
assert(len == answer.length);
assert(ba == answer);
//level 1
ba.length = 0;
pre.value = 10;
answer = [1,0,1,0,1];
len = pre.encode(ba);
assert(len == answer.length);
assert(ba == answer);
//level 2
ba.length = 0;
pre.value = 28;
answer = [1,1,1,1,1,1];
len = pre.encode(ba);
assert(len == answer.length);
assert(ba == answer);
//decode
//level 0
answer = [0,1,0, 1,1,1]; //3 + added junk
ba = BitArray(answer);
len = pre.decode(ba);
assert(len == 3);
assert(pre.value == 3);
//level 1
answer = [1,0,1,0,1, 1,1,1]; //10 + junk
ba = BitArray(answer);
len = pre.decode(ba);
assert(len == 5);
assert(pre.value == 10);
//level 2
answer = [1,1,1,1,1,1, 1,1,1];//28 + junk
ba = BitArray(answer);
len = pre.decode(ba);
assert(len == 6);
assert(pre.value == 28);
//max bits
//max levels
assert(pre.maxBits == 6);
assert(pre.maxLevels == 3);
}
}
//lz77 implimentation. Not fully tested.
//for BitArray constants mostly
struct LZE {
/*
static immutable bool[][] def_levelCodes = [[0,0],[0,1],[1,1],[1,0,0],[1,0,1]];
static immutable int[] def_lenBits = [3,3,7,11,13];
static immutable int[] def_distBits = [5,8,13,17,20];
static immutable int[] def_rawBits = [2,4,6,8,10];
PrefixCodes dist = PrefixCodes(def_levelCodes, def_distBits, 1);
PrefixCodes len = PrefixCodes(def_levelCodes, def_lenBits, 4);
PrefixCodes raw = PrefixCodes(def_levelCodes, def_rawBits, 1);
*/
static immutable bool[][] def_levelCodes = [[0],[1,0],[1,1]];
static immutable int[] def_lenBits = [3,3,8];
static immutable int[] def_distBits = [5,8,8];
static immutable bool[][] def_rawLevelCodes = [[false],[true]];
static immutable int[] def_rawBits = [2,4];
PrefixCodes dist = PrefixCodes(def_levelCodes, def_distBits, 1);
PrefixCodes len = PrefixCodes(def_levelCodes, def_lenBits, 4);
PrefixCodes raw = PrefixCodes(def_rawLevelCodes, def_rawBits, 1);
enum windowMin = 1;
enum rawMin = 1;
//calculated via 'update' need to get real values for defaults.
int windowMax = 544;
int lengthMin = 4;
int lengthMax = 275;
int rawMax = 20;
int windowPos;
int length;
//a more accurate one since a fixed one will require 6 bytes when
//we know it can fit in as little as 2.
int getLengthMin(int dist_, int len_) const @safe pure {
auto distData = dist.resultsFrom(dist_);
auto lenData = len.resultsFrom(len_);
if ((distData.level == -1) || (lenData.level == -1))
return int.max; //can't satisfy...
//staircase... that was unintentional...
int bits = 1;
bits += len.prefix[distData.level].length;
bits += dist.prefix[distData.level].length;
bits += len.bitSizes[distData.level];
bits += dist.bitSizes[distData.level];
return ((bits + 7) / 8) + 1;
}
//update and adjust ints to more realistic values.
void update() pure @safe { //@safe pure {
int bits = 1; //1 for raw/LZ
PrefixCodes.Calc calc;
//distance/window
bits += dist.maxBits;
calc = dist.results(dist.maxLevels-1);
windowMax = calc.max;
//length, get minimum size needed.
bits += len.maxBits;
int l = ((bits + 7) / 8) + 1;
//update length min/max
len.rawMin = l; //calc.min is for that level, not lowest at level 0
calc = len.results(len.maxLevels-1);
lengthMin = l;
lengthMax = calc.max;
calc = raw.results(raw.maxLevels-1);
rawMax = calc.max;
}
//any illegal data is 'raw'.
bool isRaw() const @property {
return (windowPos < windowMin) || (windowPos > windowMax) ||
(length < lengthMin) || (length > lengthMax);
}
void clear() pure @safe { update(); windowPos = length = 0; }
}
unittest {
LZE lze;
lze.update();
writeln(lze);
}
/**Partial LZMA implimentation. See notes
full bit uses of length/window not possible currently
*/
void[] lzeCompress(const void[] rawInput, int rawStart = 0, SwiftSearch ss = null, LZE lz_data = LZE.init) {
BitArray ba_data;
debug {writeln("lzeCompress");}
ubyte[] input = cast(ubyte[]) rawInput;
ubyte[] window;
ba_data.reserve(input.length * 16);
if (!ss.length)
ss = swiftSearchScan(input, 2);
else
ss = ss.dup;
foreach(int position; rawStart .. input.length) {
if (position < rawStart)
continue;
lz_data = windowSearch(lz_data, ss, input, position, ss.length > 65536);
if (lz_data.isRaw)
continue;
bulkRawWrite(lz_data, ba_data, input[rawStart .. position]);
ba_data ~= true;
//save length
lz_data.len.value = lz_data.length;
lz_data.dist.value = lz_data.windowPos;
lz_data.len.encode(ba_data);
lz_data.dist.encode(ba_data);
debug {
writeln("LZE - len: ", lz_data.length, ", dist: ", lz_data.windowPos);
writeln(ba_data);
}
//save distance/window offset
rawStart = position + lz_data.length;
lz_data.clear();
}
//raw at the end to handle?
bulkRawWrite(lz_data, ba_data, input[rawStart .. $]);
void[] buff;
ba_data.getBuffer(buff);
return buff[0 .. ((cast(int) ba_data.length + 7) / 8)];
}
///Partial LZMA implimentation. See notes
void[] lzeDeCompress(const void[] input, LZE lz_data = LZE.init) {
ubyte[] buffer;
const BitArray ba = BitArray(cast(void[]) input);
int offset;
debug {writeln("lzeDeCompress");}
while((ba.length - offset) >= (lz_data.raw.minBits + 8)) {
if (!ba[offset]) {
offset++; //skip isRaw bit
offset += lz_data.raw.decode(ba[offset .. $]);
debug { writeln("LZE-Raw: ", lz_data.raw.value);
writeln(ba[offset .. $]);}
ubyte ub;
for(; lz_data.raw.value; lz_data.raw.value--) {
offset += ba.rawRead(ub, offset);
buffer ~= ub;
debug { writeln("Raw: ", ub);
writeln(ba[offset .. $]);}
}
} else {
offset++; //skip isRaw bit
offset += lz_data.len.decode(ba[offset .. $]);
offset += lz_data.dist.decode(ba[offset .. $]);
int length = lz_data.len.value;
int window = lz_data.dist.value;
debug {
writeln("LZE - len: ", length, ", dist: ", window);
writeln(ba[offset .. $]);
}
//overlapping copy, likely long string like "*****"
//can't have optimizations as they might not copy it right.screw it up.
if (window < length) {
buffer.length = buffer.length + length;
auto lhs = buffer[($-window-length) .. $];
auto rhs = buffer[$-length .. $];
foreach(i, ref b; rhs)
b = lhs[i];
} else
buffer ~= buffer[($-window) .. ($-window+length)];
}
}
return cast(void[]) buffer;
}
unittest {
writeln("LZe half");
string s = "Hello Hello";
//2 byte struct sequence
void[] x = lzeCompress(s);
writeln(x);
string y = cast(string) lzeDeCompress(x);
assert(y == s);
string dups = "--------";
auto x3 = lzeCompress(dups);
writeln(x3);
string y3 = cast(string) lzeDeCompress(x3);
writeln(y3);
writeln(dups);
assert(y3 == dups);
string dups2 = "abcabcabc";
auto x4 = lzeCompress(dups2);
writeln(x4);
string y4 = cast(string) lzeDeCompress(x4);
assert(y4 == dups2);
string longBuffer = dups ~ dups ~ dups ~ dups;
x3 = lzeCompress(longBuffer);
writeln(x3);
//broken only due to minimum size of 6 which is wrong,
//incomplete re-working in progress
y3 = cast(string) lzeDeCompress(x3);
assert(y3 == longBuffer);
}
//huffman starts here. unions/repacking may be done later.
struct Node {
Node[] nextLevel;
Tree decodeTree; //just the start of the tree.
BitArray[] bitCodes; //0 level only
bool singleElement;
uint singleElementValue;