Skip to content

Commit 6318dab

Browse files
committed
xts: avoid redundant bounds checks
Small changes to improve performance of xts by about 6%. This removes all bounds checks, which can be verified by running: go build -gcflags="-d=ssa/check_bce/debug=1" . Before this would show mutiple Found IsInBounds/IsSliceInBounds in the inner loops of Encrypt and Decrypt. Tweaked the benchmark to use a larger buffer to make the improvement more visible. XTS is often used with disk sector sizes, so larger values are appropriate. goos: linux goarch: amd64 pkg: golang.org/x/crypto/xts cpu: Intel(R) Xeon(R) W-2135 CPU @ 3.70GHz │ before.txt │ after.txt │ │ sec/op │ sec/op vs base │ XTS-12 1.720µ ± 2% 1.619µ ± 2% -5.87% (p=0.000 n=10) │ before.txt │ after.txt │ │ B/s │ B/s vs base │ XTS-12 177.4Mi ± 2% 188.5Mi ± 2% +6.24% (p=0.000 n=10) │ before.txt │ after.txt │ │ B/op │ B/op vs base │ XTS-12 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ ¹ all samples are equal │ before.txt │ after.txt │ │ allocs/op │ allocs/op vs base │ XTS-12 0.000 ± 0% 0.000 ± 0% ~ (p=1.000 n=10) ¹ ¹ all samples are equal
1 parent b61b08d commit 6318dab

File tree

2 files changed

+6
-5
lines changed

2 files changed

+6
-5
lines changed

xts/xts.go

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ func (c *Cipher) Encrypt(ciphertext, plaintext []byte, sectorNum uint64) {
8787

8888
c.k2.Encrypt(tweak[:], tweak[:])
8989

90-
for len(plaintext) > 0 {
90+
for len(plaintext) >= blockSize && len(ciphertext) >= blockSize {
9191
for j := range tweak {
9292
ciphertext[j] = plaintext[j] ^ tweak[j]
9393
}
@@ -126,7 +126,7 @@ func (c *Cipher) Decrypt(plaintext, ciphertext []byte, sectorNum uint64) {
126126

127127
c.k2.Encrypt(tweak[:], tweak[:])
128128

129-
for len(ciphertext) > 0 {
129+
for len(ciphertext) >= blockSize && len(plaintext) >= blockSize {
130130
for j := range tweak {
131131
plaintext[j] = ciphertext[j] ^ tweak[j]
132132
}

xts/xts_test.go

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -106,13 +106,14 @@ func TestShorterCiphertext(t *testing.T) {
106106

107107
func BenchmarkXTS(b *testing.B) {
108108
b.ReportAllocs()
109+
b.SetBytes(320)
109110
c, err := NewCipher(aes.NewCipher, make([]byte, 32))
110111
if err != nil {
111112
b.Fatalf("NewCipher failed: %s", err)
112113
}
113-
plaintext := make([]byte, 32)
114-
encrypted := make([]byte, 48)
115-
decrypted := make([]byte, 48)
114+
plaintext := make([]byte, 320)
115+
encrypted := make([]byte, 336)
116+
decrypted := make([]byte, 336)
116117

117118
for i := 0; i < b.N; i++ {
118119
c.Encrypt(encrypted, plaintext, 0)

0 commit comments

Comments
 (0)