github.com/TeaOSLab/EdgeNode@v1.3.8/internal/compressions/reader_zstd_test.go (about)

     1  // Copyright 2022 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
     2  
     3  package compressions_test
     4  
     5  import (
     6  	"bytes"
     7  	"github.com/TeaOSLab/EdgeNode/internal/compressions"
     8  	"github.com/iwind/TeaGo/rands"
     9  	"github.com/iwind/TeaGo/types"
    10  	"io"
    11  	"strings"
    12  	"testing"
    13  )
    14  
    15  func TestZSTDReader(t *testing.T) {
    16  	for _, testString := range []string{"Hello", "World", "Ni", "Hao"} {
    17  		t.Log("===", testString, "===")
    18  		var buf = &bytes.Buffer{}
    19  		writer, err := compressions.NewZSTDWriter(buf, 5)
    20  		if err != nil {
    21  			t.Fatal(err)
    22  		}
    23  		_, err = writer.Write([]byte(testString))
    24  		if err != nil {
    25  			t.Fatal(err)
    26  		}
    27  		err = writer.Close()
    28  		if err != nil {
    29  			t.Fatal(err)
    30  		}
    31  
    32  		reader, err := compressions.NewZSTDReader(buf)
    33  		if err != nil {
    34  			t.Fatal(err)
    35  		}
    36  		var data = make([]byte, 4096)
    37  		for {
    38  			n, err := reader.Read(data)
    39  			if n > 0 {
    40  				t.Log(string(data[:n]))
    41  			}
    42  			if err != nil {
    43  				if err == io.EOF {
    44  					break
    45  				}
    46  				t.Fatal(err)
    47  			}
    48  		}
    49  		err = reader.Close()
    50  		if err != nil {
    51  			t.Fatal(err)
    52  		}
    53  	}
    54  }
    55  
    56  func BenchmarkZSTDReader(b *testing.B) {
    57  	var randomData = func() []byte {
    58  		var b = strings.Builder{}
    59  		for i := 0; i < 1024; i++ {
    60  			b.WriteString(types.String(rands.Int64() % 10))
    61  		}
    62  		return []byte(b.String())
    63  	}
    64  
    65  	var buf = &bytes.Buffer{}
    66  	writer, err := compressions.NewZSTDWriter(buf, 5)
    67  	if err != nil {
    68  		b.Fatal(err)
    69  	}
    70  	_, err = writer.Write(randomData())
    71  	if err != nil {
    72  		b.Fatal(err)
    73  	}
    74  	err = writer.Close()
    75  	if err != nil {
    76  		b.Fatal(err)
    77  	}
    78  
    79  	b.ResetTimer()
    80  
    81  	for i := 0; i < b.N; i++ {
    82  		var newBytes = make([]byte, buf.Len())
    83  		copy(newBytes, buf.Bytes())
    84  		reader, err := compressions.NewZSTDReader(bytes.NewReader(newBytes))
    85  		if err != nil {
    86  			b.Fatal(err)
    87  		}
    88  		var data = make([]byte, 4096)
    89  		for {
    90  			n, err := reader.Read(data)
    91  			if n > 0 {
    92  				_ = data[:n]
    93  			}
    94  			if err != nil {
    95  				if err == io.EOF {
    96  					break
    97  				}
    98  				b.Fatal(err)
    99  			}
   100  		}
   101  		err = reader.Close()
   102  		if err != nil {
   103  			b.Fatal(err)
   104  		}
   105  	}
   106  }