File: zlib.scm

package info (click to toggle)
guile-zlib 0.2.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 144 kB
  • sloc: lisp: 924; makefile: 63
file content (858 lines) | stat: -rw-r--r-- 33,772 bytes parent folder | download
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
;;; Guile-zlib --- GNU Guile bindings of zlib
;;; Copyright © 2016-2017, 2021, 2024 Ludovic Courtès <ludo@gnu.org>
;;; Copyright © 2020 Mathieu Othacehe <othacehe@gnu.org>
;;; Copyright © 2013 David Thompson <dthompson2@worcester.edu>
;;; Copyright © 2023 Artyom V. Poptsov <poptsov.artyom@gmail.com>
;;;
;;; This file is part of Guile-zlib.
;;;
;;; Guile-zlib is free software; you can redistribute it and/or modify it
;;; under the terms of the GNU General Public License as published by
;;; the Free Software Foundation; either version 3 of the License, or (at
;;; your option) any later version.
;;;
;;; Guile-zlib is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;;; GNU General Public License for more details.
;;;
;;; You should have received a copy of the GNU General Public License
;;; along with Guile-zlib.  If not, see <http://www.gnu.org/licenses/>.

(define-module (zlib)
  #:use-module (zlib config)
  #:use-module (rnrs bytevectors)
  #:use-module (ice-9 binary-ports)
  #:use-module (ice-9 match)
  #:use-module (system foreign)
  #:use-module (ice-9 receive)
  #:use-module (srfi srfi-1)
  #:export (make-gzip-input-port
            make-gzip-output-port
            call-with-gzip-input-port
            call-with-gzip-output-port
            %default-buffer-size
            %default-compression-level

            compress
            uncompress
            adler32
            crc32

            make-zlib-input-port
            make-zlib-output-port
            call-with-zlib-input-port
            call-with-zlib-output-port

            ;; Error codes returned together with 'zlib-error' exceptions.
            Z_OK
            Z_STREAM_END
            Z_NEED_DICT
            Z_ERRNO
            Z_STREAM_ERROR
            Z_DATA_ERROR
            Z_MEM_ERROR
            Z_BUF_ERROR))

;;; Commentary:
;;;
;;; This file is extracted from Guix and originally written by Ludovic Courtès.
;;; Bindings to the gzip-related part of zlib's API.  The main limitation of
;;; this API is that it requires a file descriptor as the source or sink.
;;;
;;; Code:

(define %zlib
  (delay (dynamic-link %libz)))

