util.go 846 B

123456789101112131415161718192021222324252627282930313233343536
  1. // SPDX-FileCopyrightText: 2023 The Pion community <https://pion.ly>
  2. // SPDX-License-Identifier: MIT
  3. package srtp
  4. import "bytes"
  5. // Grow the buffer size to the given number of bytes.
  6. func growBufferSize(buf []byte, size int) []byte {
  7. if size <= cap(buf) {
  8. return buf[:size]
  9. }
  10. buf2 := make([]byte, size)
  11. copy(buf2, buf)
  12. return buf2
  13. }
  14. // Check if buffers match, if not allocate a new buffer and return it
  15. func allocateIfMismatch(dst, src []byte) []byte {
  16. if dst == nil {
  17. dst = make([]byte, len(src))
  18. copy(dst, src)
  19. } else if !bytes.Equal(dst, src) { // bytes.Equal returns on ref equality, no optimization needed
  20. extraNeeded := len(src) - len(dst)
  21. if extraNeeded > 0 {
  22. dst = append(dst, make([]byte, extraNeeded)...)
  23. } else if extraNeeded < 0 {
  24. dst = dst[:len(dst)+extraNeeded]
  25. }
  26. copy(dst, src)
  27. }
  28. return dst
  29. }