-
Notifications
You must be signed in to change notification settings - Fork 595
/
compression.scala
1205 lines (1127 loc) · 43.8 KB
/
compression.scala
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
/*
* Copyright (c) 2013 Functional Streams for Scala
*
* 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.
*/
package fs2
import java.io.EOFException
import java.nio.charset.StandardCharsets
import java.time.Instant
import java.util.zip._
import cats.effect.kernel.Sync
/** Provides utilities for compressing/decompressing byte streams. */
object compression {
object ZLibParams {
sealed abstract class Header(private[compression] val juzDeflaterNoWrap: Boolean)
case object Header {
private[fs2] def apply(juzDeflaterNoWrap: Boolean): ZLibParams.Header =
if (juzDeflaterNoWrap) ZLibParams.Header.GZIP else ZLibParams.Header.ZLIB
case object ZLIB extends Header(juzDeflaterNoWrap = false)
case object GZIP extends Header(juzDeflaterNoWrap = true)
}
}
/** Deflate algorithm parameters.
*/
sealed trait DeflateParams {
/** Size of the internal buffer. Default size is 32 KB.
*/
val bufferSize: Int
/** Compression header. Defaults to [[ZLibParams.Header.ZLIB]].
*/
val header: ZLibParams.Header
/** Compression level. Default level is [[java.util.zip.Deflater.DEFAULT_COMPRESSION]].
*/
val level: DeflateParams.Level
/** Compression strategy. Default strategy is [[java.util.zip.Deflater.DEFAULT_STRATEGY]].
*/
val strategy: DeflateParams.Strategy
/** Compression flush mode. Default flush mode is [[java.util.zip.Deflater.NO_FLUSH]].
*/
val flushMode: DeflateParams.FlushMode
private[compression] val bufferSizeOrMinimum: Int = bufferSize.max(128)
}
object DeflateParams {
def apply(
bufferSize: Int = 1024 * 32,
header: ZLibParams.Header = ZLibParams.Header.ZLIB,
level: DeflateParams.Level = DeflateParams.Level.DEFAULT,
strategy: DeflateParams.Strategy = DeflateParams.Strategy.DEFAULT,
flushMode: DeflateParams.FlushMode = DeflateParams.FlushMode.DEFAULT
): DeflateParams =
DeflateParamsImpl(bufferSize, header, level, strategy, flushMode)
private case class DeflateParamsImpl(
bufferSize: Int,
header: ZLibParams.Header,
level: DeflateParams.Level,
strategy: DeflateParams.Strategy,
flushMode: DeflateParams.FlushMode
) extends DeflateParams
sealed abstract class Level(private[compression] val juzDeflaterLevel: Int)
case object Level {
private[fs2] def apply(level: Int): Level =
level match {
case DEFAULT.juzDeflaterLevel => Level.DEFAULT
case ZERO.juzDeflaterLevel => Level.ZERO
case ONE.juzDeflaterLevel => Level.ONE
case TWO.juzDeflaterLevel => Level.TWO
case THREE.juzDeflaterLevel => Level.THREE
case FOUR.juzDeflaterLevel => Level.FOUR
case FIVE.juzDeflaterLevel => Level.FIVE
case SIX.juzDeflaterLevel => Level.SIX
case SEVEN.juzDeflaterLevel => Level.SEVEN
case EIGHT.juzDeflaterLevel => Level.EIGHT
case NINE.juzDeflaterLevel => Level.NINE
}
case object DEFAULT extends Level(juzDeflaterLevel = Deflater.DEFAULT_COMPRESSION)
case object BEST_SPEED extends Level(juzDeflaterLevel = Deflater.BEST_SPEED)
case object BEST_COMPRESSION extends Level(juzDeflaterLevel = Deflater.BEST_COMPRESSION)
case object NO_COMPRESSION extends Level(juzDeflaterLevel = Deflater.NO_COMPRESSION)
case object ZERO extends Level(juzDeflaterLevel = 0)
case object ONE extends Level(juzDeflaterLevel = 1)
case object TWO extends Level(juzDeflaterLevel = 2)
case object THREE extends Level(juzDeflaterLevel = 3)
case object FOUR extends Level(juzDeflaterLevel = 4)
case object FIVE extends Level(juzDeflaterLevel = 5)
case object SIX extends Level(juzDeflaterLevel = 6)
case object SEVEN extends Level(juzDeflaterLevel = 7)
case object EIGHT extends Level(juzDeflaterLevel = 8)
case object NINE extends Level(juzDeflaterLevel = 9)
}
sealed abstract class Strategy(private[compression] val juzDeflaterStrategy: Int)
case object Strategy {
private[fs2] def apply(strategy: Int): Strategy =
strategy match {
case DEFAULT.juzDeflaterStrategy => Strategy.DEFAULT
case FILTERED.juzDeflaterStrategy => Strategy.FILTERED
case HUFFMAN_ONLY.juzDeflaterStrategy => Strategy.HUFFMAN_ONLY
}
case object DEFAULT extends Strategy(juzDeflaterStrategy = Deflater.DEFAULT_STRATEGY)
case object BEST_SPEED extends Strategy(juzDeflaterStrategy = Deflater.HUFFMAN_ONLY)
case object BEST_COMPRESSION extends Strategy(juzDeflaterStrategy = Deflater.DEFAULT_STRATEGY)
case object FILTERED extends Strategy(juzDeflaterStrategy = Deflater.FILTERED)
case object HUFFMAN_ONLY extends Strategy(juzDeflaterStrategy = Deflater.HUFFMAN_ONLY)
}
sealed abstract class FlushMode(private[compression] val juzDeflaterFlushMode: Int)
case object FlushMode {
private[fs2] def apply(flushMode: Int): FlushMode =
flushMode match {
case DEFAULT.juzDeflaterFlushMode => FlushMode.NO_FLUSH
case SYNC_FLUSH.juzDeflaterFlushMode => FlushMode.SYNC_FLUSH
case FULL_FLUSH.juzDeflaterFlushMode => FlushMode.FULL_FLUSH
}
case object DEFAULT extends FlushMode(juzDeflaterFlushMode = Deflater.NO_FLUSH)
case object BEST_SPEED extends FlushMode(juzDeflaterFlushMode = Deflater.FULL_FLUSH)
case object BEST_COMPRESSION extends FlushMode(juzDeflaterFlushMode = Deflater.NO_FLUSH)
case object NO_FLUSH extends FlushMode(juzDeflaterFlushMode = Deflater.NO_FLUSH)
case object SYNC_FLUSH extends FlushMode(juzDeflaterFlushMode = Deflater.SYNC_FLUSH)
case object FULL_FLUSH extends FlushMode(juzDeflaterFlushMode = Deflater.FULL_FLUSH)
}
/** Reasonable defaults for most applications.
*/
val DEFAULT: DeflateParams = DeflateParams()
/** Best speed for real-time, intermittent, fragmented, interactive or discontinuous streams.
*/
val BEST_SPEED: DeflateParams = DeflateParams(
level = Level.BEST_SPEED,
strategy = Strategy.BEST_SPEED,
flushMode = FlushMode.BEST_SPEED
)
/** Best compression for finite, complete, readily-available, continuous or file streams.
*/
val BEST_COMPRESSION: DeflateParams = DeflateParams(
bufferSize = 1024 * 128,
level = Level.BEST_COMPRESSION,
strategy = Strategy.BEST_COMPRESSION,
flushMode = FlushMode.BEST_COMPRESSION
)
}
/** Returns a `Pipe` that deflates (compresses) its input elements using
* the the Deflate algorithm.
*
* @param deflateParams See [[compression.DeflateParams]]
*/
def deflate[F[_]](
deflateParams: DeflateParams
)(implicit SyncF: Sync[F]): Pipe[F, Byte, Byte] =
stream =>
Stream
.bracket(
SyncF.delay {
val deflater =
new Deflater(
deflateParams.level.juzDeflaterLevel,
deflateParams.header.juzDeflaterNoWrap
)
deflater.setStrategy(deflateParams.strategy.juzDeflaterStrategy)
deflater
}
)(deflater => SyncF.delay(deflater.end()))
.flatMap(deflater => _deflate(deflateParams, deflater, crc32 = None)(stream))
private def _deflate[F[_]](
deflateParams: DeflateParams,
deflater: Deflater,
crc32: Option[CRC32]
): Pipe[F, Byte, Byte] =
in =>
Stream.suspend {
val deflatedBuffer = new Array[Byte](deflateParams.bufferSizeOrMinimum)
_deflate_stream(deflateParams, deflater, crc32, deflatedBuffer)(in).stream
}
private def _deflate_chunk[F[_]](
deflateParams: DeflateParams,
deflater: Deflater,
crc32: Option[CRC32],
chunk: Chunk[Byte],
deflatedBuffer: Array[Byte],
isFinalChunk: Boolean
): Pull[F, Byte, Unit] = {
val bytesChunk = chunk.toBytes
deflater.setInput(
bytesChunk.values,
bytesChunk.offset,
bytesChunk.length
)
if (isFinalChunk)
deflater.finish()
crc32.foreach(_.update(bytesChunk.values, bytesChunk.offset, bytesChunk.length))
def isDone: Boolean =
(isFinalChunk && deflater.finished) || (!isFinalChunk && deflater.needsInput)
def runDeflate(): Int =
if (isDone) 0
else
deflater.deflate(
deflatedBuffer,
0,
deflateParams.bufferSizeOrMinimum,
deflateParams.flushMode.juzDeflaterFlushMode
)
def pull(): Pull[F, Byte, Unit] = {
val deflatedBytes = runDeflate()
if (isDone)
Pull.output(copyAsChunkBytes(deflatedBuffer, deflatedBytes))
else
Pull.output(copyAsChunkBytes(deflatedBuffer, deflatedBytes)) >> pull()
}
pull()
}
private def _deflate_stream[F[_]](
deflateParams: DeflateParams,
deflater: Deflater,
crc32: Option[CRC32],
deflatedBuffer: Array[Byte]
): Stream[F, Byte] => Pull[F, Byte, Unit] =
_.pull.unconsNonEmpty.flatMap {
case Some((inflatedChunk, inflatedStream)) =>
_deflate_chunk(
deflateParams,
deflater,
crc32,
inflatedChunk,
deflatedBuffer,
isFinalChunk = false
) >>
_deflate_stream(deflateParams, deflater, crc32, deflatedBuffer)(inflatedStream)
case None =>
_deflate_chunk(
deflateParams,
deflater,
crc32,
Chunk.empty[Byte],
deflatedBuffer,
isFinalChunk = true
)
}
/** Inflate algorithm parameters.
*/
sealed trait InflateParams {
/** Size of the internal buffer. Default size is 32 KB.
*/
val bufferSize: Int
/** Compression header. Defaults to [[ZLibParams.Header.ZLIB]]
*/
val header: ZLibParams.Header
private[compression] val bufferSizeOrMinimum: Int = bufferSize.max(128)
}
object InflateParams {
def apply(
bufferSize: Int = 1024 * 32,
header: ZLibParams.Header = ZLibParams.Header.ZLIB
): InflateParams =
InflateParamsImpl(bufferSize, header)
/** Reasonable defaults for most applications.
*/
val DEFAULT: InflateParams = InflateParams()
private case class InflateParamsImpl(
bufferSize: Int,
header: ZLibParams.Header
) extends InflateParams
}
/** Returns a `Pipe` that inflates (decompresses) its input elements using
* a `java.util.zip.Inflater` with the parameter `nowrap`.
* @param inflateParams See [[compression.InflateParams]]
*/
def inflate[F[_]](
inflateParams: InflateParams
)(implicit SyncF: Sync[F]): Pipe[F, Byte, Byte] =
stream =>
Stream
.bracket(SyncF.delay(new Inflater(inflateParams.header.juzDeflaterNoWrap)))(inflater =>
SyncF.delay(inflater.end())
)
.flatMap(inflater => _inflate(inflateParams, inflater, crc32 = None)(SyncF)(stream))
private def _inflate[F[_]](
inflateParams: InflateParams,
inflater: Inflater,
crc32: Option[CRC32]
)(implicit
SyncF: Sync[F]
): Pipe[F, Byte, Byte] =
in =>
Stream.suspend {
val inflatedBuffer = new Array[Byte](inflateParams.bufferSizeOrMinimum)
in.pull.unconsNonEmpty.flatMap {
case Some((deflatedChunk, deflatedStream)) =>
_inflate_chunk(
inflater,
crc32,
deflatedChunk,
inflatedBuffer
) >> _inflate_stream(
inflateParams,
inflater,
crc32,
inflatedBuffer
)(SyncF)(deflatedStream)
case None =>
Pull.done
}.stream
}
private def _inflate_chunk[F[_]](
inflater: Inflater,
crc32: Option[CRC32],
chunk: Chunk[Byte],
inflatedBuffer: Array[Byte]
): Pull[F, Byte, Unit] = {
val bytesChunk = chunk.toBytes
inflater.setInput(
bytesChunk.values,
bytesChunk.offset,
bytesChunk.length
)
def runInflate(): Int =
if (inflater.finished()) -2
else if (inflater.needsInput()) -1
else {
val byteCount = inflater.inflate(inflatedBuffer)
crc32.foreach(_.update(inflatedBuffer, 0, byteCount))
byteCount
}
def pull(): Pull[F, Byte, Unit] =
runInflate() match {
case inflatedBytes if inflatedBytes <= -2 =>
inflater.getRemaining match {
case bytesRemaining if bytesRemaining > 0 =>
Pull.output(
Chunk.Bytes(
bytesChunk.values,
bytesChunk.offset + bytesChunk.length - bytesRemaining,
bytesRemaining
)
)
case _ =>
Pull.done
}
case inflatedBytes if inflatedBytes == -1 =>
Pull.done
case inflatedBytes if inflatedBytes < inflatedBuffer.length =>
if (inflater.finished())
inflater.getRemaining match {
case bytesRemaining if bytesRemaining > 0 =>
Pull.output(copyAsChunkBytes(inflatedBuffer, inflatedBytes)) >>
Pull.output(
Chunk.Bytes(
bytesChunk.values,
bytesChunk.offset + bytesChunk.length - bytesRemaining,
bytesRemaining
)
)
case _ =>
Pull.output(copyAsChunkBytes(inflatedBuffer, inflatedBytes))
}
else Pull.output(copyAsChunkBytes(inflatedBuffer, inflatedBytes))
case inflatedBytes =>
Pull.output(copyAsChunkBytes(inflatedBuffer, inflatedBytes)) >> pull()
}
pull()
}
private def _inflate_stream[F[_]](
inflateParams: InflateParams,
inflater: Inflater,
crc32: Option[CRC32],
inflatedBuffer: Array[Byte]
)(implicit SyncF: Sync[F]): Stream[F, Byte] => Pull[F, Byte, Unit] =
_.pull.unconsNonEmpty.flatMap {
case Some((deflatedChunk, deflatedStream)) =>
_inflate_chunk(
inflater,
crc32,
deflatedChunk,
inflatedBuffer
) >> _inflate_stream(
inflateParams,
inflater,
crc32,
inflatedBuffer
)(SyncF)(deflatedStream)
case None =>
if (!inflater.finished)
Pull.raiseError[F](new DataFormatException("Insufficient data"))
else
Pull.done
}
/** Returns a pipe that incrementally compresses input into the GZIP format
* as defined by RFC 1952 at https://www.ietf.org/rfc/rfc1952.txt. Output is
* compatible with the GNU utils `gunzip` utility, as well as really anything
* else that understands GZIP. Note, however, that the GZIP format is not
* "stable" in the sense that all compressors will produce identical output
* given identical input. Part of the header seeding is arbitrary and chosen by
* the compression implementation. For this reason, the exact bytes produced
* by this pipe will differ in insignificant ways from the exact bytes produced
* by a tool like the GNU utils `gzip`.
*
* GZIP wraps a deflate stream with file attributes and stream integrity validation.
* Therefore, GZIP is a good choice for compressing finite, complete, readily-available,
* continuous or file streams. A simpler deflate stream may be better suited to
* real-time, intermittent, fragmented, interactive or discontinuous streams where
* network protocols typically provide stream integrity validation.
*
* @param bufferSize The buffer size which will be used to page data
* into chunks. This will be the chunk size of the
* output stream. You should set it to be equal to
* the size of the largest chunk in the input stream.
* Setting this to a size which is ''smaller'' than
* the chunks in the input stream will result in
* performance degradation of roughly 50-75%. Default
* size is 32 KB.
* @param deflateLevel level the compression level (0-9)
* @param deflateStrategy strategy compression strategy -- see `java.util.zip.Deflater` for details
* @param modificationTime optional file modification time
* @param fileName optional file name
* @param comment optional file comment
*/
def gzip[F[_]](
bufferSize: Int = 1024 * 32,
deflateLevel: Option[Int] = None,
deflateStrategy: Option[Int] = None,
modificationTime: Option[Instant] = None,
fileName: Option[String] = None,
comment: Option[String] = None
)(implicit SyncF: Sync[F]): Pipe[F, Byte, Byte] =
gzip[F](
fileName = fileName,
modificationTime = modificationTime,
comment = comment,
deflateParams = DeflateParams(
bufferSize = bufferSize,
header = ZLibParams.Header.GZIP,
level = deflateLevel
.map(DeflateParams.Level.apply)
.getOrElse(DeflateParams.Level.DEFAULT),
strategy = deflateStrategy
.map(DeflateParams.Strategy.apply)
.getOrElse(DeflateParams.Strategy.DEFAULT),
flushMode = DeflateParams.FlushMode.DEFAULT
)
)
/** Returns a pipe that incrementally compresses input into the GZIP format
* as defined by RFC 1952 at https://www.ietf.org/rfc/rfc1952.txt. Output is
* compatible with the GNU utils `gunzip` utility, as well as really anything
* else that understands GZIP. Note, however, that the GZIP format is not
* "stable" in the sense that all compressors will produce identical output
* given identical input. Part of the header seeding is arbitrary and chosen by
* the compression implementation. For this reason, the exact bytes produced
* by this pipe will differ in insignificant ways from the exact bytes produced
* by a tool like the GNU utils `gzip`.
*
* GZIP wraps a deflate stream with file attributes and stream integrity validation.
* Therefore, GZIP is a good choice for compressing finite, complete, readily-available,
* continuous or file streams. A simpler deflate stream may be better suited to
* real-time, intermittent, fragmented, interactive or discontinuous streams where
* network protocols typically provide stream integrity validation.
*
* @param fileName optional file name
* @param modificationTime optional file modification time
* @param comment optional file comment
* @param deflateParams see [[compression.DeflateParams]]
*/
def gzip[F[_]](
fileName: Option[String],
modificationTime: Option[Instant],
comment: Option[String],
deflateParams: DeflateParams
)(implicit SyncF: Sync[F]): Pipe[F, Byte, Byte] =
stream =>
deflateParams match {
case params: DeflateParams if params.header == ZLibParams.Header.GZIP =>
Stream
.bracket(
SyncF.delay {
val deflater = new Deflater(params.level.juzDeflaterLevel, true)
deflater.setStrategy(params.strategy.juzDeflaterStrategy)
(deflater, new CRC32())
}
) { case (deflater, _) => SyncF.delay(deflater.end()) }
.flatMap { case (deflater, crc32) =>
_gzip_header(fileName, modificationTime, comment, params.level.juzDeflaterLevel) ++
_deflate(
params,
deflater,
Some(crc32)
)(stream) ++
_gzip_trailer(deflater, crc32)
}
case params: DeflateParams =>
Stream.raiseError(
new ZipException(
s"${ZLibParams.Header.GZIP} header type required, not ${params.header}."
)
)
}
private def _gzip_header[F[_]](
fileName: Option[String],
modificationTime: Option[Instant],
comment: Option[String],
deflateLevel: Int
): Stream[F, Byte] = {
// See RFC 1952: https://www.ietf.org/rfc/rfc1952.txt
val secondsSince197001010000: Long =
modificationTime.map(_.getEpochSecond).getOrElse(0)
val header = Array[Byte](
gzipMagicFirstByte, // ID1: Identification 1
gzipMagicSecondByte, // ID2: Identification 2
gzipCompressionMethod.DEFLATE, // CM: Compression Method
(gzipFlag.FHCRC + // FLG: Header CRC
fileName.map(_ => gzipFlag.FNAME).getOrElse(zeroByte) + // FLG: File name
comment.map(_ => gzipFlag.FCOMMENT).getOrElse(zeroByte)).toByte, // FLG: Comment
(secondsSince197001010000 & 0xff).toByte, // MTIME: Modification Time
((secondsSince197001010000 >> 8) & 0xff).toByte,
((secondsSince197001010000 >> 16) & 0xff).toByte,
((secondsSince197001010000 >> 24) & 0xff).toByte,
deflateLevel match { // XFL: Extra flags
case Deflater.BEST_COMPRESSION => gzipExtraFlag.DEFLATE_MAX_COMPRESSION_SLOWEST_ALGO
case Deflater.BEST_SPEED => gzipExtraFlag.DEFLATE_FASTEST_ALGO
case _ => zeroByte
},
gzipOperatingSystem.THIS
) // OS: Operating System
val crc32 = new CRC32()
crc32.update(header)
val fileNameEncoded = fileName.map { string =>
val bytes = string.replaceAll("\u0000", "_").getBytes(StandardCharsets.ISO_8859_1)
crc32.update(bytes)
crc32.update(zeroByte.toInt)
bytes
}
val commentEncoded = comment.map { string =>
val bytes = string.replaceAll("\u0000", " ").getBytes(StandardCharsets.ISO_8859_1)
crc32.update(bytes)
crc32.update(zeroByte.toInt)
bytes
}
val crc32Value = crc32.getValue
val crc16 = Array[Byte](
(crc32Value & 0xff).toByte,
((crc32Value >> 8) & 0xff).toByte
)
Stream.chunk(moveAsChunkBytes(header)) ++
fileNameEncoded
.map(bytes => Stream.chunk(moveAsChunkBytes(bytes)) ++ Stream.emit(zeroByte))
.getOrElse(Stream.empty) ++
commentEncoded
.map(bytes => Stream.chunk(moveAsChunkBytes(bytes)) ++ Stream.emit(zeroByte))
.getOrElse(Stream.empty) ++
Stream.chunk(moveAsChunkBytes(crc16))
}
private def _gzip_trailer[F[_]](deflater: Deflater, crc32: CRC32): Stream[F, Byte] = {
// See RFC 1952: https://www.ietf.org/rfc/rfc1952.txt
val crc32Value = crc32.getValue
val bytesIn = deflater.getTotalIn
val trailer = Array[Byte](
(crc32Value & 0xff).toByte, // CRC-32: Cyclic Redundancy Check
((crc32Value >> 8) & 0xff).toByte,
((crc32Value >> 16) & 0xff).toByte,
((crc32Value >> 24) & 0xff).toByte,
(bytesIn & 0xff).toByte, // ISIZE: Input size
((bytesIn >> 8) & 0xff).toByte,
((bytesIn >> 16) & 0xff).toByte,
((bytesIn >> 24) & 0xff).toByte
)
Stream.chunk(moveAsChunkBytes(trailer))
}
/** Gunzip decompression results including file properties and
* decompressed content stream, used as follows:
* stream
* .through(gunzip[IO]())
* .flatMap { gunzipResult =>
* // Access properties here.
* gunzipResult.content
* }
*
* @param content Uncompressed content stream.
* @param modificationTime Modification time of compressed file.
* @param fileName File name.
* @param comment File comment.
*/
final case class GunzipResult[F[_]](
content: Stream[F, Byte],
modificationTime: Option[Instant] = None,
fileName: Option[String] = None,
comment: Option[String] = None
)
/** Returns a pipe that incrementally decompresses input according to the GZIP
* format as defined by RFC 1952 at https://www.ietf.org/rfc/rfc1952.txt. Any
* errors in decompression will be sequenced as exceptions into the output
* stream. Decompression is handled in a streaming and async fashion without
* any thread blockage.
*
* The chunk size here is actually really important. Matching the input stream
* largest chunk size, or roughly 8 KB (whichever is larger) is a good rule of
* thumb.
*
* @param bufferSize The bounding size of the input buffer. This should roughly
* match the size of the largest chunk in the input stream.
* This will also be the chunk size in the output stream.
* Default size is 32 KB.
* @return See [[compression.GunzipResult]]
*/
def gunzip[F[_]](
bufferSize: Int = 1024 * 32
)(implicit SyncF: Sync[F]): Stream[F, Byte] => Stream[F, GunzipResult[F]] =
gunzip(
InflateParams(
bufferSize = bufferSize,
header = ZLibParams.Header.GZIP
)
)
/** Returns a pipe that incrementally decompresses input according to the GZIP
* format as defined by RFC 1952 at https://www.ietf.org/rfc/rfc1952.txt. Any
* errors in decompression will be sequenced as exceptions into the output
* stream. Decompression is handled in a streaming and async fashion without
* any thread blockage.
*
* The chunk size here is actually really important. Matching the input stream
* largest chunk size, or roughly 8 KB (whichever is larger) is a good rule of
* thumb.
*
* @param inflateParams See [[compression.InflateParams]]
* @return See [[compression.GunzipResult]]
*/
def gunzip[F[_]](
inflateParams: InflateParams
)(implicit SyncF: Sync[F]): Stream[F, Byte] => Stream[F, GunzipResult[F]] =
stream =>
inflateParams match {
case params: InflateParams if params.header == ZLibParams.Header.GZIP =>
Stream
.bracket(SyncF.delay((new Inflater(true), new CRC32(), new CRC32()))) {
case (inflater, _, _) => SyncF.delay(inflater.end())
}
.flatMap { case (inflater, headerCrc32, contentCrc32) =>
stream.pull
.unconsN(gzipHeaderBytes)
.flatMap {
case Some((mandatoryHeaderChunk, streamAfterMandatoryHeader)) =>
_gunzip_matchMandatoryHeader(
params,
mandatoryHeaderChunk,
streamAfterMandatoryHeader,
headerCrc32,
contentCrc32,
inflater
)
case None =>
Pull.output1(GunzipResult(Stream.raiseError(new EOFException())))
}
.stream
}
case params: InflateParams =>
Stream.raiseError(
new ZipException(
s"${ZLibParams.Header.GZIP} header type required, not ${params.header}."
)
)
}
private def _gunzip_matchMandatoryHeader[F[_]](
inflateParams: InflateParams,
mandatoryHeaderChunk: Chunk[Byte],
streamAfterMandatoryHeader: Stream[F, Byte],
headerCrc32: CRC32,
contentCrc32: CRC32,
inflater: Inflater
)(implicit SyncF: Sync[F]) =
(mandatoryHeaderChunk.size, mandatoryHeaderChunk.toBytes.values) match {
case (
`gzipHeaderBytes`,
Array(
`gzipMagicFirstByte`,
`gzipMagicSecondByte`,
gzipCompressionMethod.DEFLATE,
flags,
_,
_,
_,
_,
_
)
) if gzipFlag.reserved5(flags) =>
Pull.output1(
GunzipResult(
Stream.raiseError(
new ZipException("Unsupported gzip flag reserved bit 5 is non-zero")
)
)
)
case (
`gzipHeaderBytes`,
Array(
`gzipMagicFirstByte`,
`gzipMagicSecondByte`,
gzipCompressionMethod.DEFLATE,
flags,
_,
_,
_,
_,
_
)
) if gzipFlag.reserved6(flags) =>
Pull.output1(
GunzipResult(
Stream.raiseError(
new ZipException("Unsupported gzip flag reserved bit 6 is non-zero")
)
)
)
case (
`gzipHeaderBytes`,
Array(
`gzipMagicFirstByte`,
`gzipMagicSecondByte`,
gzipCompressionMethod.DEFLATE,
flags,
_,
_,
_,
_,
_
)
) if gzipFlag.reserved7(flags) =>
Pull.output1(
GunzipResult(
Stream.raiseError(
new ZipException("Unsupported gzip flag reserved bit 7 is non-zero")
)
)
)
case (
`gzipHeaderBytes`,
header @ Array(
`gzipMagicFirstByte`,
`gzipMagicSecondByte`,
gzipCompressionMethod.DEFLATE,
flags,
_,
_,
_,
_,
_,
_
)
) =>
headerCrc32.update(header)
val secondsSince197001010000 =
unsignedToLong(header(4), header(5), header(6), header(7))
_gunzip_readOptionalHeader(
inflateParams,
streamAfterMandatoryHeader,
flags,
headerCrc32,
contentCrc32,
secondsSince197001010000,
inflater
).pull.uncons1
.flatMap {
case Some((gunzipResult, _)) =>
Pull.output1(gunzipResult)
case None =>
Pull.output1(GunzipResult(Stream.raiseError(new EOFException())))
}
case (
`gzipHeaderBytes`,
Array(
`gzipMagicFirstByte`,
`gzipMagicSecondByte`,
compressionMethod,
_,
_,
_,
_,
_,
_,
_
)
) =>
Pull.output1(
GunzipResult(
Stream.raiseError(
new ZipException(
s"Unsupported gzip compression method: $compressionMethod"
)
)
)
)
case _ =>
Pull.output1(
GunzipResult(Stream.raiseError(new ZipException("Not in gzip format")))
)
}
private def _gunzip_readOptionalHeader[F[_]](
inflateParams: InflateParams,
streamAfterMandatoryHeader: Stream[F, Byte],
flags: Byte,
headerCrc32: CRC32,
contentCrc32: CRC32,
secondsSince197001010000: Long,
inflater: Inflater
)(implicit SyncF: Sync[F]): Stream[F, GunzipResult[F]] =
streamAfterMandatoryHeader
.through(_gunzip_skipOptionalExtraField(gzipFlag.fextra(flags), headerCrc32))
.through(
_gunzip_readOptionalStringField(
gzipFlag.fname(flags),
headerCrc32,
"file name",
fileNameBytesSoftLimit
)
)
.flatMap { case (fileName, streamAfterFileName) =>
streamAfterFileName
.through(
_gunzip_readOptionalStringField(
gzipFlag.fcomment(flags),
headerCrc32,
"file comment",
fileCommentBytesSoftLimit
)
)
.flatMap { case (comment, streamAfterComment) =>
Stream.emit(
GunzipResult(
modificationTime =
if (secondsSince197001010000 != 0)
Some(Instant.ofEpochSecond(secondsSince197001010000))
else None,
fileName = fileName,
comment = comment,
content = streamAfterComment
.through(
_gunzip_validateHeader(
(flags & gzipFlag.FHCRC) == gzipFlag.FHCRC,
headerCrc32
)
)
.through(
_inflate(
inflateParams = inflateParams,
inflater = inflater,
crc32 = Some(contentCrc32)
)
)
.through(_gunzip_validateTrailer(contentCrc32, inflater))
)
)
}
}
private def _gunzip_skipOptionalExtraField[F[_]](
isPresent: Boolean,
crc32: CRC32
)(implicit Sync: Sync[F]): Pipe[F, Byte, Byte] =
stream =>
if (isPresent)
stream.pull
.unconsN(gzipOptionalExtraFieldLengthBytes)
.flatMap {
case Some((optionalExtraFieldLengthChunk, streamAfterOptionalExtraFieldLength)) =>
(
optionalExtraFieldLengthChunk.size,
optionalExtraFieldLengthChunk.toBytes.values
) match {
case (
`gzipOptionalExtraFieldLengthBytes`,
lengthBytes @ Array(firstByte, secondByte)
) =>
crc32.update(lengthBytes)
val optionalExtraFieldLength = unsignedToInt(firstByte, secondByte)
streamAfterOptionalExtraFieldLength.pull
.unconsN(optionalExtraFieldLength)
.flatMap {
case Some((optionalExtraFieldChunk, streamAfterOptionalExtraField)) =>
val fieldBytes = optionalExtraFieldChunk.toBytes
crc32.update(fieldBytes.values, fieldBytes.offset, fieldBytes.length)
Pull.output1(streamAfterOptionalExtraField)
case None =>
Pull.raiseError(
new ZipException("Failed to read optional extra field header")
)
}
case _ =>
Pull.raiseError(
new ZipException("Failed to read optional extra field header length")
)
}
case None =>
Pull.raiseError(new EOFException())
}
.stream
.flatten
else stream
private def _gunzip_readOptionalStringField[F[_]](
isPresent: Boolean,
crc32: CRC32,
fieldName: String,
fieldBytesSoftLimit: Int
)(implicit
SyncF: Sync[F]
): Stream[F, Byte] => Stream[F, (Option[String], Stream[F, Byte])] =
stream =>
if (isPresent)
unconsUntil[F, Byte](_ == zeroByte, fieldBytesSoftLimit)(stream).flatMap {
case Some((chunk, rest)) =>
Pull.output1(
(
if (chunk.isEmpty)
Some("")
else {
val bytesChunk = chunk.toBytes
crc32.update(bytesChunk.values, bytesChunk.offset, bytesChunk.length)
Some(
new String(
bytesChunk.values,
bytesChunk.offset,
bytesChunk.length,
StandardCharsets.ISO_8859_1
)
)
},
rest
.dropWhile { byte =>
// Will also call crc32.update(byte) for the zeroByte dropped hereafter.
crc32.update(byte.toInt)
byte != zeroByte
}
.drop(1)
)
)
case None =>