(define (zlib-procedure ret name parameters)
  "Return a procedure corresponding to C function NAME in libz, or #f if
either zlib or the function could not be found."
  (match (false-if-exception (dynamic-func name (force %zlib)))
    ((? pointer? ptr)
     (pointer->procedure ret ptr parameters))
    (#f
     #f)))

(define-wrapped-pointer-type <gzip-file>
  ;; Scheme counterpart of the 'gzFile' opaque type.
  gzip-file?
  pointer->gzip-file
  gzip-file->pointer
  (lambda (obj port)
    (format port "#<gzip-file ~a>"
            (number->string (object-address obj) 16))))

;; On Guile 2.0, (set-port-encoding! PORT #f) throws.  Work around it.
(cond-expand
 ((not guile-2.2)                                 ;Guile 2.0
  (define (set-port-encoding!* port encoding)
    (when encoding
      (set-port-encoding! port encoding))))
 (else
  (define set-port-encoding!* set-port-encoding!)))

(define gzerror
  (let ((proc (zlib-procedure '* "gzerror" '(* *))))
    (lambda (gzfile)
      "Return two values: the error code corresponding to the current error
on GZFILE (one of the Z_* constants), and the corresponding error message as
a string."
      (let* ((errnum* (make-bytevector (sizeof int)))
             (ptr     (proc (gzip-file->pointer gzfile)
                            (bytevector->pointer errnum*))))
        (values (bytevector-sint-ref errnum* 0
                                     (native-endianness) (sizeof int))
                (pointer->string ptr))))))

(define gzdopen
  (let ((proc (zlib-procedure '* "gzdopen" (list int '*))))
    (lambda (fd mode)
      "Open file descriptor FD as a gzip stream with the given MODE.  MODE must
be a string denoting the how FD is to be opened, such as \"r\" for reading or
\"w9\" for writing data compressed at level 9 to FD.  Calling 'gzclose' also
closes FD."
      (let ((result (proc fd (string->pointer mode))))
        (if (null-pointer? result)
            (throw 'zlib-error 'gzdopen)
            (pointer->gzip-file result))))))

(define (raise-gzerror-exception proc gzfile)
  "Raise a 'zlib-error' exception that includes information returned by
'gzerror' on GZFILE."
  (call-with-values (lambda () (gzerror gzfile))
    (lambda (code message)
      (throw 'zlib-error proc code message))))

(define (print-zlib-error port key args default-printer)
  (match args
    ((_ proc)
     (format port "In procedure ~a: unspecified zlib error" proc))
    ((_ proc code)
     (format port "In procedure ~a: zlib error ~a" proc code))
    ((_ proc code message . _)
     (format port "In procedure ~a: zlib error ~a: ~a" proc code message))))

(set-exception-printer! 'zlib-error print-zlib-error)

(define gzread!
  (let ((proc (zlib-procedure int "gzread" (list '* '* unsigned-int))))
    (lambda* (gzfile bv #:optional (start 0) (count (bytevector-length bv)))
      "Read up to COUNT bytes from GZFILE into BV at offset START.  Return the
number of uncompressed bytes actually read; it is zero if COUNT is zero or if
the end-of-stream has been reached."
      (let ((ret (proc (gzip-file->pointer gzfile)
                       (bytevector->pointer bv start)
                       count)))
        (if (< ret 0)
            (raise-gzerror-exception 'gzread! gzfile)
            ret)))))

(define gzwrite
  (let ((proc (zlib-procedure int "gzwrite" (list '* '* unsigned-int))))
    (lambda* (gzfile bv #:optional (start 0) (count (bytevector-length bv)))
      "Write up to COUNT bytes from BV at offset START into GZFILE.  Return
the number of uncompressed bytes written, a strictly positive integer."
      (let ((ret (proc (gzip-file->pointer gzfile)
                       (bytevector->pointer bv start)
                       count)))
        (if (<= ret 0)
            (raise-gzerror-exception 'gzwrite gzfile)
            ret)))))

(define gzbuffer!
  (let ((proc (zlib-procedure int "gzbuffer" (list '* unsigned-int))))
    (lambda (gzfile size)
      "Change the internal buffer size of GZFILE to SIZE bytes."
      (let ((ret (proc (gzip-file->pointer gzfile) size)))
        (unless (zero? ret)
          (raise-gzerror-exception 'gzbuffer gzfile))))))

(define gzeof?
  (let ((proc (zlib-procedure int "gzeof" '(*))))
    (lambda (gzfile)
      "Return true if the end-of-file has been reached on GZFILE."
      (not (zero? (proc (gzip-file->pointer gzfile)))))))

(define gzclose
  (let ((proc (zlib-procedure int "gzclose" '(*))))
    (lambda (gzfile)
      "Close GZFILE."
      (let ((ret (proc (gzip-file->pointer gzfile))))
        (unless (zero? ret)
          (raise-gzerror-exception 'gzclose gzfile))))))



;;;
;;; Port interface.
;;;

(define %default-buffer-size
  ;; Default buffer size, as documented in <zlib.h>.
  8192)

(define %default-compression-level
  ;; Z_DEFAULT_COMPRESSION.
  -1)

(define* (make-gzip-input-port port #:key (buffer-size %default-buffer-size))
  "Return an input port that decompresses data read from PORT, a file port.  The
new port inherits the encoding of PORT.  PORT is automatically closed when the
resulting port is closed.  BUFFER-SIZE is the size in bytes of the internal
buffer, 8 KiB by default; using a larger buffer increases decompression speed.
An error is thrown if PORT contains buffered input, which would be lost (and is
lost anyway)."
  (define gzfile
    (match (drain-input port)
      (""                                         ;PORT's buffer is empty
       ;; 'gzclose' will eventually close the file descriptor beneath PORT.
       ;; 'close-port' on PORT would get EBADF if 'gzclose' already closed it,
       ;; so that's no good; revealed ports are no good either because they
       ;; leak (see <https://bugs.gnu.org/28784>); calling 'close-port' after
       ;; 'gzclose' doesn't work either because it leads to a race condition
       ;; (see <https://bugs.gnu.org/29335>).  So we dup and close PORT right
       ;; away.
       (gzdopen (dup (fileno port)) "r"))
      (_
       ;; This is unrecoverable but it's better than having the buffered input
       ;; be lost, leading to unclear end-of-file or corrupt-data errors down
       ;; the path.
       (throw 'zlib-error 'make-gzip-input-port
              "port contains buffered input" port))))

  (define (read! bv start count)
    (gzread! gzfile bv start count))

  (define encoding (port-encoding port))

  (unless (= buffer-size %default-buffer-size)
    (gzbuffer! gzfile buffer-size))

  (close-port port)                               ;we no longer need it

  (let ((result (make-custom-binary-input-port "gzip-input" read! #f #f
                                               (lambda () (gzclose gzfile)))))
    (set-port-encoding!* result encoding)
    result))


(define* (make-gzip-output-port port
                                #:key
                                (level %default-compression-level)
                                (buffer-size %default-buffer-size))
  "Return an output port that compresses data at the given LEVEL, using PORT, a
file port, as its sink.  PORT must be a file port; it is automatically closed
when the resulting port is closed.  The new port inherits the encoding of PORT."
  (define gzfile
    (begin
      (force-output port)                         ;empty PORT's buffer
      (gzdopen (dup (fileno port))
               (string-append "w" (number->string level)))))

  (define (write! bv start count)
    (gzwrite gzfile bv start count))

  (define encoding (port-encoding port))

  (unless (= buffer-size %default-buffer-size)
    (gzbuffer! gzfile buffer-size))

  (close-port port)
  (let ((result (make-custom-binary-output-port "gzip-output" write! #f #f
                                                (lambda () (gzclose gzfile)))))
    (set-port-encoding!* result encoding)
    result))

(define (call-with-zlib-port port proc)
  "Call PROC with PORT as its argument.  Close PORT when leaving the dynamic
extent of PROC via return or exception."
  ;; Note: Not using 'dynamic-wind' to allow for 'abort-to-prompt' calls in
  ;; PROC, as happens with Fibers.
  (catch #t
    (lambda ()
      (let ((result (proc port)))
        (close-port port)
        result))
    (lambda args
      (close-port port)
      (apply throw args))))

(define* (call-with-gzip-input-port port proc
                                    #:key (buffer-size %default-buffer-size))
  "Call PROC with a port that wraps PORT and decompresses data read from it.
PORT must be a file port; it is closed upon completion.  The new port inherits
the encoding of PORT.  The gzip internal buffer size is set to BUFFER-SIZE
bytes.

See 'call-with-zlib-input-port' for a slightly slower variant that does not
require PORT to be a file port."
  (call-with-zlib-port (make-gzip-input-port port #:buffer-size buffer-size)
    proc))

(define* (call-with-gzip-output-port port proc
                                     #:key
                                     (level %default-compression-level)
                                     (buffer-size %default-buffer-size))
  "Call PROC with an output port that wraps PORT and compresses data.  PORT must
be a file port; it is closed upon completion.  The new port inherits the
encoding of PORT.  The gzip internal buffer size is set to BUFFER-SIZE bytes.

See 'call-with-zlib-output-port' for a slightly slower variant that does not
require PORT to be a file port."
  (call-with-zlib-port (make-gzip-output-port port
                                              #:level level
                                              #:buffer-size buffer-size)
    proc))


;;;
;;; Raw operations, originally from davexunit's guile-zlib
;;; https://github.com/davexunit/guile-zlib
;;; fd28b7515efc4af6faf55854993cb0c8bed1f8c5
;;;

;;
;; ZEXTERN int ZEXPORT uncompress OF((Bytef *dest, uLongf *destLen,
;;                                    const Bytef *source, uLong sourceLen));
;;
;; Decompresses the source buffer into the destination
;; buffer. sourceLen is the byte length of the source buffer. Upon
;; entry, destLen is the total size of the destination buffer, which
;; must be large enough to hold the entire uncompressed data. (The
;; size of the uncompressed data must have been saved previously by
;; the compressor and transmitted to the decompressor by some
;; mechanism outside the scope of this compression library.) Upon
;; exit, destLen is the actual size of the compressed buffer.
;;
;; uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
;; enough memory, Z_BUF_ERROR if there was not enough room in the
;; output buffer, or Z_DATA_ERROR if the input data was corrupted or
;; incomplete. In the case where there is not enough room,
;; uncompress() will fill the output buffer with the uncompressed data
;; up to that point.
(define %uncompress
  (zlib-procedure int "uncompress" (list '* '* '* unsigned-long)))

;; ZEXTERN int ZEXPORT uncompress2(Bytef *dest,   uLongf *destLen,
;;                                 const Bytef *source, uLong *sourceLen);
;;
;; Same as uncompress, except that sourceLen is a pointer, where the length of
;; the source is *sourceLen. On return, *sourceLen is the number of source bytes
;; consumed.
(define %uncompress2
  (zlib-procedure int "uncompress2" (list '* '* '* '*)))

;;
;; ZEXTERN int ZEXPORT compress OF((Bytef *dest, uLongf *destLen,
;;                                  const Bytef *source, uLong sourceLen));
;;
;; Compresses the source buffer into the destination buffer. sourceLen
;; is the byte length of the source buffer. Upon entry, destLen is the
;; total size of the destination buffer, which must be at least the
;; value returned by compressBound(sourceLen). Upon exit, destLen is
;; the actual size of the compressed buffer.
;;
;; compress returns Z_OK if success, Z_MEM_ERROR if there was not
;; enough memory, Z_BUF_ERROR if there was not enough room in the
;; output buffer.
(define %compress
  (zlib-procedure int "compress" (list '* '* '* unsigned-long)))

;;
;; ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
;;
;; compressBound() returns an upper bound on the compressed size after
;; compress() or compress2() on sourceLen bytes. It would be used
;; before a compress() or compress2() call to allocate the destination
;; buffer.
(define %compress-bound
  (zlib-procedure unsigned-long "compressBound" (list unsigned-long)))

;; Update a running Adler-32 checksum with the bytes buf[0..len-1] and
;; return the updated checksum.  If buf is Z_NULL, this function returns the
;; required initial value for the checksum.
;;
;;   An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
;; much faster.
;;
;; Usage example:
;;
;;   uLong adler = adler32(0L, Z_NULL, 0);
;;
;;   while (read_buffer(buffer, length) != EOF) {
;;     adler = adler32(adler, buffer, length);
;;   }
;;   if (adler != original_adler) error();
(define %adler32
  (zlib-procedure unsigned-long "adler32" (list unsigned-long '* unsigned-int)))

;; Update a running CRC-32 with the bytes buf[0..len-1] and return the
;; updated CRC-32.  If buf is Z_NULL, this function returns the required
;; initial value for the crc.  Pre- and post-conditioning (one's complement) is
;; performed within this function so it shouldn't be done by the application.
;;
;; Usage example:
;;
;;   uLong crc = crc32(0L, Z_NULL, 0);
;;
;;   while (read_buffer(buffer, length) != EOF) {
;;     crc = crc32(crc, buffer, length);
;;   }
;;   if (crc != original_crc) error();
(define %crc32
  (zlib-procedure unsigned-long "crc32" (list unsigned-long '* unsigned-int)))

;; There is a bit of guesswork involved when creating the bytevectors
;; to store compressed/uncompressed data in. This procedure provides a
;; convenient way to copy the portion of a bytevector that was
;; actually used.
(define (bytevector-copy-region bv start end)
  (let* ((length (- end start))
         (new-bv (make-bytevector length)))
    (bytevector-copy! bv start new-bv 0 length)
    new-bv))

;; uncompress/compress take a bytevector that zlib writes the size of
;; the returned data to. This procedure saves me a few keystrokes when
;; fetching that value.
(define (buffer-length bv)
  (bytevector-uint-ref bv 0
                       (native-endianness) (sizeof unsigned-long)))

(define (uncompress bv)
  "Uncompresses bytevector and returns a bytevector containing
the uncompressed data."
  (define (try-uncompress length)
    (let* ((dest (make-bytevector (* (sizeof uint8) length)))
           (dest-length   (make-bytevector (sizeof unsigned-long)))
           (source-length (make-bytevector (sizeof unsigned-long))))
      (bytevector-uint-set! source-length 0 length
                            (native-endianness) (sizeof unsigned-long))
      (bytevector-uint-set! dest-length 0 length
                            (native-endianness) (sizeof unsigned-long))
      (let ((result (%uncompress2 (bytevector->pointer dest)
                                  (bytevector->pointer dest-length)
                                  (bytevector->pointer bv)
                                  (bytevector->pointer source-length))))
        (values result
                (bytevector-copy-region dest 0 (buffer-length dest-length))
                (buffer-length source-length)))))

  (let try-again ((tries  1)
                  (length (inexact->exact
                           (round (* (bytevector-length bv) 1.5)))))
    ;; Bail after so many failed attempts. This shouldn't happen, but
    ;; I don't like the idea of a potentially unbounded loop that
    ;; keeps allocating larger and larger chunks of memory.
    (if (> tries 10)
        (throw 'zlib-error 'uncompress 0)
        (receive (ret-code uncompressed-data read-source-length)
            (try-uncompress length)
          ;; return code -5 means that destination buffer was too small.
          ;; return code  0 means everything went OK.
          (cond ((= ret-code -5)
                 (let* ((compressesed-data-size (bytevector-length bv))
                        (percent                (* (/ read-source-length
                                                      compressesed-data-size)
                                                   100))
                        (next-size (inexact->exact (round (/ (* 100 length)
                                                             percent)))))
                   (try-again (1+ tries) next-size)))
                ((= ret-code 0)
                 uncompressed-data)
                (else
                 (throw 'zlib-error 'uncompress ret-code)))))))

(define (compress bv)
  "Compresses bytevector and returns a bytevector containing the compressed data."
  (let* ((bv-length      (bytevector-length bv))
         (dest-length    (%compress-bound bv-length))
         (dest-bv        (make-bytevector dest-length))
         (dest-length-bv (make-bytevector (sizeof unsigned-long)))
         (ret-code       0))
    (bytevector-uint-set! dest-length-bv 0 dest-length
                          (native-endianness) (sizeof unsigned-long))
    (set! ret-code
          (%compress (bytevector->pointer dest-bv)
                     (bytevector->pointer dest-length-bv)
                     (bytevector->pointer bv)
                     bv-length))
    (if (= ret-code 0)
        (bytevector-copy-region dest-bv 0
                                (buffer-length dest-length-bv))
        (throw 'zlib-error 'compress ret-code))))

(define %default-adler32 (%adler32 0 %null-pointer 0))
(define %default-crc32   (%crc32   0 %null-pointer 0))

(define* (adler32 bv #:optional (value %default-adler32))
  "Computes adler32 checksum with optional starting value."
  (%adler32 value (bytevector->pointer bv) (bytevector-length bv)))

(define* (crc32 bv #:optional (value %default-crc32))
  "Computes crc32 checksum with optional starting value."
  (%crc32 value (bytevector->pointer bv) (bytevector-length bv)))


;;;
;;; Low-level zlib stream API.
;;;

(define %zlib-version
  ;; Library version that we're targeting.
  "1.2.11")

;; struct zstream
(define %stream-struct
  (list '*                                        ;next_in
        unsigned-int                              ;avail_in
        unsigned-long                             ;total_in

        '*                                        ;next_out
        unsigned-int                              ;avail_out
        unsigned-long                             ;total_out

        '*                                        ;msg
        '*                                        ;state

        '*                                        ;zalloc
        '*                                        ;zfree
        '*                                        ;opaque

        int                                       ;data_type

        unsigned-long                             ;adler
        unsigned-long))                           ;reserved

(define (offset-of types n)
  "Return the offset of the Nth field among TYPES, the list of types of a
struct's fields."
  (if (zero? n)
      0
      (let* ((base  (sizeof (take types n)))
             (align (alignof (list-ref types n)))
             (mod   (modulo base align)))
        (if (zero? mod)
            base
            (+ base (- align mod))))))

(define-syntax-rule (define-stream-getter name index)
  "Define NAME as a procedure accessing the INDEXth field of %STREAM-STRUCT."
  (define name
    (let* ((offset (offset-of %stream-struct index))
           (type   (list-ref %stream-struct index))
           (size   (sizeof type)))
      (lambda (stream)
        (bytevector-uint-ref stream offset (native-endianness)
                             size)))))

(define-syntax-rule (define-stream-setter name index)
  "Define NAME as a procedure setting the INDEXth field of %STREAM-STRUCT."
  (define name
    (let* ((offset (offset-of %stream-struct index))
           (type   (list-ref %stream-struct index))
           (size   (sizeof type)))
      (lambda (stream value)
        (bytevector-uint-set! stream offset value
                              (native-endianness) size)))))

(define-stream-getter stream-avail-in 1)
(define-stream-getter stream-avail-out 4)
(define-stream-getter stream-error-message 6)
(define-stream-setter set-stream-next-in! 0)
(define-stream-setter set-stream-avail-in! 1)
(define-stream-setter set-stream-next-out! 3)
(define-stream-setter set-stream-avail-out! 4)

(define (stream-error-message* stream)
  "Return the error message associated with STREAM or #f."
  (match (stream-error-message stream)
    ((? zero?) #f)
    (address   (pointer->string (make-pointer address)))))

(define inflate!
  (let ((proc (zlib-procedure int "inflate" `(* ,int))))
    (lambda (stream flush)
      (proc stream flush))))

(define deflate!
  (let ((proc (zlib-procedure int "deflate" `(* ,int))))
    (lambda (stream flush)
      (proc stream flush))))

(define (window-bits-for-format format)
  ;; Search for "windowBits" in <zlib.h>.
  (define MAX_WBITS 15)                           ;<zconf.h>
  (match format
    ('deflate (- MAX_WBITS))                      ;raw deflate
    ('zlib    MAX_WBITS)                          ;zlib header
    ('gzip    (+ MAX_WBITS 16))))                 ;gzip header

(define inflate-init!
  (let ((proc (zlib-procedure int "inflateInit2_" `(* ,int * ,int))))
    (lambda (stream window-bits)
      (let ((ret (proc stream window-bits
                       (string->pointer %zlib-version)
                       (sizeof %stream-struct))))
        (unless (zero? ret)
          (throw 'zlib-error 'inflate-init! ret))))))

(define deflate-init!
  (let ((proc (zlib-procedure int "deflateInit2_" `(* ,int ,int ,int ,int
                                                      ,int * ,int))))
    (lambda* (stream level
                     #:key
                     (window-bits (window-bits-for-format 'zlib))
                     (memory-level 8)
                     (strategy Z_DEFAULT_STRATEGY))
      (let ((ret (proc stream level Z_DEFLATED
                       window-bits memory-level strategy
                       (string->pointer %zlib-version)
                       (sizeof %stream-struct))))
        (unless (zero? ret)
          (throw 'zlib-error 'deflate-init! ret))))))

(define inflate-end!
  (let ((proc (zlib-procedure int "inflateEnd" '(*))))
    (lambda (stream)
      (let ((ret (proc stream)))
        (unless (zero? ret)
          (throw 'zlib-error 'inflate-end! ret))))))

(define deflate-end!
  (let ((proc (zlib-procedure int "deflateEnd" '(*))))
    (lambda (stream)
      (let ((ret (proc stream)))
        (unless (zero? ret)
          (throw 'zlib-error 'deflate-end! ret))))))

;; Error codes.
(define Z_OK 0)
(define Z_STREAM_END 1)
(define Z_NEED_DICT 2)
(define Z_ERRNO -1)
(define Z_STREAM_ERROR -2)
(define Z_DATA_ERROR -3)
(define Z_MEM_ERROR -4)
(define Z_BUF_ERROR -5)

;; Flush flags.
(define Z_NO_FLUSH 0)
(define Z_PARTIAL_FLUSH 1)
(define Z_SYNC_FLUSH 2)
(define Z_FULL_FLUSH 3)
(define Z_FINISH 4)

;; 'deflate-init!' flags.
(define Z_DEFLATED 8)
(define Z_DEFAULT_STRATEGY 0)

(define* (make-zlib-input-port port
                               #:key
                               (format 'zlib)
                               (buffer-size %default-buffer-size)
                               (close? #t))
  "Return an input port that decompresses data read from PORT.  FORMAT is a
symbol denoting the header format; it must be one of 'deflate (RFC 1950), 'zlib
(RFC 1951), or 'gzip (RFC 1952).  The new port inherits the encoding of PORT.

When CLOSE? is true, PORT is automatically closed when the resulting port is
closed."
  (define input-buffer (make-bytevector buffer-size))

  ;; Instead of writing uncompressed data directly to the user-provided
  ;; buffer, keep a large-enough buffer.  That way, we know we cannot stumble
  ;; into Z_BUF_ERROR because of insufficient output space.
  (define output-buffer (make-bytevector %default-buffer-size))
  (define buffered 0)
  (define offset 0)

  (define eof? #f)

  (define stream (make-bytevector (sizeof %stream-struct)))
  (define pointer
    (let ((ptr (bytevector->pointer stream)))
      (lambda (bv)
        (if (eq? bv stream)
            ptr
            (bytevector->pointer bv)))))

  (define (read! bv start count)
    (cond ((> buffered 0)
           (let ((n (min count buffered)))
             (bytevector-copy! output-buffer offset bv start n)
             (set! buffered (- buffered n))
             (set! offset (+ offset n))
             n))
          (eof? 0)
          (else
           (set! offset 0)
           (set-stream-next-out! stream
                                 (pointer-address
                                  (bytevector->pointer output-buffer)))
           (set-stream-avail-out! stream (bytevector-length output-buffer))

           (let loop ((ret Z_OK)
                      (flush? #f))
             (if (and (not flush?)
                      (or (zero? (stream-avail-in stream))
                          (= Z_BUF_ERROR ret)))
                 (let ((n (get-bytevector-n! port input-buffer
                                             0 buffer-size)))
                   (if (eof-object? n)
                       (loop ret #t)
                       (begin
                         (set-stream-next-in! stream
                                              (pointer-address
                                               (bytevector->pointer input-buffer)))
                         (set-stream-avail-in! stream n)
                         (loop ret flush?))))

                 (let ((ret (inflate! (pointer stream)
                                      (if flush? Z_SYNC_FLUSH 0))))
                   (set! buffered (- (bytevector-length output-buffer)
                                     (stream-avail-out stream)))
                   (cond ((= ret Z_OK)
                          (read! bv start count))
                         ((= ret Z_STREAM_END)
                          (set! eof? #t)
                          (read! bv start count))
                         ((and (not flush?) (= Z_BUF_ERROR ret))
                          (loop ret flush?))
                         (else
                          (throw 'zlib-error ret
                                 (stream-error-message* stream))))))))))

  (define encoding (port-encoding port))

  (define result
    (make-custom-binary-input-port "zlib-input" read! #f #f
                                   (lambda ()
                                     (inflate-end! (pointer stream))
                                     (when close?
                                       (close-port port)))))

  ;; No need for extra buffering.
  (cond-expand ((or guile-2.2 guile-3.0)
                (setvbuf result 'none))
               (else #t))                         ;not possible on 2.0

  (inflate-init! (pointer stream)
                 (window-bits-for-format format))
  (set-stream-avail-in! stream 0)
  (set-port-encoding!* result encoding)
  result)

(define* (make-zlib-output-port port
                                #:key
                                (format 'zlib)
                                (buffer-size %default-buffer-size)
                                (level %default-compression-level)
                                (close? #t))
  "Return an output port that compresses data at the given LEVEL, using PORT as
its sink.  FORMAT is a symbol denoting the header format; it must be one of
'deflate (RFC 1950), 'zlib (RFC 1951), or 'gzip (RFC 1952).  The new port
inherits the encoding of PORT.

When FORMAT is 'gzip, the gzip header takes default values, and in particular
no modification time and no file name.

When CLOSE? is true, PORT is automatically closed when the resulting port is
closed."
  (define output-buffer (make-bytevector buffer-size))
  (define stream (make-bytevector (sizeof %stream-struct)))

  (define pointer
    (let ((ptr (bytevector->pointer stream)))
      (lambda (bv)
        (if (eq? bv stream)
            ptr
            (bytevector->pointer bv)))))

  (define (output-compressed-data! stream)
    (put-bytevector port output-buffer 0
                    (- buffer-size (stream-avail-out stream)))
    (set-stream-avail-out! stream buffer-size)
    (set-stream-next-out! stream
                          (pointer-address
                           (bytevector->pointer output-buffer))))

  (define* (write! bv start count #:optional flush?)
    (set-stream-next-in! stream (+ start (pointer-address
                                          (bytevector->pointer bv))))
    (set-stream-avail-in! stream count)

    (let loop ()
      (if (zero? (stream-avail-out stream))
          (begin
            (output-compressed-data! stream)
            (loop))
          (let ((ret (deflate! (pointer stream)
                       (if flush? Z_FINISH Z_NO_FLUSH))))
            (cond ((= ret Z_BUF_ERROR)
                   (loop))
                  ((= ret Z_OK)
                   (match (- count (stream-avail-in stream))
                     (0 (loop))                   ;zero would mean EOF
                     (n n)))
                  ((and flush? (= ret Z_STREAM_END))
                   (- count (stream-avail-in stream)))
                  (else
                   (throw 'zlib-error 'deflate! ret
                          (stream-error-message* stream))))))))

  (define (flush)
    (write! #vu8() 0 0 #t)
    (output-compressed-data! stream))

  (define (close)
    (flush)
    (deflate-end! (pointer stream))
    (when close?
      (close-port port)))

  (define encoding (port-encoding port))

  (deflate-init! (pointer stream) level
    #:window-bits (window-bits-for-format format))

  (set-stream-avail-out! stream buffer-size)
  (set-stream-next-out! stream
                        (pointer-address (bytevector->pointer output-buffer)))

  (let ((result (make-custom-binary-output-port "zlib-output" write! #f #f close)))
    (set-port-encoding!* result encoding)
    result))

(define* (call-with-zlib-input-port port proc
                                    #:key
                                    (format 'zlib)
                                    (buffer-size %default-buffer-size))
  "Call PROC with a port that wraps PORT and decompresses data read from it.
PORT is closed upon completion.  The zlib internal buffer size is set to
BUFFER-SIZE bytes."
  (call-with-zlib-port (make-zlib-input-port port
                                             #:format format
                                             #:buffer-size buffer-size
                                             #:close? #t)
    proc))

(define* (call-with-zlib-output-port port proc
                                     #:key
                                     (format 'zlib)
                                     (level %default-compression-level)
                                     (buffer-size %default-buffer-size))
  "Call PROC with an output port that wraps PORT and compresses data in the
given FORMAT, with the given LEVEL.  PORT is closed upon completion.  The
zlib internal buffer size is set to BUFFER-SIZE bytes."
  (call-with-zlib-port (make-zlib-output-port port
                                              #:format format
                                              #:level level
                                              #:buffer-size buffer-size
                                              #:close? #t)
    proc))

;; Local Variables:
;; eval: (put 'call-with-zlib-port 'scheme-indent-function 1)
;; End: