Repository navigation
Expand file tree
/
Copy pathCompressRawZlib.java
More file actions
1940 lines (1705 loc) · 75.7 KB
/
Copy pathCompressRawZlib.java
File metadata and controls
1940 lines (1705 loc) · 75.7 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
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.*;
import org.perlonjava.runtime.operators.ReferenceOperators;
import org.perlonjava.runtime.runtimetypes.*;
import java.io.*;
import java.lang.invoke.MethodHandle;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.*;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarCache.scalarUndef;
/**
* Java XS backend for Compress::Raw::Zlib.
* Provides low-level zlib streaming compress/decompress API
* used by IO::Compress::Gzip, Mojo::Content, etc.
*/
public class CompressRawZlib extends PerlModuleBase {
// Zlib constants
private static final int Z_OK = 0;
private static final int Z_STREAM_END = 1;
private static final int Z_NEED_DICT = 2;
private static final int Z_ERRNO = -1;
private static final int Z_STREAM_ERROR = -2;
private static final int Z_DATA_ERROR = -3;
private static final int Z_MEM_ERROR = -4;
private static final int Z_BUF_ERROR = -5;
private static final int Z_VERSION_ERROR = -6;
private static final int Z_NO_FLUSH = 0;
private static final int Z_PARTIAL_FLUSH = 1;
private static final int Z_SYNC_FLUSH = 2;
private static final int Z_FULL_FLUSH = 3;
private static final int Z_FINISH = 4;
private static final int Z_BLOCK = 5;
private static final int Z_TREES = 6;
private static final int Z_DEFAULT_COMPRESSION = -1;
private static final int MAX_WBITS = 15;
private static final int MAX_MEM_LEVEL = 9;
// Flags
private static final int FLAG_APPEND = 1;
private static final int FLAG_CRC = 2;
private static final int FLAG_ADLER = 4;
private static final int FLAG_CONSUME_INPUT = 8;
private static final int FLAG_LIMIT_OUTPUT = 16;
// Constant map for the constant() function
private static final Map<String, Object> CONSTANTS = new HashMap<>();
static {
CONSTANTS.put("Z_OK", 0);
CONSTANTS.put("Z_STREAM_END", 1);
CONSTANTS.put("Z_NEED_DICT", 2);
CONSTANTS.put("Z_ERRNO", -1);
CONSTANTS.put("Z_STREAM_ERROR", -2);
CONSTANTS.put("Z_DATA_ERROR", -3);
CONSTANTS.put("Z_MEM_ERROR", -4);
CONSTANTS.put("Z_BUF_ERROR", -5);
CONSTANTS.put("Z_VERSION_ERROR", -6);
CONSTANTS.put("Z_NO_FLUSH", 0);
CONSTANTS.put("Z_PARTIAL_FLUSH", 1);
CONSTANTS.put("Z_SYNC_FLUSH", 2);
CONSTANTS.put("Z_FULL_FLUSH", 3);
CONSTANTS.put("Z_FINISH", 4);
CONSTANTS.put("Z_BLOCK", 5);
CONSTANTS.put("Z_TREES", 6);
CONSTANTS.put("Z_NO_COMPRESSION", 0);
CONSTANTS.put("Z_BEST_SPEED", 1);
CONSTANTS.put("Z_BEST_COMPRESSION", 9);
CONSTANTS.put("Z_DEFAULT_COMPRESSION", -1);
CONSTANTS.put("Z_FILTERED", 1);
CONSTANTS.put("Z_HUFFMAN_ONLY", 2);
CONSTANTS.put("Z_RLE", 3);
CONSTANTS.put("Z_FIXED", 4);
CONSTANTS.put("Z_DEFAULT_STRATEGY", 0);
CONSTANTS.put("Z_DEFLATED", 8);
CONSTANTS.put("Z_NULL", 0);
CONSTANTS.put("Z_ASCII", 1);
CONSTANTS.put("Z_BINARY", 0);
CONSTANTS.put("Z_UNKNOWN", 2);
CONSTANTS.put("MAX_WBITS", 15);
CONSTANTS.put("MAX_MEM_LEVEL", 9);
CONSTANTS.put("OS_CODE", 3); // Unix
CONSTANTS.put("DEF_WBITS", 15);
CONSTANTS.put("ZLIB_VERSION", "1.2.13");
CONSTANTS.put("ZLIB_VERNUM", 0x12D0);
// zlib-ng constants (we're not zlib-ng)
CONSTANTS.put("ZLIBNG_VERSION", "");
CONSTANTS.put("ZLIBNG_VERNUM", 0);
CONSTANTS.put("ZLIBNG_VER_MAJOR", 0);
CONSTANTS.put("ZLIBNG_VER_MINOR", 0);
CONSTANTS.put("ZLIBNG_VER_REVISION", 0);
CONSTANTS.put("ZLIBNG_VER_STATUS", 0);
CONSTANTS.put("ZLIBNG_VER_MODIFIED", 0);
}
// CRC32 lookup table for seeded CRC computation
private static final long[] CRC32_TABLE = new long[256];
static {
for (int i = 0; i < 256; i++) {
long c = i;
for (int j = 0; j < 8; j++) {
if ((c & 1) != 0) {
c = 0xEDB88320L ^ (c >>> 1);
} else {
c >>>= 1;
}
}
CRC32_TABLE[i] = c;
}
}
public CompressRawZlib() {
super("Compress::Raw::Zlib", false);
}
public static void initialize() {
CompressRawZlib crz = new CompressRawZlib();
try {
// Package-level functions
crz.registerMethod("constant", null);
crz.registerMethod("crc32", "crc32Func", null);
crz.registerMethod("adler32", "adler32Func", null);
crz.registerMethod("_deflateInit", "deflateInit", null);
crz.registerMethod("_inflateInit", "inflateInit", null);
crz.registerMethod("_inflateScanInit", "inflateScanInit", null);
crz.registerMethod("zlib_version", "zlibVersion", null);
crz.registerMethod("zlibCompileFlags", null);
crz.registerMethod("is_zlib_native", "isZlibNative", null);
crz.registerMethod("is_zlibng_native", "isZlibngNative", null);
crz.registerMethod("is_zlibng_compat", "isZlibngCompat", null);
crz.registerMethod("is_zlibng", "isZlibng", null);
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing Compress::Raw::Zlib method: " + e.getMessage());
}
// Register deflateStream methods
String[] deflateMethods = {
"deflate", "flush", "deflateReset", "_deflateParams", "deflateTune",
"crc32", "adler32", "total_in", "total_out", "msg",
"dict_adler", "get_Level", "get_Strategy", "get_Bufsize",
"compressedBytes", "uncompressedBytes", "DESTROY"
};
registerStreamMethods("Compress::Raw::Zlib::deflateStream", deflateMethods, "ds_");
// Register inflateStream methods
String[] inflateMethods = {
"inflate", "inflateReset", "inflateSync",
"crc32", "adler32", "total_in", "total_out", "msg",
"dict_adler", "get_Bufsize",
"compressedBytes", "uncompressedBytes", "DESTROY"
};
registerStreamMethods("Compress::Raw::Zlib::inflateStream", inflateMethods, "is_");
String[] inflateScanMethods = {
"scan", "inflate", "inflateReset", "inflateSync", "_createDeflateStream",
"createDeflateStream", "getLastBlockOffset", "getEndOffset", "resetLastBlockByte",
"crc32", "adler32", "total_in", "total_out", "msg",
"dict_adler", "get_Bufsize",
"compressedBytes", "uncompressedBytes", "DESTROY"
};
registerStreamMethods("Compress::Raw::Zlib::inflateScanStream", inflateScanMethods, "iss_");
// Set $Compress::Raw::Zlib::gzip_os_code
GlobalVariable.getGlobalVariable("Compress::Raw::Zlib::gzip_os_code")
.set(new RuntimeScalar(3)); // Unix
// Set $XS_VERSION for version check in CPAN .pm
GlobalVariable.getGlobalVariable("Compress::Raw::Zlib::XS_VERSION")
.set(new RuntimeScalar("2.224"));
}
/**
* Register static methods from this class into a different Perl package.
*/
private static void registerStreamMethods(String packageName, String[] methods, String javaPrefix) {
for (String method : methods) {
try {
String javaName = javaPrefix + method;
MethodHandle mh = RuntimeCode.lookup.findStatic(
CompressRawZlib.class, javaName, RuntimeCode.methodType);
RuntimeCode code = new RuntimeCode(mh, null, null);
code.isStatic = true;
code.packageName = packageName;
code.subName = method;
String fullName = NameNormalizer.normalizeVariableName(method, packageName);
GlobalVariable.getGlobalCodeRef(fullName).set(new RuntimeScalar(code));
} catch (Exception e) {
System.err.println("Warning: Missing " + packageName + "::" + method + ": " + e.getMessage());
}
}
}
// =============================================
// Package-level functions
// =============================================
/**
* constant($name) - returns ($error, $value) for AUTOLOAD
*/
public static RuntimeList constant(RuntimeArray args, int ctx) {
String name = args.size() > 0 ? args.get(0).toString() : "";
Object val = CONSTANTS.get(name);
RuntimeList result = new RuntimeList();
if (val != null) {
result.add(new RuntimeScalar("")); // no error
if (val instanceof String) {
result.add(new RuntimeScalar((String) val));
} else {
result.add(new RuntimeScalar(((Number) val).longValue()));
}
} else {
result.add(new RuntimeScalar("Unknown constant: " + name));
result.add(new RuntimeScalar(0));
}
return result;
}
public static RuntimeList zlibVersion(RuntimeArray args, int ctx) {
return new RuntimeScalar("1.2.13").getList();
}
public static RuntimeList zlibCompileFlags(RuntimeArray args, int ctx) {
return new RuntimeScalar(0).getList();
}
public static RuntimeList isZlibNative(RuntimeArray args, int ctx) {
return new RuntimeScalar(1).getList();
}
public static RuntimeList isZlibngNative(RuntimeArray args, int ctx) {
return new RuntimeScalar(0).getList();
}
public static RuntimeList isZlibngCompat(RuntimeArray args, int ctx) {
return new RuntimeScalar(0).getList();
}
public static RuntimeList isZlibng(RuntimeArray args, int ctx) {
return new RuntimeScalar(0).getList();
}
/**
* crc32($buffer [, $crc])
*/
public static RuntimeList crc32Func(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return new RuntimeScalar(0).getList();
}
byte[] input = getInputBytes(args.get(0));
long seed = 0;
if (args.size() > 1 && args.get(1).getDefinedBoolean()) {
seed = args.get(1).getLong() & 0xFFFFFFFFL;
}
long crc = crc32WithSeed(input, seed);
return new RuntimeScalar(crc).getList();
}
/**
* adler32($buffer [, $adler])
*/
public static RuntimeList adler32Func(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return new RuntimeScalar(1).getList();
}
byte[] input = getInputBytes(args.get(0));
long seed = 1;
if (args.size() > 1 && args.get(1).getDefinedBoolean()) {
seed = args.get(1).getLong() & 0xFFFFFFFFL;
}
long s1 = seed & 0xFFFF;
long s2 = (seed >>> 16) & 0xFFFF;
for (byte b : input) {
s1 = (s1 + (b & 0xFF)) % 65521;
s2 = (s2 + s1) % 65521;
}
return new RuntimeScalar((s2 << 16) | s1).getList();
}
// =============================================
// _deflateInit / _inflateInit
// =============================================
/**
* _deflateInit($flags, $level, $method, $windowBits, $memLevel, $strategy, $bufsize, $dictionary)
* Returns ($stream, $status)
*/
public static RuntimeList deflateInit(RuntimeArray args, int ctx) {
int flags = args.size() > 0 ? args.get(0).getInt() : 0;
int level = args.size() > 1 ? args.get(1).getInt() : Z_DEFAULT_COMPRESSION;
// int method = args.size() > 2 ? args.get(2).getInt() : 8; // always Z_DEFLATED
int wbits = args.size() > 3 ? args.get(3).getInt() : MAX_WBITS;
// int memLevel = args.size() > 4 ? args.get(4).getInt() : MAX_MEM_LEVEL;
int strategy = args.size() > 5 ? args.get(5).getInt() : 0;
int bufsize = args.size() > 6 ? args.get(6).getInt() : 4096;
byte[] dictBytes = args.size() > 7 ? getInputBytes(args.get(7)) : new byte[0];
try {
boolean nowrap;
boolean gzipMode = false;
int actualWbits;
if (wbits < 0) {
// Raw deflate (no header)
nowrap = true;
actualWbits = -wbits;
} else if (wbits > 15) {
// Gzip mode
nowrap = true; // Emit the RFC 1952 wrapper around raw deflate bytes.
gzipMode = true;
actualWbits = wbits - 16;
} else {
// Zlib format
nowrap = false;
actualWbits = wbits;
}
Deflater deflater = new Deflater(level, nowrap);
if (strategy == 1) deflater.setStrategy(Deflater.FILTERED);
else if (strategy == 2) deflater.setStrategy(Deflater.HUFFMAN_ONLY);
long dictAdler = 0;
if (dictBytes.length > 0) {
deflater.setDictionary(dictBytes);
dictAdler = adler32WithSeed(dictBytes, 1L);
}
// Create the stream object
RuntimeHash self = new RuntimeHash();
self.put("_deflater", new RuntimeScalar(deflater));
self.put("_flags", new RuntimeScalar(flags));
self.put("_level", new RuntimeScalar(level));
self.put("_strategy", new RuntimeScalar(strategy));
self.put("_bufsize", new RuntimeScalar(bufsize));
self.put("_total_in", new RuntimeScalar(0));
self.put("_total_out", new RuntimeScalar(0));
self.put("_crc32", new RuntimeScalar(0L));
self.put("_adler32", new RuntimeScalar(1L));
self.put("_dict_adler", new RuntimeScalar(dictAdler));
self.put("_msg", new RuntimeScalar());
self.put("_gzip_mode", new RuntimeScalar(gzipMode ? 1 : 0));
self.put("_gzip_header_emitted", new RuntimeScalar(0));
self.put("_gzip_crc32", new RuntimeScalar(0L));
RuntimeScalar ref = self.createReference();
ReferenceOperators.bless(ref, new RuntimeScalar("Compress::Raw::Zlib::deflateStream"));
// In scalar context, return only the object (CPAN code uses: $d ||= Deflate->new(...))
if (ctx == RuntimeContextType.SCALAR) {
RuntimeList result = new RuntimeList();
result.add(ref);
return result;
}
RuntimeList result = new RuntimeList();
result.add(ref);
result.add(new RuntimeScalar(Z_OK));
return result;
} catch (Exception e) {
// In scalar context, return undef on error
if (ctx == RuntimeContextType.SCALAR) {
RuntimeList result = new RuntimeList();
result.add(scalarUndef);
return result;
}
RuntimeList result = new RuntimeList();
result.add(scalarUndef);
result.add(new RuntimeScalar(Z_STREAM_ERROR));
return result;
}
}
/**
* _inflateInit($flags, $windowBits, $bufsize, $dictionary)
* Returns ($stream, $status)
*/
public static RuntimeList inflateInit(RuntimeArray args, int ctx) {
int flags = args.size() > 0 ? args.get(0).getInt() : 0;
int wbits = args.size() > 1 ? args.get(1).getInt() : MAX_WBITS;
int bufsize = args.size() > 2 ? args.get(2).getInt() : 4096;
byte[] dictBytes = args.size() > 3 ? getInputBytes(args.get(3)) : new byte[0];
String dict = new String(dictBytes, StandardCharsets.ISO_8859_1);
try {
boolean nowrap;
if (wbits < 0) {
nowrap = true;
} else if (wbits > 15) {
// WANT_GZIP or WANT_GZIP_OR_ZLIB - Java Inflater handles raw,
// gzip headers stripped by IO::Uncompress layer
nowrap = true;
} else {
nowrap = false;
}
Inflater inflater = new Inflater(nowrap);
RuntimeHash self = new RuntimeHash();
self.put("_inflater", new RuntimeScalar(inflater));
if (wbits > MAX_WBITS && wbits <= MAX_WBITS + 32) {
// zlib uses MAX_WBITS + 16 for gzip-only input and
// MAX_WBITS + 32 to auto-detect either gzip or zlib wrappers.
boolean autoDetectWrapper = wbits > MAX_WBITS + 16;
self.put("_gzip_inflater",
new RuntimeScalar(new GzipInflateState(inflater, autoDetectWrapper)));
}
self.put("_flags", new RuntimeScalar(flags));
self.put("_bufsize", new RuntimeScalar(bufsize));
self.put("_total_in", new RuntimeScalar(0));
self.put("_total_out", new RuntimeScalar(0));
self.put("_crc32", new RuntimeScalar(0L));
self.put("_adler32", new RuntimeScalar(1L));
self.put("_dict_adler", new RuntimeScalar(0));
RuntimeScalar dictionaryScalar = new RuntimeScalar(dict);
dictionaryScalar.type = RuntimeScalarType.BYTE_STRING;
self.put("_dictionary", dictionaryScalar);
self.put("_dictionary_used", new RuntimeScalar(0));
self.put("_msg", new RuntimeScalar());
RuntimeScalar ref = self.createReference();
ReferenceOperators.bless(ref, new RuntimeScalar("Compress::Raw::Zlib::inflateStream"));
// In scalar context, return only the object (CPAN code uses: $i ||= Inflate->new(...))
if (ctx == RuntimeContextType.SCALAR) {
RuntimeList result = new RuntimeList();
result.add(ref);
return result;
}
RuntimeList result = new RuntimeList();
result.add(ref);
result.add(new RuntimeScalar(Z_OK));
return result;
} catch (Exception e) {
// In scalar context, return undef on error
if (ctx == RuntimeContextType.SCALAR) {
RuntimeList result = new RuntimeList();
result.add(scalarUndef);
return result;
}
RuntimeList result = new RuntimeList();
result.add(scalarUndef);
result.add(new RuntimeScalar(Z_STREAM_ERROR));
return result;
}
}
public static RuntimeList inflateScanInit(RuntimeArray args, int ctx) {
RuntimeList result = inflateInit(args, ctx);
if (ctx == RuntimeContextType.SCALAR || result.isEmpty()) {
if (!result.isEmpty()) {
RuntimeScalar ref = result.elements.get(0).scalar();
if (ref.getDefinedBoolean()) {
ReferenceOperators.bless(ref, new RuntimeScalar("Compress::Raw::Zlib::inflateScanStream"));
initializeInflateScanState(ref.hashDeref());
}
}
return result;
}
RuntimeScalar ref = result.elements.get(0).scalar();
if (ref.getDefinedBoolean()) {
ReferenceOperators.bless(ref, new RuntimeScalar("Compress::Raw::Zlib::inflateScanStream"));
initializeInflateScanState(ref.hashDeref());
}
return result;
}
// =============================================
// deflateStream methods (ds_ prefix)
// =============================================
/**
* $d->deflate($input, $output)
* Compresses input and writes to output scalar.
* Returns status code.
*/
public static RuntimeList ds_deflate(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar inputScalar = args.size() > 1 ? args.get(1) : new RuntimeScalar("");
RuntimeScalar outputRef = args.size() > 2 ? args.get(2) : null;
Deflater deflater = getDeflater(self);
if (deflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
int flags = self.get("_flags").getInt();
byte[] input = getInputBytes(inputScalar);
if (self.get("_gzip_mode").getBoolean()) {
self.put("_gzip_crc32", new RuntimeScalar(crc32WithSeed(
input, self.get("_gzip_crc32").getLong() & 0xFFFFFFFFL)));
}
// Track CRC/Adler of uncompressed data
if ((flags & FLAG_CRC) != 0) {
long crc = crc32WithSeed(input, self.get("_crc32").getLong() & 0xFFFFFFFFL);
self.put("_crc32", new RuntimeScalar(crc));
}
if ((flags & FLAG_ADLER) != 0) {
long adler = adler32WithSeed(input, self.get("_adler32").getLong() & 0xFFFFFFFFL);
self.put("_adler32", new RuntimeScalar(adler));
}
deflater.setInput(input);
int bufsize = self.get("_bufsize").getInt();
byte[] buf = new byte[Math.max(bufsize, input.length + 256)];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int count;
while ((count = deflater.deflate(buf, 0, buf.length, Deflater.NO_FLUSH)) > 0) {
baos.write(buf, 0, count);
}
// Update totals
long totalIn = self.get("_total_in").getLong() + input.length;
long totalOut = self.get("_total_out").getLong() + baos.size();
self.put("_total_in", new RuntimeScalar(totalIn));
self.put("_total_out", new RuntimeScalar(totalOut));
self.put("_msg", new RuntimeScalar());
// Write output
if (outputRef != null) {
writeDeflateOutput(self, outputRef, baos, flags, false);
}
return new RuntimeScalar(Z_OK).getList();
}
/**
* $d->flush($output [, $flush_type])
*/
public static RuntimeList ds_flush(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar outputRef = args.size() > 1 ? args.get(1) : null;
int flushType = args.size() > 2 ? args.get(2).getInt() : Z_FINISH;
Deflater deflater = getDeflater(self);
if (deflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
if (flushType < Z_NO_FLUSH || flushType > Z_TREES) {
self.put("_msg", new RuntimeScalar("stream error"));
return new RuntimeScalar(Z_STREAM_ERROR).getList();
}
int flags = self.get("_flags").getInt();
if (flushType == Z_FINISH) {
deflater.finish();
}
int bufsize = self.get("_bufsize").getInt();
byte[] buf = new byte[Math.max(bufsize, 1024)];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int javaFlush = (flushType == Z_SYNC_FLUSH) ? Deflater.SYNC_FLUSH :
(flushType == Z_FULL_FLUSH) ? Deflater.FULL_FLUSH :
Deflater.NO_FLUSH;
if (flushType == Z_FINISH) {
javaFlush = Deflater.NO_FLUSH; // finish() already called
}
int count;
do {
if (flushType == Z_FINISH) {
count = deflater.deflate(buf);
} else {
count = deflater.deflate(buf, 0, buf.length, javaFlush);
}
if (count > 0) {
baos.write(buf, 0, count);
}
} while (count > 0);
long totalOut = self.get("_total_out").getLong() + baos.size();
self.put("_total_out", new RuntimeScalar(totalOut));
self.put("_msg", new RuntimeScalar());
if (outputRef != null) {
writeDeflateOutput(self, outputRef, baos, flags, flushType == Z_FINISH);
}
return new RuntimeScalar(Z_OK).getList();
}
public static RuntimeList ds_deflateReset(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
Deflater deflater = getDeflater(self);
if (deflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
deflater.reset();
self.put("_total_in", new RuntimeScalar(0));
self.put("_total_out", new RuntimeScalar(0));
self.put("_crc32", new RuntimeScalar(0L));
self.put("_adler32", new RuntimeScalar(1L));
self.put("_gzip_header_emitted", new RuntimeScalar(0));
self.put("_gzip_crc32", new RuntimeScalar(0L));
self.put("_msg", new RuntimeScalar());
return new RuntimeScalar(Z_OK).getList();
}
public static RuntimeList ds__deflateParams(RuntimeArray args, int ctx) {
// _deflateParams($flags, $level, $strategy, $bufsize)
RuntimeHash self = args.get(0).hashDeref();
Deflater deflater = getDeflater(self);
if (deflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
int flags = args.size() > 1 ? args.get(1).getInt() : 0;
if ((flags & 1) != 0 && args.size() > 2) {
int level = args.get(2).getInt();
deflater.setLevel(level);
self.put("_level", new RuntimeScalar(level));
}
if ((flags & 2) != 0 && args.size() > 3) {
int strategy = args.get(3).getInt();
if (strategy == 1) deflater.setStrategy(Deflater.FILTERED);
else if (strategy == 2) deflater.setStrategy(Deflater.HUFFMAN_ONLY);
else deflater.setStrategy(Deflater.DEFAULT_STRATEGY);
self.put("_strategy", new RuntimeScalar(strategy));
}
if ((flags & 4) != 0 && args.size() > 4) {
self.put("_bufsize", args.get(4));
}
return new RuntimeScalar(Z_OK).getList();
}
/**
* deflateTune($good_length, $max_lazy, $nice_length, $max_chain)
* Not supported by java.util.zip.Deflater -- stub returns Z_OK.
*/
public static RuntimeList ds_deflateTune(RuntimeArray args, int ctx) {
return new RuntimeScalar(Z_OK).getList();
}
public static RuntimeList ds_crc32(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_crc32").getLong()).getList();
}
public static RuntimeList ds_adler32(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_adler32").getLong()).getList();
}
public static RuntimeList ds_total_in(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_total_in").getLong()).getList();
}
public static RuntimeList ds_total_out(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_total_out").getLong()).getList();
}
public static RuntimeList ds_msg(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_msg").getList();
}
public static RuntimeList ds_dict_adler(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_dict_adler").getLong()).getList();
}
public static RuntimeList ds_get_Level(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_level").getList();
}
public static RuntimeList ds_get_Strategy(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_strategy").getList();
}
public static RuntimeList ds_get_Bufsize(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_bufsize").getList();
}
public static RuntimeList ds_compressedBytes(RuntimeArray args, int ctx) {
return ds_total_out(args, ctx);
}
public static RuntimeList ds_uncompressedBytes(RuntimeArray args, int ctx) {
return ds_total_in(args, ctx);
}
public static RuntimeList ds_DESTROY(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
Deflater deflater = getDeflater(self);
if (deflater != null) {
deflater.end();
}
return new RuntimeList();
}
// =============================================
// inflateStream methods (is_ prefix)
// =============================================
/**
* $i->inflate($input, $output [, $eof])
* Decompresses input, writes to output.
* Returns status code.
*/
public static RuntimeList is_inflate(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
RuntimeScalar inputRef = args.size() > 1 ? args.get(1) : new RuntimeScalar("");
RuntimeScalar outputRef = args.size() > 2 ? args.get(2) : null;
GzipInflateState gzipState = getGzipInflateState(self);
if (gzipState != null) {
return inflateGzip(self, gzipState, inputRef, outputRef);
}
Inflater inflater = getInflater(self);
if (inflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
int flags = self.get("_flags").getInt();
int bufsize = self.get("_bufsize").getInt();
// Get input data (dereference if needed)
RuntimeScalar actualInput = inputRef;
if (inputRef.type == RuntimeScalarType.REFERENCE) {
actualInput = inputRef.scalarDeref();
}
byte[] input = actualInput.toString().getBytes(StandardCharsets.ISO_8859_1);
int inputLenBefore = input.length;
inflater.setInput(input);
byte[] buf = new byte[Math.max(bufsize, 4096)];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int status = Z_OK;
try {
boolean limitOutput = (flags & FLAG_LIMIT_OUTPUT) != 0;
int totalInflated = 0;
while (!inflater.finished() && !inflater.needsInput()) {
int count = inflater.inflate(buf);
if (count > 0) {
baos.write(buf, 0, count);
totalInflated += count;
if (limitOutput && totalInflated >= bufsize) {
status = Z_BUF_ERROR;
break;
}
} else if (inflater.needsDictionary()) {
if (applyInflaterDictionary(self, inflater)) {
continue;
}
status = Z_NEED_DICT;
break;
} else {
break;
}
}
if (inflater.finished()) {
status = Z_STREAM_END;
}
if (status == Z_OK || status == Z_STREAM_END) {
self.put("_msg", new RuntimeScalar());
}
} catch (DataFormatException e) {
self.put("_msg", new RuntimeScalar(e.getMessage() != null ? e.getMessage() : "data error"));
return new RuntimeScalar(Z_DATA_ERROR).getList();
}
// Track how many input bytes were consumed
int remaining = inflater.getRemaining();
int consumed = inputLenBefore - remaining;
// Update totals
long totalIn = self.get("_total_in").getLong() + consumed;
long totalOut = self.get("_total_out").getLong() + baos.size();
self.put("_total_in", new RuntimeScalar(totalIn));
self.put("_total_out", new RuntimeScalar(totalOut));
// Track CRC/Adler of uncompressed output
byte[] outputBytes = baos.toByteArray();
if ((flags & FLAG_CRC) != 0) {
long crc = crc32WithSeed(outputBytes, self.get("_crc32").getLong() & 0xFFFFFFFFL);
self.put("_crc32", new RuntimeScalar(crc));
}
if ((flags & FLAG_ADLER) != 0) {
long adler = adler32WithSeed(outputBytes, self.get("_adler32").getLong() & 0xFFFFFFFFL);
self.put("_adler32", new RuntimeScalar(adler));
}
if (isInflateScanStream(self)) {
appendScanInput(self, input, consumed);
if (status == Z_STREAM_END) {
updateInflateScanState(self);
}
}
// FLAG_CONSUME_INPUT: modify input to remove consumed bytes
if ((flags & FLAG_CONSUME_INPUT) != 0) {
if (remaining > 0) {
String remainStr = new String(input, consumed, remaining, StandardCharsets.ISO_8859_1);
RuntimeScalar remainScalar = new RuntimeScalar(remainStr);
remainScalar.type = RuntimeScalarType.BYTE_STRING;
if (inputRef.type == RuntimeScalarType.REFERENCE) {
inputRef.scalarDeref().set(remainScalar);
} else {
inputRef.set(remainScalar);
}
} else {
RuntimeScalar empty = new RuntimeScalar("");
if (inputRef.type == RuntimeScalarType.REFERENCE) {
inputRef.scalarDeref().set(empty);
} else {
inputRef.set(empty);
}
}
}
// Write output
if (outputRef != null) {
writeOutput(outputRef, baos, flags);
}
return new RuntimeScalar(status).getList();
}
private static RuntimeList inflateGzip(RuntimeHash self, GzipInflateState gzipState,
RuntimeScalar inputRef, RuntimeScalar outputRef) {
int flags = self.get("_flags").getInt();
int bufsize = self.get("_bufsize").getInt();
RuntimeScalar actualInput = inputRef.type == RuntimeScalarType.REFERENCE
? inputRef.scalarDeref()
: inputRef;
byte[] input = actualInput.toString().getBytes(StandardCharsets.ISO_8859_1);
GzipInflateResult result = gzipState.inflate(input, bufsize,
(flags & FLAG_LIMIT_OUTPUT) != 0);
self.put("_msg", result.message == null ? new RuntimeScalar() : new RuntimeScalar(result.message));
long totalIn = self.get("_total_in").getLong() + result.consumed;
long totalOut = self.get("_total_out").getLong() + result.output.length;
self.put("_total_in", new RuntimeScalar(totalIn));
self.put("_total_out", new RuntimeScalar(totalOut));
if ((flags & FLAG_CRC) != 0) {
long crc = crc32WithSeed(result.output, self.get("_crc32").getLong() & 0xFFFFFFFFL);
self.put("_crc32", new RuntimeScalar(crc));
}
if ((flags & FLAG_ADLER) != 0) {
long adler = adler32WithSeed(result.output, self.get("_adler32").getLong() & 0xFFFFFFFFL);
self.put("_adler32", new RuntimeScalar(adler));
}
if ((flags & FLAG_CONSUME_INPUT) != 0) {
setScalarBytes(actualInput, new String(result.leftover, StandardCharsets.ISO_8859_1));
}
if (outputRef != null) {
ByteArrayOutputStream output = new ByteArrayOutputStream(result.output.length);
output.writeBytes(result.output);
writeOutput(outputRef, output, flags);
}
return new RuntimeScalar(result.status).getList();
}
public static RuntimeList is_inflateReset(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
GzipInflateState gzipState = getGzipInflateState(self);
if (gzipState != null) {
gzipState.reset();
}
Inflater inflater = getInflater(self);
if (inflater == null) return new RuntimeScalar(Z_STREAM_ERROR).getList();
inflater.reset();
self.put("_total_in", new RuntimeScalar(0));
self.put("_total_out", new RuntimeScalar(0));
self.put("_crc32", new RuntimeScalar(0L));
self.put("_adler32", new RuntimeScalar(1L));
self.put("_dict_adler", new RuntimeScalar(0));
self.put("_dictionary_used", new RuntimeScalar(0));
self.put("_msg", new RuntimeScalar());
return new RuntimeScalar(Z_OK).getList();
}
public static RuntimeList is_inflateSync(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
Inflater inflater = getInflater(self);
if (inflater == null || args.size() < 2) {
return new RuntimeScalar(Z_STREAM_ERROR).getList();
}
RuntimeScalar inputScalar = args.get(1);
RuntimeScalar actualInput = inputScalar.type == RuntimeScalarType.REFERENCE
? inputScalar.scalarDeref()
: inputScalar;
String previousTail = "";
RuntimeScalar tailScalar = self.get("_sync_tail");
if (tailScalar != null && tailScalar.getDefinedBoolean()) {
previousTail = tailScalar.toString();
}
String inputString = actualInput.toString();
byte[] combined = (previousTail + inputString).getBytes(StandardCharsets.ISO_8859_1);
int marker = findFullFlushMarker(combined);
if (marker < 0) {
int tailLength = Math.min(3, combined.length);
String tail = new String(combined, combined.length - tailLength, tailLength, StandardCharsets.ISO_8859_1);
self.put("_sync_tail", new RuntimeScalar(tail));
setScalarBytes(actualInput, "");
return new RuntimeScalar(Z_DATA_ERROR).getList();
}
int afterMarker = marker + 4;
String remaining = new String(combined, afterMarker, combined.length - afterMarker, StandardCharsets.ISO_8859_1);
self.put("_sync_tail", new RuntimeScalar(""));
self.put("_inflater", new RuntimeScalar(new Inflater(true)));
setScalarBytes(actualInput, remaining);
return new RuntimeScalar(Z_OK).getList();
}
public static RuntimeList is_crc32(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_crc32").getLong()).getList();
}
public static RuntimeList is_adler32(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_adler32").getLong()).getList();
}
public static RuntimeList is_total_in(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_total_in").getLong()).getList();
}
public static RuntimeList is_total_out(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_total_out").getLong()).getList();
}
public static RuntimeList is_msg(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_msg").getList();
}
public static RuntimeList is_dict_adler(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return new RuntimeScalar(self.get("_dict_adler").getLong()).getList();
}
public static RuntimeList is_get_Bufsize(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
return self.get("_bufsize").getList();
}
public static RuntimeList is_compressedBytes(RuntimeArray args, int ctx) {
return is_total_in(args, ctx);
}
public static RuntimeList is_uncompressedBytes(RuntimeArray args, int ctx) {
return is_total_out(args, ctx);
}
public static RuntimeList is_DESTROY(RuntimeArray args, int ctx) {
RuntimeHash self = args.get(0).hashDeref();
Inflater inflater = getInflater(self);
if (inflater != null) {
inflater.end();
}
return new RuntimeList();
}
public static RuntimeList iss_scan(RuntimeArray args, int ctx) {
return is_inflate(args, ctx);
}
public static RuntimeList iss_inflate(RuntimeArray args, int ctx) {
return is_inflate(args, ctx);
}
public static RuntimeList iss_inflateReset(RuntimeArray args, int ctx) {
return is_inflateReset(args, ctx);
}
public static RuntimeList iss_inflateSync(RuntimeArray args, int ctx) {
return is_inflateSync(args, ctx);
}
public static RuntimeList iss__createDeflateStream(RuntimeArray args, int ctx) {
return createDeflateStreamFromScan(args, sliceArgs(args, 1), ctx);
}
public static RuntimeList iss_createDeflateStream(RuntimeArray args, int ctx) {
return createDeflateStreamFromScan(args, deflateInitArgsFromScanCreate(args), ctx);
}