...
▽

Source file src/compress/flate/deflate_test.go

Documentation: compress/flate

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package flate
     6  
     7  import (
     8  	"bytes"
     9  	"errors"
    10  	"fmt"
    11  	"internal/testenv"
    12  	"io"
    13  	"math/rand"
    14  	"os"
    15  	"reflect"
    16  	"runtime/debug"
    17  	"strconv"
    18  	"strings"
    19  	"sync"
    20  	"testing"
    21  )
    22  
    23  type deflateTest struct {
    24  	in    []byte
    25  	level int
    26  	out   []byte
    27  }
    28  
    29  type deflateInflateTest struct {
    30  	in []byte
    31  }
    32  
    33  type reverseBitsTest struct {
    34  	in       uint16
    35  	bitCount uint8
    36  	out      uint16
    37  }
    38  
    39  var deflateTests = []*deflateTest{
    40  	0: {[]byte{}, 0, []byte{0x3, 0x0}},
    41  	1: {[]byte{0x11}, BestCompression, []byte{0x12, 0x4, 0xc, 0x0}},
    42  	2: {[]byte{0x11}, BestCompression, []byte{0x12, 0x4, 0xc, 0x0}},
    43  	3: {[]byte{0x11}, BestCompression, []byte{0x12, 0x4, 0xc, 0x0}},
    44  
    45  	4: {[]byte{0x11}, 0, []byte{0x0, 0x1, 0x0, 0xfe, 0xff, 0x11, 0x3, 0x0}},
    46  	5: {[]byte{0x11, 0x12}, 0, []byte{0x0, 0x2, 0x0, 0xfd, 0xff, 0x11, 0x12, 0x3, 0x0}},
    47  	6: {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, 0,
    48  		[]byte{0x0, 0x8, 0x0, 0xf7, 0xff, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x3, 0x0},
    49  	},
    50  	7:  {[]byte{}, 1, []byte{0x3, 0x0}},
    51  	8:  {[]byte{0x11}, BestCompression, []byte{0x12, 0x4, 0xc, 0x0}},
    52  	9:  {[]byte{0x11, 0x12}, BestCompression, []byte{0x12, 0x14, 0x2, 0xc, 0x0}},
    53  	10: {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, BestCompression, []byte{0x12, 0x84, 0x1, 0xc0, 0x0}},
    54  	11: {[]byte{}, 9, []byte{0x3, 0x0}},
    55  	12: {[]byte{0x11}, 9, []byte{0x12, 0x4, 0xc, 0x0}},
    56  	13: {[]byte{0x11, 0x12}, 9, []byte{0x12, 0x14, 0x2, 0xc, 0x0}},
    57  	14: {[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}, 9, []byte{0x12, 0x84, 0x1, 0xc0, 0x0}},
    58  }
    59  
    60  var deflateInflateTests = []*deflateInflateTest{
    61  	{[]byte{}},
    62  	{[]byte{0x11}},
    63  	{[]byte{0x11, 0x12}},
    64  	{[]byte{0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11}},
    65  	{[]byte{0x11, 0x10, 0x13, 0x41, 0x21, 0x21, 0x41, 0x13, 0x87, 0x78, 0x13}},
    66  	{largeDataChunk()},
    67  }
    68  
    69  var reverseBitsTests = []*reverseBitsTest{
    70  	{1, 1, 1},
    71  	{1, 2, 2},
    72  	{1, 3, 4},
    73  	{1, 4, 8},
    74  	{1, 5, 16},
    75  	{17, 5, 17},
    76  	{257, 9, 257},
    77  	{29, 5, 23},
    78  }
    79  
    80  func largeDataChunk() []byte {
    81  	result := make([]byte, 100000)
    82  	for i := range result {
    83  		result[i] = byte(i * i & 0xFF)
    84  	}
    85  	return result
    86  }
    87  
    88  func TestBulkHash4(t *testing.T) {
    89  	for _, x := range deflateTests {
    90  		y := x.out
    91  		if len(y) < minMatchLength {
    92  			continue
    93  		}
    94  		y = append(y, y...)
    95  		for j := 4; j < len(y); j++ {
    96  			y := y[:j]
    97  			dst := make([]uint32, len(y)-minMatchLength+1)
    98  			for i := range dst {
    99  				dst[i] = uint32(i + 100)
   100  			}
   101  			bulkHash4(y, dst)
   102  			for i, got := range dst {
   103  				want := hash4(y[i:])
   104  				if got != want && got == uint32(i)+100 {
   105  					t.Errorf("Len:%d Index:%d, want 0x%08x but not modified", len(y), i, want)
   106  				} else if got != want {
   107  					t.Errorf("Len:%d Index:%d, got 0x%08x want:0x%08x", len(y), i, got, want)
   108  				}
   109  			}
   110  		}
   111  	}
   112  }
   113  
   114  func TestDeflate(t *testing.T) {
   115  	for i, h := range deflateTests {
   116  		var buf bytes.Buffer
   117  		w, err := NewWriter(&buf, h.level)
   118  		if err != nil {
   119  			t.Errorf("NewWriter: %v", err)
   120  			continue
   121  		}
   122  		w.Write(h.in)
   123  		w.Close()
   124  		if !bytes.Equal(buf.Bytes(), h.out) {
   125  			t.Errorf("%d: Deflate(%d, %x) =\n%#v\nwant\n%#v", i, h.level, h.in, buf.Bytes(), h.out)
   126  		}
   127  	}
   128  }
   129  
   130  func TestWriterClose(t *testing.T) {
   131  	b := new(bytes.Buffer)
   132  	zw, err := NewWriter(b, 6)
   133  	if err != nil {
   134  		t.Fatalf("NewWriter: %v", err)
   135  	}
   136  
   137  	if c, err := zw.Write([]byte("Test")); err != nil || c != 4 {
   138  		t.Fatalf("Write to not closed writer: %s, %d", err, c)
   139  	}
   140  
   141  	if err := zw.Close(); err != nil {
   142  		t.Fatalf("Close: %v", err)
   143  	}
   144  
   145  	afterClose := b.Len()
   146  
   147  	if c, err := zw.Write([]byte("Test")); err == nil || c != 0 {
   148  		t.Fatalf("Write to closed writer: %v, %d", err, c)
   149  	}
   150  
   151  	if err := zw.Flush(); err == nil {
   152  		t.Fatalf("Flush to closed writer: %s", err)
   153  	}
   154  
   155  	if err := zw.Close(); err != nil {
   156  		t.Fatalf("Close: %v", err)
   157  	}
   158  
   159  	if afterClose != b.Len() {
   160  		t.Fatalf("Writer wrote data after close. After close: %d. After writes on closed stream: %d", afterClose, b.Len())
   161  	}
   162  }
   163  
   164  // A sparseReader returns a stream consisting of 0s followed by 1<<16 1s.
   165  // This tests missing hash references in a very large input.
   166  type sparseReader struct {
   167  	l   int64
   168  	cur int64
   169  }
   170  
   171  func (r *sparseReader) Read(b []byte) (n int, err error) {
   172  	if r.cur >= r.l {
   173  		return 0, io.EOF
   174  	}
   175  	n = len(b)
   176  	cur := r.cur + int64(n)
   177  	if cur > r.l {
   178  		n -= int(cur - r.l)
   179  		cur = r.l
   180  	}
   181  	for i := range b[0:n] {
   182  		if r.cur+int64(i) >= r.l-1<<16 {
   183  			b[i] = 1
   184  		} else {
   185  			b[i] = 0
   186  		}
   187  	}
   188  	r.cur = cur
   189  	return
   190  }
   191  
   192  func TestVeryLongSparseChunk(t *testing.T) {
   193  	if testing.Short() {
   194  		t.Skip("skipping sparse chunk during short test")
   195  	}
   196  	var buf bytes.Buffer
   197  	w, err := NewWriter(&buf, 1)
   198  	if err != nil {
   199  		t.Errorf("NewWriter: %v", err)
   200  		return
   201  	}
   202  	if _, err = io.Copy(w, &sparseReader{l: 23e8}); err != nil {
   203  		t.Errorf("Compress failed: %v", err)
   204  		return
   205  	}
   206  }
   207  
   208  type syncBuffer struct {
   209  	buf    bytes.Buffer
   210  	mu     sync.RWMutex
   211  	closed bool
   212  	ready  chan bool
   213  }
   214  
   215  func newSyncBuffer() *syncBuffer {
   216  	return &syncBuffer{ready: make(chan bool, 1)}
   217  }
   218  
   219  func (b *syncBuffer) Read(p []byte) (n int, err error) {
   220  	for {
   221  		b.mu.RLock()
   222  		n, err = b.buf.Read(p)
   223  		b.mu.RUnlock()
   224  		if n > 0 || b.closed {
   225  			return
   226  		}
   227  		<-b.ready
   228  	}
   229  }
   230  
   231  func (b *syncBuffer) signal() {
   232  	select {
   233  	case b.ready <- true:
   234  	default:
   235  	}
   236  }
   237  
   238  func (b *syncBuffer) Write(p []byte) (n int, err error) {
   239  	n, err = b.buf.Write(p)
   240  	b.signal()
   241  	return
   242  }
   243  
   244  func (b *syncBuffer) WriteMode() {
   245  	b.mu.Lock()
   246  }
   247  
   248  func (b *syncBuffer) ReadMode() {
   249  	b.mu.Unlock()
   250  	b.signal()
   251  }
   252  
   253  func (b *syncBuffer) Close() error {
   254  	b.closed = true
   255  	b.signal()
   256  	return nil
   257  }
   258  
   259  func testSync(t *testing.T, level int, input []byte, name string) {
   260  	if len(input) == 0 {
   261  		return
   262  	}
   263  
   264  	t.Logf("--testSync %d, %d, %s", level, len(input), name)
   265  	buf := newSyncBuffer()
   266  	buf1 := new(bytes.Buffer)
   267  	buf.WriteMode()
   268  	w, err := NewWriter(io.MultiWriter(buf, buf1), level)
   269  	if err != nil {
   270  		t.Errorf("NewWriter: %v", err)
   271  		return
   272  	}
   273  	r := NewReader(buf)
   274  
   275  	// Write half the input and read back.
   276  	for i := range 2 {
   277  		var lo, hi int
   278  		if i == 0 {
   279  			lo, hi = 0, (len(input)+1)/2
   280  		} else {
   281  			lo, hi = (len(input)+1)/2, len(input)
   282  		}
   283  		t.Logf("#%d: write %d-%d", i, lo, hi)
   284  		if _, err := w.Write(input[lo:hi]); err != nil {
   285  			t.Errorf("testSync: write: %v", err)
   286  			return
   287  		}
   288  		if i == 0 {
   289  			if err := w.Flush(); err != nil {
   290  				t.Errorf("testSync: flush: %v", err)
   291  				return
   292  			}
   293  		} else {
   294  			if err := w.Close(); err != nil {
   295  				t.Errorf("testSync: close: %v", err)
   296  			}
   297  		}
   298  		buf.ReadMode()
   299  		out := make([]byte, hi-lo+1)
   300  		m, err := io.ReadAtLeast(r, out, hi-lo)
   301  		t.Logf("#%d: read %d", i, m)
   302  		if m != hi-lo || err != nil {
   303  			t.Errorf("testSync/%d (%d, %d, %s): read %d: %d, %v (%d left)", i, level, len(input), name, hi-lo, m, err, buf.buf.Len())
   304  			return
   305  		}
   306  		if !bytes.Equal(input[lo:hi], out[:hi-lo]) {
   307  			t.Errorf("testSync/%d: read wrong bytes: %x vs %x", i, input[lo:hi], out[:hi-lo])
   308  			return
   309  		}
   310  		// This test originally checked that after reading
   311  		// the first half of the input, there was nothing left
   312  		// in the read buffer (buf.buf.Len() != 0) but that is
   313  		// not necessarily the case: the write Flush may emit
   314  		// some extra framing bits that are not necessary
   315  		// to process to obtain the first half of the uncompressed
   316  		// data. The test ran correctly most of the time, because
   317  		// the background goroutine had usually read even
   318  		// those extra bits by now, but it's not a useful thing to
   319  		// check.
   320  		buf.WriteMode()
   321  	}
   322  	buf.ReadMode()
   323  	out := make([]byte, 10)
   324  	if n, err := r.Read(out); n > 0 || err != io.EOF {
   325  		t.Errorf("testSync (%d, %d, %s): final Read: %d, %v (hex: %x)", level, len(input), name, n, err, out[0:n])
   326  	}
   327  	if buf.buf.Len() != 0 {
   328  		t.Errorf("testSync (%d, %d, %s): extra data at end", level, len(input), name)
   329  	}
   330  	r.Close()
   331  
   332  	// stream should work for ordinary reader too
   333  	r = NewReader(buf1)
   334  	out, err = io.ReadAll(r)
   335  	if err != nil {
   336  		t.Errorf("testSync: read: %s", err)
   337  		return
   338  	}
   339  	r.Close()
   340  	if !bytes.Equal(input, out) {
   341  		t.Errorf("testSync: decompress(compress(data)) != data: level=%d input=%s", level, name)
   342  	}
   343  }
   344  
   345  func testToFromWithLevelAndLimit(t *testing.T, level int, input []byte, name string, limit int) {
   346  	var buffer bytes.Buffer
   347  	w, err := NewWriter(&buffer, level)
   348  	if err != nil {
   349  		t.Errorf("NewWriter: %v", err)
   350  		return
   351  	}
   352  	w.Write(input)
   353  	w.Close()
   354  	if limit > 0 {
   355  		t.Logf("level: %d - Size:%.2f%%, %d b\n", level, float64(buffer.Len()*100)/float64(limit), buffer.Len())
   356  	}
   357  	if limit > 0 && buffer.Len() > limit {
   358  		t.Errorf("level: %d, len(compress(data)) = %d > limit = %d", level, buffer.Len(), limit)
   359  	}
   360  
   361  	r := NewReader(&buffer)
   362  	out, err := io.ReadAll(r)
   363  	if err != nil {
   364  		t.Errorf("read: %s", err)
   365  		return
   366  	}
   367  	r.Close()
   368  	if !bytes.Equal(input, out) {
   369  		t.Errorf("decompress(compress(data)) != data: level=%d input=%s", level, name)
   370  		return
   371  	}
   372  	testSync(t, level, input, name)
   373  }
   374  
   375  func testToFromWithLimit(t *testing.T, input []byte, name string, limit [11]int) {
   376  	for i := range 10 {
   377  		testToFromWithLevelAndLimit(t, i, input, name, limit[i])
   378  	}
   379  	testToFromWithLevelAndLimit(t, -2, input, name, limit[10])
   380  }
   381  
   382  func TestDeflateInflate(t *testing.T) {
   383  	t.Parallel()
   384  	for i, h := range deflateInflateTests {
   385  		if testing.Short() && len(h.in) > 10000 {
   386  			continue
   387  		}
   388  		testToFromWithLimit(t, h.in, fmt.Sprintf("#%d", i), [11]int{})
   389  	}
   390  }
   391  
   392  func TestReverseBits(t *testing.T) {
   393  	for _, h := range reverseBitsTests {
   394  		if v := reverseBits(h.in, h.bitCount); v != h.out {
   395  			t.Errorf("reverseBits(%v,%v) = %v, want %v",
   396  				h.in, h.bitCount, v, h.out)
   397  		}
   398  	}
   399  }
   400  
   401  type deflateInflateStringTest struct {
   402  	filename string
   403  	label    string
   404  	limit    [11]int // Number 11 is ConstantCompression
   405  }
   406  
   407  var deflateInflateStringTests = []deflateInflateStringTest{
   408  	{
   409  		"../testdata/e.txt",
   410  		"2.718281828...",
   411  		[...]int{100018, 67900, 50960, 51150, 50930, 50790, 50790, 50790, 50790, 50790, 43683 + 100},
   412  	},
   413  	{
   414  		"../../testdata/Isaac.Newton-Opticks.txt",
   415  		"Isaac.Newton-Opticks",
   416  		[...]int{567248, 218338, 201354, 199101, 190627, 182587, 179765, 174982, 173422, 173422, 325240},
   417  	},
   418  }
   419  
   420  func TestDeflateInflateString(t *testing.T) {
   421  	t.Parallel()
   422  	if testing.Short() && testenv.Builder() == "" {
   423  		t.Skip("skipping in short mode")
   424  	}
   425  	for _, test := range deflateInflateStringTests {
   426  		gold, err := os.ReadFile(test.filename)
   427  		if err != nil {
   428  			t.Error(err)
   429  		}
   430  		testToFromWithLimit(t, gold, test.label, test.limit)
   431  
   432  		if testing.Short() {
   433  			break
   434  		}
   435  	}
   436  }
   437  
   438  func TestReaderDict(t *testing.T) {
   439  	const (
   440  		dict = "hello world"
   441  		text = "hello again world"
   442  	)
   443  	var b bytes.Buffer
   444  	w, err := NewWriter(&b, 5)
   445  	if err != nil {
   446  		t.Fatalf("NewWriter: %v", err)
   447  	}
   448  	w.Write([]byte(dict))
   449  	w.Flush()
   450  	b.Reset()
   451  	w.Write([]byte(text))
   452  	w.Close()
   453  
   454  	r := NewReaderDict(&b, []byte(dict))
   455  	data, err := io.ReadAll(r)
   456  	if err != nil {
   457  		t.Fatal(err)
   458  	}
   459  	if string(data) != "hello again world" {
   460  		t.Fatalf("read returned %q want %q", string(data), text)
   461  	}
   462  }
   463  
   464  func TestWriterDict(t *testing.T) {
   465  	const (
   466  		dict = "hello world Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
   467  		text = "hello world again Lorem ipsum dolor sit amet"
   468  	)
   469  	// This test is sensitive to algorithm changes that skip
   470  	// data in favour of speed. Higher levels are less prone to this
   471  	// so we test level 4-9.
   472  	for l := 4; l < 9; l++ {
   473  		t.Run(fmt.Sprintf("level=%d", l), func(t *testing.T) {
   474  			var b bytes.Buffer
   475  			w, err := NewWriter(&b, l)
   476  			if err != nil {
   477  				t.Fatalf("NewWriter: %v", err)
   478  			}
   479  			w.Write([]byte(dict))
   480  			w.Flush()
   481  			b.Reset()
   482  			w.Write([]byte(text))
   483  			w.Close()
   484  
   485  			var b1 bytes.Buffer
   486  			w, _ = NewWriterDict(&b1, l, []byte(dict))
   487  			w.Write([]byte(text))
   488  			w.Close()
   489  
   490  			if !bytes.Equal(b1.Bytes(), b.Bytes()) {
   491  				t.Errorf("writer wrote\n%v\n want\n%v", b1.Bytes(), b.Bytes())
   492  			}
   493  		})
   494  	}
   495  }
   496  
   497  // See https://golang.org/issue/2508
   498  func TestRegression2508(t *testing.T) {
   499  	if testing.Short() {
   500  		t.Logf("test disabled with -short")
   501  		return
   502  	}
   503  	w, err := NewWriter(io.Discard, 1)
   504  	if err != nil {
   505  		t.Fatalf("NewWriter: %v", err)
   506  	}
   507  	buf := make([]byte, 1024)
   508  	for range 131072 {
   509  		if _, err := w.Write(buf); err != nil {
   510  			t.Fatalf("writer failed: %v", err)
   511  		}
   512  	}
   513  	w.Close()
   514  }
   515  
   516  func TestWriterReset(t *testing.T) {
   517  	t.Parallel()
   518  	for level := -2; level <= 9; level++ {
   519  		if level == -1 {
   520  			level++
   521  		}
   522  		if testing.Short() && level > 1 {
   523  			break
   524  		}
   525  		w, err := NewWriter(io.Discard, level)
   526  		if err != nil {
   527  			t.Fatalf("NewWriter: %v", err)
   528  		}
   529  		buf := []byte("hello world")
   530  		n := 1024
   531  		if testing.Short() {
   532  			n = 10
   533  		}
   534  		for i := 0; i < n; i++ {
   535  			w.Write(buf)
   536  		}
   537  		w.Reset(io.Discard)
   538  
   539  		wref, err := NewWriter(io.Discard, level)
   540  		if err != nil {
   541  			t.Fatalf("NewWriter: %v", err)
   542  		}
   543  
   544  		// DeepEqual doesn't compare functions.
   545  		w.d.fill, wref.d.fill = nil, nil
   546  		w.d.step, wref.d.step = nil, nil
   547  		w.d.state, wref.d.state = nil, nil
   548  		w.d.fast, wref.d.fast = nil, nil
   549  
   550  		// hashMatch is always overwritten when used.
   551  		if w.d.tokens.n != 0 {
   552  			t.Errorf("level %d Writer not reset after Reset. %d tokens were present", level, w.d.tokens.n)
   553  		}
   554  		// As long as the length is 0, we don't care about the content.
   555  		w.d.tokens = wref.d.tokens
   556  
   557  		// We don't care if there are values in the window, as long as it is at d.index is 0
   558  		w.d.window = wref.d.window
   559  		if !reflect.DeepEqual(w, wref) {
   560  			t.Errorf("level %d Writer not reset after Reset", level)
   561  		}
   562  	}
   563  
   564  	for i := HuffmanOnly; i <= BestCompression; i++ {
   565  		testResetOutput(t, fmt.Sprintf("dict=0/level=%d", i), func(w io.Writer) (*Writer, error) { return NewWriter(w, i) })
   566  	}
   567  	dict := []byte(strings.Repeat("we are the world - how are you?", 3))
   568  	for i := HuffmanOnly; i <= BestCompression; i++ {
   569  		testResetOutput(t, fmt.Sprintf("dict=1/level=%d", i), func(w io.Writer) (*Writer, error) { return NewWriterDict(w, i, dict) })
   570  	}
   571  }
   572  
   573  func testResetOutput(t *testing.T, name string, newWriter func(w io.Writer) (*Writer, error)) {
   574  	t.Run(name, func(t *testing.T) {
   575  		buf := new(bytes.Buffer)
   576  		w, err := newWriter(buf)
   577  		if err != nil {
   578  			t.Fatalf("NewWriter: %v", err)
   579  		}
   580  		b := []byte("hello world - how are you doing?")
   581  		for range 1024 {
   582  			w.Write(b)
   583  		}
   584  		w.Close()
   585  		out1 := buf.Bytes()
   586  
   587  		buf2 := new(bytes.Buffer)
   588  		w.Reset(buf2)
   589  		for range 1024 {
   590  			w.Write(b)
   591  		}
   592  		w.Close()
   593  		out2 := buf2.Bytes()
   594  
   595  		if len(out1) != len(out2) {
   596  			t.Errorf("got %d, expected %d bytes", len(out2), len(out1))
   597  			return
   598  		}
   599  		if !bytes.Equal(out1, out2) {
   600  			mm := 0
   601  			for i, b := range out1[:len(out2)] {
   602  				if b != out2[i] {
   603  					t.Errorf("mismatch index %d: %02x, expected %02x", i, out2[i], b)
   604  				}
   605  				mm++
   606  				if mm == 10 {
   607  					t.Fatal("Stopping")
   608  				}
   609  			}
   610  		}
   611  		t.Logf("got %d bytes", len(out1))
   612  	})
   613  }
   614  
   615  // TestBestSpeed tests that round-tripping through deflate and then inflate
   616  // recovers the original input. The Write sizes are near the thresholds in the
   617  // compressor.encSpeed method (0, 16, 128), as well as near maxStoreBlockSize
   618  // (65535).
   619  func TestBestSpeed(t *testing.T) {
   620  	t.Parallel()
   621  	abc := make([]byte, 128)
   622  	for i := range abc {
   623  		abc[i] = byte(i)
   624  	}
   625  	abcabc := bytes.Repeat(abc, 131072/len(abc))
   626  	var want []byte
   627  
   628  	testCases := [][]int{
   629  		{65536, 0},
   630  		{65536, 1},
   631  		{65536, 1, 256},
   632  		{65536, 1, 65536},
   633  		{65536, 14},
   634  		{65536, 15},
   635  		{65536, 16},
   636  		{65536, 16, 256},
   637  		{65536, 16, 65536},
   638  		{65536, 127},
   639  		{65536, 128},
   640  		{65536, 128, 256},
   641  		{65536, 128, 65536},
   642  		{65536, 129},
   643  		{65536, 65536, 256},
   644  		{65536, 65536, 65536},
   645  	}
   646  
   647  	for i, tc := range testCases {
   648  		if testing.Short() && i >= 6 {
   649  			break
   650  		}
   651  		for _, firstN := range []int{1, 65534, 65535, 65536, 65537, 131072} {
   652  			tc[0] = firstN
   653  		outer:
   654  			for _, flush := range []bool{false, true} {
   655  				buf := new(bytes.Buffer)
   656  				want = want[:0]
   657  
   658  				w, err := NewWriter(buf, BestSpeed)
   659  				if err != nil {
   660  					t.Errorf("i=%d, firstN=%d, flush=%t: NewWriter: %v", i, firstN, flush, err)
   661  					continue
   662  				}
   663  				for _, n := range tc {
   664  					want = append(want, abcabc[:n]...)
   665  					if _, err := w.Write(abcabc[:n]); err != nil {
   666  						t.Errorf("i=%d, firstN=%d, flush=%t: Write: %v", i, firstN, flush, err)
   667  						continue outer
   668  					}
   669  					if !flush {
   670  						continue
   671  					}
   672  					if err := w.Flush(); err != nil {
   673  						t.Errorf("i=%d, firstN=%d, flush=%t: Flush: %v", i, firstN, flush, err)
   674  						continue outer
   675  					}
   676  				}
   677  				if err := w.Close(); err != nil {
   678  					t.Errorf("i=%d, firstN=%d, flush=%t: Close: %v", i, firstN, flush, err)
   679  					continue
   680  				}
   681  
   682  				r := NewReader(buf)
   683  				got, err := io.ReadAll(r)
   684  				if err != nil {
   685  					t.Errorf("i=%d, firstN=%d, flush=%t: ReadAll: %v", i, firstN, flush, err)
   686  					continue
   687  				}
   688  				r.Close()
   689  
   690  				if !bytes.Equal(got, want) {
   691  					t.Errorf("i=%d, firstN=%d, flush=%t: corruption during deflate-then-inflate", i, firstN, flush)
   692  					continue
   693  				}
   694  			}
   695  		}
   696  	}
   697  }
   698  
   699  var errIO = errors.New("IO error")
   700  
   701  // failWriter fails with errIO exactly at the nth call to Write.
   702  type failWriter struct{ n int }
   703  
   704  func (w *failWriter) Write(b []byte) (int, error) {
   705  	w.n--
   706  	if w.n == -1 {
   707  		return 0, errIO
   708  	}
   709  	return len(b), nil
   710  }
   711  
   712  func TestWriterPersistentWriteError(t *testing.T) {
   713  	t.Parallel()
   714  	d, err := os.ReadFile("../../testdata/Isaac.Newton-Opticks.txt")
   715  	if err != nil {
   716  		t.Fatalf("ReadFile: %v", err)
   717  	}
   718  	d = d[:10000] // Keep this test short
   719  
   720  	zw, err := NewWriter(nil, DefaultCompression)
   721  	if err != nil {
   722  		t.Fatalf("NewWriter: %v", err)
   723  	}
   724  
   725  	// Sweep over the threshold at which an error is returned.
   726  	// The variable i makes it such that the ith call to failWriter.Write will
   727  	// return errIO. Since failWriter errors are not persistent, we must ensure
   728  	// that flate.Writer errors are persistent.
   729  	for i := 0; i < 1000; i++ {
   730  		fw := &failWriter{i}
   731  		zw.Reset(fw)
   732  
   733  		_, werr := zw.Write(d)
   734  		cerr := zw.Close()
   735  		ferr := zw.Flush()
   736  		if werr != errIO && werr != nil {
   737  			t.Errorf("test %d, mismatching Write error: got %v, want %v", i, werr, errIO)
   738  		}
   739  		if cerr != errIO && fw.n < 0 {
   740  			t.Errorf("test %d, mismatching Close error: got %v, want %v", i, cerr, errIO)
   741  		}
   742  		if ferr != errIO && fw.n < 0 {
   743  			t.Errorf("test %d, mismatching Flush error: got %v, want %v", i, ferr, errIO)
   744  		}
   745  		if fw.n >= 0 {
   746  			// At this point, the failure threshold was sufficiently high enough
   747  			// that we wrote the whole stream without any errors.
   748  			return
   749  		}
   750  	}
   751  }
   752  func TestWriterPersistentFlushError(t *testing.T) {
   753  	zw, err := NewWriter(&failWriter{0}, DefaultCompression)
   754  	if err != nil {
   755  		t.Fatalf("NewWriter: %v", err)
   756  	}
   757  	flushErr := zw.Flush()
   758  	closeErr := zw.Close()
   759  	_, writeErr := zw.Write([]byte("Test"))
   760  	checkErrors([]error{closeErr, flushErr, writeErr}, errIO, t)
   761  }
   762  
   763  func TestWriterPersistentCloseError(t *testing.T) {
   764  	// If underlying writer return error on closing stream we should persistent this error across all writer calls.
   765  	zw, err := NewWriter(&failWriter{0}, DefaultCompression)
   766  	if err != nil {
   767  		t.Fatalf("NewWriter: %v", err)
   768  	}
   769  	closeErr := zw.Close()
   770  	flushErr := zw.Flush()
   771  	_, writeErr := zw.Write([]byte("Test"))
   772  	checkErrors([]error{closeErr, flushErr, writeErr}, errIO, t)
   773  
   774  	// After closing writer we should persistent "write after close" error across Flush and Write calls, but return nil
   775  	// on next Close calls.
   776  	var b bytes.Buffer
   777  	zw.Reset(&b)
   778  	err = zw.Close()
   779  	if err != nil {
   780  		t.Fatalf("First call to close returned error: %s", err)
   781  	}
   782  	err = zw.Close()
   783  	if err != nil {
   784  		t.Fatalf("Second call to close returned error: %s", err)
   785  	}
   786  
   787  	flushErr = zw.Flush()
   788  	_, writeErr = zw.Write([]byte("Test"))
   789  	checkErrors([]error{flushErr, writeErr}, errWriterClosed, t)
   790  }
   791  
   792  func checkErrors(got []error, want error, t *testing.T) {
   793  	t.Helper()
   794  	for _, err := range got {
   795  		if err != want {
   796  			t.Errorf("Error doesn't match\nWant: %s\nGot: %s", want, got)
   797  		}
   798  	}
   799  }
   800  
   801  func TestBestSpeedMatch(t *testing.T) {
   802  	t.Parallel()
   803  	cases := []struct {
   804  		previous []byte
   805  		current  []byte
   806  		t        int
   807  		s        int
   808  		want     int32
   809  	}{{
   810  		previous: []byte{0, 0, 0, 1, 2},
   811  		current:  []byte{3, 4, 5, 0, 1, 2, 3, 4, 5},
   812  		t:        -3,
   813  		s:        3,
   814  		want:     6,
   815  	}, {
   816  		previous: []byte{0, 0, 0, 1, 2},
   817  		current:  []byte{2, 4, 5, 0, 1, 2, 3, 4, 5},
   818  		t:        -3,
   819  		s:        3,
   820  		want:     3,
   821  	}, {
   822  		previous: []byte{0, 0, 0, 1, 1},
   823  		current:  []byte{3, 4, 5, 0, 1, 2, 3, 4, 5},
   824  		t:        -3,
   825  		s:        3,
   826  		want:     2,
   827  	}, {
   828  		previous: []byte{0, 0, 0, 1, 2},
   829  		current:  []byte{2, 2, 2, 2, 1, 2, 3, 4, 5},
   830  		t:        -1,
   831  		s:        0,
   832  		want:     4,
   833  	}, {
   834  		previous: []byte{0, 0, 0, 1, 2, 3, 4, 5, 2, 2},
   835  		current:  []byte{2, 2, 2, 2, 1, 2, 3, 4, 5},
   836  		t:        -7,
   837  		s:        4,
   838  		want:     5,
   839  	}, {
   840  		previous: []byte{9, 9, 9, 9, 9},
   841  		current:  []byte{2, 2, 2, 2, 1, 2, 3, 4, 5},
   842  		t:        -1,
   843  		s:        0,
   844  		want:     0,
   845  	}, {
   846  		previous: []byte{9, 9, 9, 9, 9},
   847  		current:  []byte{9, 2, 2, 2, 1, 2, 3, 4, 5},
   848  		t:        0,
   849  		s:        1,
   850  		want:     0,
   851  	}, {
   852  		previous: []byte{},
   853  		current:  []byte{2, 2, 2, 2, 1, 2, 3, 4, 5},
   854  		t:        0,
   855  		s:        1,
   856  		want:     3,
   857  	}, {
   858  		previous: []byte{3, 4, 5},
   859  		current:  []byte{3, 4, 5},
   860  		t:        -3,
   861  		s:        0,
   862  		want:     3,
   863  	}, {
   864  		previous: make([]byte, 1000),
   865  		current:  make([]byte, 1000),
   866  		t:        -1000,
   867  		s:        0,
   868  		want:     maxMatchLength - 4,
   869  	}, {
   870  		previous: make([]byte, 200),
   871  		current:  make([]byte, 500),
   872  		t:        -200,
   873  		s:        0,
   874  		want:     maxMatchLength - 4,
   875  	}, {
   876  		previous: make([]byte, 200),
   877  		current:  make([]byte, 500),
   878  		t:        0,
   879  		s:        1,
   880  		want:     maxMatchLength - 4,
   881  	}, {
   882  		previous: make([]byte, maxMatchLength-4),
   883  		current:  make([]byte, 500),
   884  		t:        -(maxMatchLength - 4),
   885  		s:        0,
   886  		want:     maxMatchLength - 4,
   887  	}, {
   888  		previous: make([]byte, 200),
   889  		current:  make([]byte, 500),
   890  		t:        -200,
   891  		s:        400,
   892  		want:     100,
   893  	}, {
   894  		previous: make([]byte, 10),
   895  		current:  make([]byte, 500),
   896  		t:        200,
   897  		s:        400,
   898  		want:     100,
   899  	}}
   900  	for i, c := range cases {
   901  		t.Run(strconv.Itoa(i), func(t *testing.T) {
   902  			var e fastGen
   903  			e.addBlock(c.previous)
   904  			e.addBlock(c.current)
   905  			got := e.matchLenLimited(c.s+len(c.previous), c.t+len(c.previous), e.hist)
   906  			if got != c.want {
   907  				t.Errorf("Test %d: match length, want %d, got %d", i, c.want, got)
   908  			}
   909  		})
   910  	}
   911  }
   912  
   913  func TestBestSpeedMaxMatchOffset(t *testing.T) {
   914  	t.Parallel()
   915  	const abc, xyz = "abcdefgh", "stuvwxyz"
   916  	const inputMargin = 16 - 1
   917  	for _, matchBefore := range []bool{false, true} {
   918  		for _, extra := range []int{0, inputMargin - 1, inputMargin, inputMargin + 1, 2 * inputMargin} {
   919  			for offsetAdj := -5; offsetAdj <= +5; offsetAdj++ {
   920  				report := func(desc string, err error) {
   921  					t.Errorf("matchBefore=%t, extra=%d, offsetAdj=%d: %s%v",
   922  						matchBefore, extra, offsetAdj, desc, err)
   923  				}
   924  
   925  				offset := maxMatchOffset + offsetAdj
   926  
   927  				// Make src to be a []byte of the form
   928  				//	"%s%s%s%s%s" % (abc, zeros0, xyzMaybe, abc, zeros1)
   929  				// where:
   930  				//	zeros0 is approximately maxMatchOffset zeros.
   931  				//	xyzMaybe is either xyz or the empty string.
   932  				//	zeros1 is between 0 and 30 zeros.
   933  				// The difference between the two abc's will be offset, which
   934  				// is maxMatchOffset plus or minus a small adjustment.
   935  				src := make([]byte, offset+len(abc)+extra)
   936  				copy(src, abc)
   937  				if !matchBefore {
   938  					copy(src[offset-len(xyz):], xyz)
   939  				}
   940  				copy(src[offset:], abc)
   941  
   942  				buf := new(bytes.Buffer)
   943  				w, err := NewWriter(buf, BestSpeed)
   944  				if err != nil {
   945  					report("NewWriter: ", err)
   946  					continue
   947  				}
   948  				if _, err := w.Write(src); err != nil {
   949  					report("Write: ", err)
   950  					continue
   951  				}
   952  				if err := w.Close(); err != nil {
   953  					report("Writer.Close: ", err)
   954  					continue
   955  				}
   956  
   957  				r := NewReader(buf)
   958  				dst, err := io.ReadAll(r)
   959  				r.Close()
   960  				if err != nil {
   961  					report("ReadAll: ", err)
   962  					continue
   963  				}
   964  
   965  				if !bytes.Equal(dst, src) {
   966  					report("", fmt.Errorf("bytes differ after round-tripping"))
   967  					continue
   968  				}
   969  			}
   970  		}
   971  	}
   972  }
   973  
   974  type canGetFastGen interface {
   975  	getFastGen() *fastGen
   976  }
   977  
   978  func TestBestSpeedShiftOffsets(t *testing.T) {
   979  	// Test if shiftoffsets properly preserves matches and resets out-of-range matches
   980  	// seen in https://github.com/golang/go/issues/4142
   981  
   982  	for level := 1; level <= 6; level++ {
   983  		t.Run(fmt.Sprintf("level=%d", level), func(t *testing.T) {
   984  			enc := newFastEnc(level)
   985  
   986  			// testData may not generate internal matches.
   987  			testData := make([]byte, 100)
   988  			rng := rand.New(rand.NewSource(0))
   989  			for i := range testData {
   990  				testData[i] = byte(rng.Uint32())
   991  			}
   992  			valOrLen := func(val uint16) uint16 {
   993  				if val == 0 {
   994  					return uint16(len(testData))
   995  				}
   996  				return val
   997  			}
   998  			// Encode the testdata with clean state.
   999  			// Second part should pick up matches from the first block.
  1000  			var firstTokens, secondTokens tokens
  1001  			enc.encode(&firstTokens, testData)
  1002  			enc.encode(&secondTokens, testData)
  1003  			wantFirstTokens := valOrLen(firstTokens.n)
  1004  			wantSecondTokens := valOrLen(secondTokens.n)
  1005  
  1006  			if wantFirstTokens <= wantSecondTokens {
  1007  				t.Fatalf("test needs matches between inputs to be generated, %d == %d", wantFirstTokens, wantSecondTokens)
  1008  			}
  1009  			// Forward the current indicator to before wraparound.
  1010  			fg := enc.(canGetFastGen).getFastGen()
  1011  			fg.hist = nil
  1012  			fg.cur = bufferReset - int32(len(testData))
  1013  
  1014  			// Part 1 before wrap, should match clean state.
  1015  			var gotTokens tokens
  1016  			enc.encode(&gotTokens, testData)
  1017  			got := valOrLen(gotTokens.n)
  1018  			if wantFirstTokens != got {
  1019  				t.Errorf("got %d, want %d tokens", got, wantFirstTokens)
  1020  			}
  1021  
  1022  			// Verify we are about to wrap.
  1023  			gotCur := int(fg.cur) + len(fg.hist)
  1024  			if gotCur != bufferReset {
  1025  				t.Errorf("got %d, want e.cur to be at bufferReset (%d)", gotCur, bufferReset)
  1026  			}
  1027  
  1028  			// Part 2 should match clean state as well even if wrapped.
  1029  			gotTokens.Reset()
  1030  			enc.encode(&gotTokens, testData)
  1031  			got = valOrLen(gotTokens.n)
  1032  			if wantSecondTokens != got {
  1033  				t.Errorf("got %d, want %d token", got, wantSecondTokens)
  1034  			}
  1035  
  1036  			// Verify that we wrapped.
  1037  			if fg.cur >= bufferReset {
  1038  				t.Errorf("want e.cur to be < bufferReset (%d), got %d", bufferReset, fg.cur)
  1039  			}
  1040  
  1041  			// Forward the current buffer, leaving the matches at the bottom.
  1042  			fg.cur = bufferReset
  1043  			fg.hist = nil
  1044  
  1045  			// Ensure that no matches were picked up.
  1046  			gotTokens.Reset()
  1047  			enc.encode(&gotTokens, testData)
  1048  			got = valOrLen(gotTokens.n)
  1049  			if wantFirstTokens != got {
  1050  				t.Errorf("got %d, want %d tokens", got, wantFirstTokens)
  1051  			}
  1052  		})
  1053  	}
  1054  }
  1055  
  1056  func TestMaxStackSize(t *testing.T) {
  1057  	// This test must not run in parallel with other tests as debug.SetMaxStack
  1058  	// affects all goroutines.
  1059  	n := debug.SetMaxStack(1 << 16)
  1060  	defer debug.SetMaxStack(n)
  1061  
  1062  	var wg sync.WaitGroup
  1063  	defer wg.Wait()
  1064  
  1065  	b := make([]byte, 1<<20)
  1066  	for level := HuffmanOnly; level <= BestCompression; level++ {
  1067  		// Run in separate goroutine to increase probability of stack regrowth.
  1068  		wg.Add(1)
  1069  		go func(level int) {
  1070  			defer wg.Done()
  1071  			zw, err := NewWriter(io.Discard, level)
  1072  			if err != nil {
  1073  				t.Errorf("level %d, NewWriter() = %v, want nil", level, err)
  1074  			}
  1075  			if n, err := zw.Write(b); n != len(b) || err != nil {
  1076  				t.Errorf("level %d, Write() = (%d, %v), want (%d, nil)", level, n, err, len(b))
  1077  			}
  1078  			if err := zw.Close(); err != nil {
  1079  				t.Errorf("level %d, Close() = %v, want nil", level, err)
  1080  			}
  1081  			zw.Reset(io.Discard)
  1082  		}(level)
  1083  	}
  1084  }
  1085  

View as plain text