File: swizzle_test.go

package info (click to toggle)
golang-golang-x-exp 0.0~git20230522.2e198f4-1~bpo12%2B1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-backports
  • size: 6,404 kB
  • sloc: ansic: 1,900; objc: 276; sh: 272; asm: 48; makefile: 26
file content (86 lines) | stat: -rw-r--r-- 1,989 bytes parent folder | download | duplicates (6)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
// Copyright 2015 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package swizzle

import (
	"bytes"
	"math/rand"
	"testing"
)

func TestBGRAShortInput(t *testing.T) {
	const s = "012.456.89A.CDE.GHI.KLM.O"
	testCases := []string{
		0: "012.456.89A.CDE.GHI.KLM.O",
		1: "210.456.89A.CDE.GHI.KLM.O",
		2: "210.654.89A.CDE.GHI.KLM.O",
		3: "210.654.A98.CDE.GHI.KLM.O",
		4: "210.654.A98.EDC.GHI.KLM.O",
		5: "210.654.A98.EDC.IHG.KLM.O",
		6: "210.654.A98.EDC.IHG.MLK.O",
	}
	for i, want := range testCases {
		b := []byte(s)
		BGRA(b[:4*i])
		got := string(b)
		if got != want {
			t.Errorf("i=%d: got %q, want %q", i, got, want)
		}
		changed := got != s
		wantChanged := i != 0
		if changed != wantChanged {
			t.Errorf("i=%d: changed=%t, want %t", i, changed, wantChanged)
		}
	}
}

func TestBGRARandomInput(t *testing.T) {
	r := rand.New(rand.NewSource(1))
	fastBuf := make([]byte, 1024)
	slowBuf := make([]byte, 1024)
	for i := range fastBuf {
		fastBuf[i] = uint8(r.Intn(256))
	}
	copy(slowBuf, fastBuf)

	for i := 0; i < 100000; i++ {
		o := r.Intn(len(fastBuf))
		n := r.Intn(len(fastBuf)-o) &^ 0x03
		BGRA(fastBuf[o : o+n])
		pureGoBGRA(slowBuf[o : o+n])
		if bytes.Equal(fastBuf, slowBuf) {
			continue
		}
		for j := range fastBuf {
			x := fastBuf[j]
			y := slowBuf[j]
			if x != y {
				t.Fatalf("iter %d: swizzling [%d:%d+%d]: bytes differ at offset %d (aka %d+%d): %#02x vs %#02x",
					i, o, o, n, j, o, j-o, x, y)
			}
		}
	}
}

func pureGoBGRA(p []byte) {
	if len(p)%4 != 0 {
		return
	}
	for i := 0; i < len(p); i += 4 {
		p[i+0], p[i+2] = p[i+2], p[i+0]
	}
}

func benchmarkBGRA(b *testing.B, f func([]byte)) {
	const w, h = 1920, 1080 // 1080p RGBA.
	buf := make([]byte, 4*w*h)
	b.ResetTimer()
	for i := 0; i < b.N; i++ {
		f(buf)
	}
}

func BenchmarkBGRA(b *testing.B)       { benchmarkBGRA(b, BGRA) }
func BenchmarkPureGoBGRA(b *testing.B) { benchmarkBGRA(b, pureGoBGRA) }