github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/exp/shiny/driver/internal/swizzle/swizzle_test.go (about)

     1  // Copyright 2015 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 swizzle
     6  
     7  import (
     8  	"bytes"
     9  	"math/rand"
    10  	"testing"
    11  )
    12  
    13  func TestBGRAShortInput(t *testing.T) {
    14  	const s = "012.456.89A.CDE.GHI.KLM.O"
    15  	testCases := []string{
    16  		0: "012.456.89A.CDE.GHI.KLM.O",
    17  		1: "210.456.89A.CDE.GHI.KLM.O",
    18  		2: "210.654.89A.CDE.GHI.KLM.O",
    19  		3: "210.654.A98.CDE.GHI.KLM.O",
    20  		4: "210.654.A98.EDC.GHI.KLM.O",
    21  		5: "210.654.A98.EDC.IHG.KLM.O",
    22  		6: "210.654.A98.EDC.IHG.MLK.O",
    23  	}
    24  	for i, want := range testCases {
    25  		b := []byte(s)
    26  		BGRA(b[:4*i])
    27  		got := string(b)
    28  		if got != want {
    29  			t.Errorf("i=%d: got %q, want %q", i, got, want)
    30  		}
    31  		changed := got != s
    32  		wantChanged := i != 0
    33  		if changed != wantChanged {
    34  			t.Errorf("i=%d: changed=%t, want %t", i, changed, wantChanged)
    35  		}
    36  	}
    37  }
    38  
    39  func TestBGRARandomInput(t *testing.T) {
    40  	r := rand.New(rand.NewSource(1))
    41  	fastBuf := make([]byte, 1024)
    42  	slowBuf := make([]byte, 1024)
    43  	for i := range fastBuf {
    44  		fastBuf[i] = uint8(r.Intn(256))
    45  	}
    46  	copy(slowBuf, fastBuf)
    47  
    48  	for i := 0; i < 100000; i++ {
    49  		o := r.Intn(len(fastBuf))
    50  		n := r.Intn(len(fastBuf)-o) &^ 0x03
    51  		BGRA(fastBuf[o : o+n])
    52  		pureGoBGRA(slowBuf[o : o+n])
    53  		if bytes.Equal(fastBuf, slowBuf) {
    54  			continue
    55  		}
    56  		for j := range fastBuf {
    57  			x := fastBuf[j]
    58  			y := slowBuf[j]
    59  			if x != y {
    60  				t.Fatalf("iter %d: swizzling [%d:%d+%d]: bytes differ at offset %d (aka %d+%d): %#02x vs %#02x",
    61  					i, o, o, n, j, o, j-o, x, y)
    62  			}
    63  		}
    64  	}
    65  }
    66  
    67  func pureGoBGRA(p []byte) {
    68  	if len(p)%4 != 0 {
    69  		return
    70  	}
    71  	for i := 0; i < len(p); i += 4 {
    72  		p[i+0], p[i+2] = p[i+2], p[i+0]
    73  	}
    74  }
    75  
    76  func benchmarkBGRA(b *testing.B, f func([]byte)) {
    77  	const w, h = 1920, 1080 // 1080p RGBA.
    78  	buf := make([]byte, 4*w*h)
    79  	b.ResetTimer()
    80  	for i := 0; i < b.N; i++ {
    81  		f(buf)
    82  	}
    83  }
    84  
    85  func BenchmarkBGRA(b *testing.B)       { benchmarkBGRA(b, BGRA) }
    86  func BenchmarkPureGoBGRA(b *testing.B) { benchmarkBGRA(b, pureGoBGRA) }