git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/httpx/webapphandler_test.go (about)

     1  package httpx
     2  
     3  import (
     4  	"encoding/base64"
     5  	"strconv"
     6  	"testing"
     7  
     8  	"github.com/zeebo/blake3"
     9  )
    10  
    11  // func TestWebapphandlerTypes(t *testing.T) {
    12  // 	var fileInfo webappFileInfo
    13  // 	fmt.Printf("size(webappFileInfo): %d\n", unsafe.Sizeof(fileInfo))
    14  // }
    15  
    16  func TestEncodeEtagOptimized(t *testing.T) {
    17  	elems := []struct {
    18  		Input    string
    19  		Expected string
    20  		Hash     [32]byte
    21  	}{
    22  		{
    23  			Input:    "1",
    24  			Expected: "",
    25  		},
    26  		{
    27  			Input:    "2",
    28  			Expected: "",
    29  		},
    30  		{
    31  			Input:    "3",
    32  			Expected: "",
    33  		},
    34  		{
    35  			Input:    "Hello World!",
    36  			Expected: "",
    37  		},
    38  	}
    39  	for i := range elems {
    40  		elems[i].Hash = blake3.Sum256([]byte(elems[i].Input))
    41  		elems[i].Expected = strconv.Quote(base64.RawURLEncoding.EncodeToString(elems[i].Hash[:]))
    42  	}
    43  
    44  	for _, elem := range elems {
    45  		value := encodeEtagOptimized(elem.Hash)
    46  		if value != elem.Expected {
    47  			t.Errorf("expected: %s | got: %s | input: %s\n", elem.Expected, value, elem.Input)
    48  		}
    49  	}
    50  }
    51  
    52  func BenchmarkEncodeEtagOptimized(b *testing.B) {
    53  	hash := blake3.Sum256([]byte("Hello World!"))
    54  
    55  	b.Run("strconv.Quote(base64.RawURLEncoding.EncodeToString(hash))", func(b *testing.B) {
    56  		b.ReportAllocs()
    57  		b.SetBytes(int64(len(hash)))
    58  		b.ResetTimer()
    59  		for i := 0; i < b.N; i++ {
    60  			strconv.Quote(base64.RawURLEncoding.EncodeToString(hash[:]))
    61  		}
    62  	})
    63  
    64  	b.Run("encodeEtag(hash)", func(b *testing.B) {
    65  		b.ReportAllocs()
    66  		b.SetBytes(int64(len(hash)))
    67  		b.ResetTimer()
    68  		for i := 0; i < b.N; i++ {
    69  			encodeEtagOptimized(hash)
    70  		}
    71  	})
    72  
    73  	// b.Run("toEtagPlus(hash)", func(b *testing.B) {
    74  	// 	b.ReportAllocs()
    75  	// 	b.SetBytes(int64(len(hash)))
    76  	// 	b.ResetTimer()
    77  	// 	for i := 0; i < b.N; i++ {
    78  	// 		toEtagPlus(hash)
    79  	// 	}
    80  	// })
    81  }