Update to gobook@0a3e8d997823052c6a8575feca6e515ac6f8299d

This commit is contained in:
Alan Donovan
2015-11-30 22:37:52 -05:00
parent 84af1e6bd3
commit 34cd1719c0
7 changed files with 343 additions and 3 deletions
+20 -3
View File
@@ -2,6 +2,20 @@
// License: https://creativecommons.org/licenses/by-nc-sa/4.0/
// See page 362.
// The version of this file that appears in the book does not comply
// with the proposed rules for passing pointers between Go and C.
// (https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md)
// The rules forbid a C function like bz2compress from storing 'in' and
// 'out' (pointers to variables allocated by Go) into the Go variable 's',
// even temporarily.
//
// To comply with the rules, the bz_stream variable must be allocated
// by C code. We have introduced two C functions, bz2alloc and
// bz2free, to allocate and free instances of the bz_stream type.
// Also, we have changed bz2compress so that before it returns, it
// clears the fields of the bz_stream that contain point to Go
// variables.
//!+
// Package bzip provides a writer that uses bzip2 compression (bzip.org).
@@ -11,8 +25,12 @@ package bzip
#cgo CFLAGS: -I/usr/include
#cgo LDFLAGS: -L/usr/lib -lbz2
#include <bzlib.h>
#include <stdlib.h>
bz_stream* bz2alloc() { return calloc(1, sizeof(bz_stream)); }
int bz2compress(bz_stream *s, int action,
char *in, unsigned *inlen, char *out, unsigned *outlen);
void bz2free(bz_stream* s) { return free(s); }
*/
import "C"
@@ -34,9 +52,7 @@ func NewWriter(out io.Writer) io.WriteCloser {
verbosity = 0
workFactor = 30
)
// NOTE: This code may not work in future Go releases.
// See http://www.gopl.io/errata.html for explanation.
w := &writer{w: out, stream: new(C.bz_stream)}
w := &writer{w: out, stream: C.bz2alloc()}
C.BZ2_bzCompressInit(w.stream, blockSize, verbosity, workFactor)
return w
}
@@ -75,6 +91,7 @@ func (w *writer) Close() error {
}
defer func() {
C.BZ2_bzCompressEnd(w.stream)
C.bz2free(w.stream)
w.stream = nil
}()
for {