Skip to content

Commit

Permalink
Reduce GC pressure on xorBytesCTR
Browse files Browse the repository at this point in the history
  • Loading branch information
aankur authored and Sean-Der committed Oct 2, 2024
1 parent ac17807 commit c8977fd
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions crypto.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ package srtp

import (
"crypto/cipher"
"sync"

"github.com/pion/transport/v3/utils/xor"
)
Expand All @@ -19,17 +20,30 @@ func incrementCTR(ctr []byte) {
}
}

var xorBufferPool = sync.Pool{ // nolint:gochecknoglobals
New: func() interface{} {
return make([]byte, 1500)
},
}

// xorBytesCTR performs CTR encryption and decryption.
// It is equivalent to cipher.NewCTR followed by XORKeyStream.
func xorBytesCTR(block cipher.Block, iv []byte, dst, src []byte) error {
if len(iv) != block.BlockSize() {
return errBadIVLength
}

ctr := make([]byte, len(iv))
xorBuf := xorBufferPool.Get()
defer xorBufferPool.Put(xorBuf)
buffer, ok := xorBuf.([]byte)
if !ok {
return errFailedTypeAssertion

Check warning on line 40 in crypto.go

View check run for this annotation

Codecov / codecov/patch

crypto.go#L40

Added line #L40 was not covered by tests
}

ctr := buffer[:len(iv)]
copy(ctr, iv)
bs := block.BlockSize()
stream := make([]byte, bs)
stream := buffer[len(iv) : len(iv)+bs]

i := 0
for i < len(src) {
Expand Down

0 comments on commit c8977fd

Please sign in to comment.